【问题标题】:How to Write Your Own attr_accessible Type Macro如何编写自己的 attr_accessible 类型宏
【发布时间】:2011-03-10 12:35:50
【问题描述】:

我不确定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

【问题讨论】:

  • 对不起,我的意思是我不知道答案。我删除了答案以防止混淆。

标签: ruby-on-rails activerecord metaprogramming


【解决方案1】:

尝试扩展 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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2020-06-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多