所以我想我想出了一个替代方案:
class Object
def typedef &block
Module.new &block
end
end
module Type
@@types = []
@@prev = Module.constants
def self.existing_types
diff = Module.constants - @@prev
@@prev = Module.constants
new_types = diff.select { |const| const.to_s.start_with? 'TYPE_' }
@@types |= new_types
end
end
我没有监控何时创建常量,而是在访问常量列表时对其进行处理。所以现在我可以做这样的事情:
irb(main):002:0> Type.existing_types
=> []
irb(main):003:0> TYPE_rock = typedef do
irb(main):004:1* def self.crumble
irb(main):005:2> puts "I'm crumbling! D:"
irb(main):006:2> end
irb(main):007:1> end
=> TYPE_rock
irb(main):008:0> Type.existing_types
=> [:TYPE_rock]
irb(main):009:0> FOO_CONST = 54
=> 54
irb(main):011:0> TYPE_water = typedef do
irb(main):012:1* def self.splash
irb(main):013:2> puts "Water! :3"
irb(main):014:2> end
irb(main):015:1> end
=> TYPE_water
irb(main):016:0> Type.existing_types
=> [:TYPE_rock, :TYPE_water]
irb(main):017:0> TYPE_rock.crumble
I'm crumbling! D:
=> nil
irb(main):018:0> TYPE_water.splash
Water! :3
=> nil
你怎么看?这完成了我想要的,而且相当简单,但我对 Ruby 还是很陌生,我不确定 Ruby 是否已经提供了一些不错的 API 来执行此操作。