Gem,rails的自定义保存方法

时间:2011-08-02 14:20:36

标签: ruby-on-rails ruby-on-rails-3 gem

我无法从我在谷歌上看到的内容中弄清楚这一点,但我想制作一个可以在保存时改变模块行为的宝石,但我不知道如何做到这一点。我如何在Gem中定义一个覆盖模型的保存方法的保存方法?

更新:我找到了Rails 3: alias_method_chain still used?,我将检查这些内容。看来alias_method_chain已弃用Rails 3。

2 个答案:

答案 0 :(得分:2)

我宁愿这样做:

module YourModule

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

  module InstanceMethods

    def save
      # Your behavior here
      super # Use this if you want to call the old save method
    end
  end
end

然后在模型中:

class User < ActiveRecord::Base
  include YourModule
end

希望有所帮助:)

答案 1 :(得分:1)

使用alias_method_chain:

module YourModule

  def self.included( base )
    base.send(:include, YourModule::InstanceMethods )
    base.alias_method_chain :save, :action
  end

  module InstanceMethods

    def save_with_action
      # do something here
      save_without_action
    end

  end

end

然后在AR对象中包含该模块:

class User < ActiveRecord::Base
    include YourModule
end