2012-05-03 51 views
4

我有一個包含模塊的模型。我想在模塊中覆蓋模型的訪問器方法。覆蓋模型的屬性訪問器在mixin /模塊中

例如:

class Blah < ActiveRecord::Base 
    include GnarlyFeatures 
    # database field: name 
end 

module GnarlyFeatures 
    def name=(value) 
    write_attribute :name, "Your New Name" 
    end 
end 

這顯然是行不通的。任何想法來完成這個?

回答

7

您的代碼看起來正確。我們正在使用這個確切的模式沒有任何問題。

如果我沒有記錯,Rails使用#method_missing作爲屬性設置器,所以你的模塊將優先於阻塞ActiveRecord的setter。

如果您正在使用的ActiveSupport ::關注(見this blog post,那麼你的實例方法需要進入一個特殊的模塊:

class Blah < ActiveRecord::Base 
    include GnarlyFeatures 
    # database field: name 
end 

module GnarlyFeatures 
    extend ActiveSupport::Concern 

    included do 
    def name=(value) 
     write_attribute :name, value 
    end 
    end 
end 
+0

哦,我倒要做錯事時是怎麼樣延長ActiveSuppport: :關注作爲模塊的一部分? – KendallB

+0

這改變了事情,看到我更新的答案 – tihm

+0

太棒了!這有幫助,雖然不是很確切,但在Rails 3.2中,它看起來像InstanceMethods不再包含在內:將訪問者包含在「包含」塊中 – KendallB