我試圖做一個類似DSL配置的類包含一個模塊,但配置變量可用於類和實例方法似乎需要亂拋垃圾訪問方法的模塊。有沒有更優雅的方式來做到這一點?ruby類實例變量配置模式
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 =:黑猩猩;放Foo.dog_breed'?班上有哪些常數可以幫助你? – Felix