2

I cannot figure this out from what I have read on Google, but I want to make a gem that will alter the behavior of the module when it saves, but I don't know how to do this. How would I define in the Gem a save method that overrides the model's save method?

Update: I have found Rails 3: alias_method_chain still used?, which I will check into. It appears that alias_method_chain is deprecated for Rails 3.

Community
  • 1
  • 1
Travis Pessetto
  • 3,260
  • 4
  • 27
  • 55
  • alter the behaviour how? like gsub one of the attributes or something to that effect? – pjammer Aug 02 '11 at 14:55
  • For example, check for true...if false abort save if not continue – Travis Pessetto Aug 18 '11 at 16:24
  • 1
    your example can be accomplished with validations. You also have the 'before_save' callback hook, if your behavior is simple. Are you thinking of doing something crazier than that? – YenTheFirst Aug 22 '11 at 06:28
  • @YenTheFirst I was thinking about doing something crazier. The reason I asked is because I want to modify a Gems behavior on everything. – Travis Pessetto Aug 22 '11 at 13:48

2 Answers2

2

I'd rather do this :

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

And then in the model :

class User < ActiveRecord::Base
  include YourModule
end

Hope it helps :)

Cydonia7
  • 3,744
  • 2
  • 23
  • 32
1

Using 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

Then you include the module in your AR object:

class User < ActiveRecord::Base
    include YourModule
end
Maurício Linhares
  • 39,901
  • 14
  • 121
  • 158
  • I am not sure but I think alias_method_chain was deprecated with Rails 3. http://stackoverflow.com/questions/3689736/rails-3-alias-method-chain-still-used – Travis Pessetto Aug 18 '11 at 16:26
  • even if alias_method_chain itself is deprecated, you can still do the same behavior. instead of 'base.alias_method_chain', you'd just have two 'base.alias_method' calls. – YenTheFirst Aug 22 '11 at 06:27