2011-03-10 31 views
0

我不確定macro是否是正確的術語。基本上,我希望能夠輕鬆地配置ActiveRecord列(使用熟悉的AR語法),以便通過調用實例方法來始終以特定方式對它們進行格式化。如何編寫自己的attr_accessible類型宏

我想從mixin中創建所有這些訪問。

例如:

class MyClass < ActiveRecord::Base 

    happy_columns :col1, :col2 # I really want this type of convenient syntax 


    # dynamically created stuff below from a mixin. 
    before_save :make_col1_happy 
    before_save :make_col2_happy 

    def make_col1_happy; self.col1 += " is happy"; end 
    def make_col2_happy; self.col2 += " is happy"; end 

end 
+0

對不起,我的意思是我不知道答案。我刪除了答案以防止混淆。 – Augusto 2011-03-10 13:01:54

回答

0

儘量延長的ActiveRecord,A.E.

#in lib/happy_columns.rb 


module HappyColumns 
    def happy_columns(cols) 
    cols.each do |c| 
    before_filter "make_#{c}_happy".to_sym 

    #here you could define your instance methot using define_method 
     define_method "make_#{c}_happy" do 
     #your code 
     end 

    end 



    include InstanceMethods 
    end 

    module InstanceMethods 
    #here you could define other your instancemethod 


    end 
end 


ActiveRecord::Base.extend HappyColumns 

確保在加載路徑中包含擴展名,那麼您可以在模型中使用happy_cols。

對不起,如果有一些錯誤,define_method請看this

希望這可以幫助。