Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you include before/after filters in a Rails Module?

I wanted to add a method to two models, so I made a module like this and included it in both models.

module UserReputation
  def check_something
    ...
  end
end

That worked fine. I then wanted to have that method called as an :after_create on all those models. It works if I add it manually to all the models, but I wanted to be smart and include it in the module like this:

module UserReputation
  after_create :check_something
  def check_something
    ...
  end
end

But this doesn't work. Is there any way to accomplish this and DRY up the after_create as well?

like image 641
Brian Armstrong Avatar asked Jul 26 '10 18:07

Brian Armstrong


1 Answers

Try self.included, which is called when the module is mixed into the class base:

module UserReputation
  def self.included(base)
    base.after_create :check_something
  end
end
like image 109
giraff Avatar answered Sep 24 '22 09:09

giraff