如何编写自己的attr_accessible类型宏

时间:2011-03-10 12:35:51

标签: ruby-on-rails activerecord metaprogramming

我不确定macro是否是正确的术语。基本上,我希望能够轻松配置ActiveRecord列(使用熟悉的AR语法),以便before_save通过调用实例方法始终以某种方式格式化它们。

我想从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

1 个答案:

答案 0 :(得分: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。

抱歉,如果出现错误,请查看{_ 3}} {/ 3}}。

希望这可以提供帮助。