views:

18

answers:

1

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?

+1  A: 

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
giraff
You rule, thanks!
Brian Armstrong
Also, just to follow up, it looks like you are missing a `def` in front of `self.included(base)`, but otherwise this works great. Thanks!
Brian Armstrong
Fixed. You're welcome!
giraff