2012-03-30 86 views
0

我搞亂了創建rails gem,而且我無法向ActiveRecord添加方法。比方說,我要做到以下幾點:Rails:將方法添加到activerecord(正確的方法?)

class DemoModel < ActiveRecord::Base 
    custom_method :first_argument, :second_argument 
end 

爲了使這項工作,我扔在以下幾點:

module DemoMethod 

    def self.included(base) 
    base.extend(ClassMethods) 
    end 

    module ClassMethods  
    def custom_method(*fields) 
     @my_fields = fields 
    end 
    end 

end 

ActiveRecord::Base.send(:include, DemoMethod) 

到目前爲止,一切都很好。

問題是,我想從模型的實例訪問my_fields變量。例如,我可能會開的form_for的東西,如:

module ActionView::Helpers::FormHelper 
    def fields_for(record_name, record_object, options = {}, &block) 
    the_fields = record_object.<I WANNA ACCESS @my_fields HERE!!!>.html_safe 
    # ... 
    end 
end 

的困難是,「custom_method」似乎只如果我設置助手作爲一個類的方法來工作,但是這意味着.self現在的模型( DemoModel)而不是我想要工作的DemoModel對象。我可以使用「custom_method self,:first_argument,:second_argument」手動傳遞對象,但要求我的美妙「custom_method」gem的用戶必須在自己的參數列表中添加「self」,似乎有點笨拙。

所以,問題是,如何更聰明的Rails人通過custom_method爲特定對象設置值,然後將其檢索到其他位置,如fields_for?

一如既往,任何建議表示讚賞。

回答

2

使用self.includedClassMethods將方法添加爲類方法。

在模塊中正常定義方法,然後包括它們是創建普通實例方法的方法。像這樣:

module DemoMethod 

    def custom_method(*fields) 
    @my_fields = fields 
    end 
end 

ActiveRecord::Base.send(:include, DemoMethod) 
+0

Ach - 當然。 .extend令我困惑。非常感謝。 – PlankTon 2012-03-30 15:22:54

相關問題