【发布时间】:2016-09-28 19:56:35
【问题描述】:
我正在尝试为包含模块的类进行类似 DSL 的配置,但要使配置的变量对类和实例方法都可用,似乎需要在模块中乱扔访问方法。有没有更优雅的方法来做到这一点?
module DogMixin
class << self
def included(base)
base.extend ClassMethods
end
end
module ClassMethods
def breed(value)
@dog_breed = value
end
def dog_breed
@dog_breed
end
end
end
class Foo
include DogMixin
breed :havanese
end
puts Foo.dog_breed
# not implemented but should be able to do this as well
f = Foo.new
f.dog_breed
【问题讨论】:
-
我还没有完全理解这个问题。你期待
f = Foo.new; f.dog_breed = :chimp; puts Foo.dog_breed的输出是什么?类中的哪些常量对您有帮助?
标签: ruby configuration