返回资讯中心
外部精选
软件工程
#开发者实时流

Ruby 开发者自建 C 风格位标志实现 BitFlags 并开源

来源标题:C-like bit flags in Ruby

Ruby 开发者因不满意现有 bit_flag gem 的 API,自行实现了一个 C 风格位标志类 BitFlags,并以 CC0 协议公开代码。该实现支持用位运算组合权限、查询标志状态,还能通过 parse 方法与 Ruby 模式匹配配合使用。

Hacker News 最新meysamazad2026/11/16 · 昨天8 分钟阅读

以下正文由 AI 翻译自 Hacker News 最新(原文版权归原站所有),可能存在偏差,重要内容请以原文为准。

我最近需要在 Ruby 里实现类似 C 的位标志。有一个 bit_flag gem 可以做这件事,但我不太喜欢它的 API。而且我觉得这么小的功能不值得引入一个依赖。于是我决定自己写一个。它的用法是这样的:

Permission = BitFlags.for(:execute, :write, :read) permissions = Permission.read | Permission.execute Permission.read?(permissions) #=> true Permission.write?(permissions) #=> false Permission.execute?(permissions) #=> true

它还能通过 parse 方法和 Ruby 的模式匹配很好地配合:

case Permission.parse(int) in [] then "none" in [:execute, :write, :read] then "all" in [:execute, :write] then "exactly execute and write" in [*, :read, *] then "has read" in [:execute] | [:write] then "only execute or write" end

我在 Mastodon 上分享了它,大家似乎挺喜欢,所以我把代码发布到了公有领域:

SPDX-License-Identifier: CC0-1.0

See: https://creativecommons.org/publicdomain/zero/1.0/deed.en

class BitFlags def self.for(names) values = names.each_with_index.to_h { |name, i| [name, 1 << i] }.freeze Class.new do define_singleton_method(:values) { values } values.each do |name, value| define_singleton_method(name) { value } define_singleton_method(:"#{name}?") { |int| int & value != 0 } end define_singleton_method(:parse) do |int| values.keys.filter { |flag| send(:"#{flag}?", int) } end end end end if FILE == $0 require "minitest/autorun" class TestFlags < Minitest::Test Permission = BitFlags.for(:execute, :write, :read) def test_values assert_equal({execute: 1, write: 2, read: 4}, Permission.values) end def test_accessors assert_equal 4, Permission.read assert_equal 2, Permission.write assert_equal 1, Permission.execute end def test_predicates permissions = Permission.read | Permission.execute assert Permission.read?(permissions) refute Permission.write?(permissions) assert Permission.execute?(permissions) end def test_parse permissions = Permission.read | Permission.execute assert_equal Permission.parse(permissions), [:execute, :read] end def test_pattern_matching_on_parse match = ->(int) { case Permission.parse(int) in [] then "none" in [:execute, :write, :read] then "all" in [:execute, :write] then "exactly execute and write" in [, :read, *] then "has read" in [:execute] | [:write] then "only execute or write" end assert_equal "none", match.call(0) assert_equal "all", match.call(7) assert_equal "exactly execute and write", match.call(3) assert_equal "has read", match.call(5) assert_equal "only execute or write", match.call(2) end end end

你也可以下载这个文件,然后用 ruby bit_flags.rb 运行测试。

你可能会好奇,我为什么不把它作为 gem 发布。简而言之:我觉得不值得。代码很短,也容易理解。把它复制进你的项目,按你的喜好重命名(也许你更愿意叫它 FlagEnum),如果愿意就把测试移到单独的文件里,然后不必担心供应链安全、.gemspec 里随意的版本约束,或者其他与你真正要解决的问题无关的事情。

也许应该有一个站点来收集这样的单文件库。但那是另一个问题了。

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →