2012-04-19 55 views
0

提前道歉 - 我是一個學習者,並且將項目作爲一種學習方式編寫。在這其中,我試圖延長ActiveRecord的,這樣我可以做到以下幾點...在Rails 3中編寫一個自定義的attr_special函數

在我的模型定義,叫...

attr_special :field, :field 

然後,在其他地方,能夠訪問此通過一些列像

Model.special_attributes 

大概的東西真的很明顯。我很好地擴展ActiveRecord,但我甚至不知道我在尋找什麼指導(構造函數?)...

回答

2

您可以定義類似下面的代碼來在您的模型中創建自定義DSL :

module SpecialAttributes 
    module ClassMethods 
    def attr_special(*attrs) 
     class_attribute :special_attributes 
     self.special_attributes = attrs 
    end 

    def special_attributes 
     self.special_attributes 
    end 
    end 

    module InstanceMethods 
    # some code here 
    end 

    def self.included(base) 
    base.extend ClassMethods 
    base.send :include, InstanceMethods 
    end 

end 

class ActiveRecord::Base 
    include SpecialAttributes 
end 

我重新打開ActiveRecord :: Base類而不是繼承,因爲它在Ruby中更常見的是繼承。

我喜歡在我的模塊中使用名爲ClassMethods和InstanceMethods的子模塊,並使用self.included方法將它們添加到基類中。所以你可以使用'include MyModule'而不必知道你是否添加實例或類方法。

我希望我能幫助你。

+0

這真的非常有用 - 非常感謝。 – user1129657 2012-04-20 06:48:34

相關問題