2016-09-28 89 views
1

我試圖做一個類似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 
+0

我還沒有完全明白這個問題。你希望從f = Foo.new得到什麼結果; f.dog_breed =:黑猩猩;放Foo.dog_breed'?班上有哪些常數可以幫助你? – Felix

回答

1

你的例子是有點不可思議,我認爲:) 總之,要避免寫的存取的一種方式(該分配 - 訪問是在我的眼前問題 - 尤其是在給定的例子)是定義常量如下例所示。但是,如果你需要運行時分配,請編輯你的問題(並因此使這個回答無效:),除非你想弄亂運行時常量賦值,這可能但是混亂)。

module DogMixin 
    # **include** DogMixin to get `Class.dog_breed` 
    class << self 
    def included(base) 
     def base.dog_breed 
     self::DOG_BREED || "pug" 
     end 
    end 
    end 

    # **extend** DogMixin to get `instance.dog_breed` 
    def dog_breed 
    self.class.const_get(:DOG_BREED) || "pug" 
    end 
end 

class Foomer 
    DOG_BREED = 'foomer' 
    extend DogMixin 
    include DogMixin 
end 

f = Foomer.new 
puts Foomer.dog_breed 
puts f.dog_breed 

# If I understand you correctly, this is the most important (?): 
f.dog_breed == Foomer.dog_breed #=> true 

花的(In Ruby) allowing mixed-in class methods access to class constants一些閱讀,以得到一個模塊實例 - 和 - 類常量查找,但它的作品。我不確定我是否真的喜歡解決方案。好問題,儘管你可以添加一些細節。

+0

是的,這個例子是有點隨機的,這是更多的配置和示例使它看起來像它可以通過繼承來處理(品種<狗),但感謝良好的答案:) – kreek