rtcoms
rtcoms

Reputation: 793

How to dynamically implement after_save hook for an ActiveRecord class in rails

I am creating a gem which create hooks like before_update_filter in ActiveRecord class . For this I have create a module UpdateFilter as given below :

module UpdateFilter
 def before_update_filter(*args)
    puts self #in class scope
    self.set_callback(:save, :before, args[0].to_sym)
 end
end

And in intializers I am doing

ActiveRecord::Base.extend UpdateFilter

Ok. Now all above is working fine . But I want to set_callbacks only if some attributes of instance changed and I cannot access attributes in before_update_filter method because it is in class scope .

As a summary I want to implement hook like . I hope it clears what I am trying to do .

before_update_filter :instance_mthod_name, :attr_prams => [:name, :rating]

Now how can I implement this??

Upvotes: 1

Views: 883

Answers (1)

KL-7
KL-7

Reputation: 47608

It might require some edits, but I think that should work:

module UpdateFilter
 def before_update_filter(callback_method, options = {})
    puts self # class scope
    self.set_callback :save, :before do
      puts self # instance scope
      # check if all of the listed attributes have changed
      if options[:attr_params].map{ |attr| attribute_changed?(attr) }.all?
        # call instance method
        send callback_method
      end
    end
 end
end

According to the docs block passed to set_callback is executed in the context of the current object. So we have access to all instance methods inside this block. We check that all (replace it with 'any' or even some other conditions) listed attributes have changed and only then call required callback instance method.

Upvotes: 2

Related Questions