Elliot
Elliot

Reputation: 13835

remote model callbacks - rails 3?

I'm not phrasing the question correctly in the title, but heres what I'd like to do.

I have a method, like such:

class User < ActiveRecord::Base
   def myMethod(abc, xyz)
     #do stuff
   end
end

I want 5 different models in my app to call this function on their after_create callback.

It seems very anti-DRY to put a function in each of those models to call this function.

Is there a way in this model (above) that holds the method - to remotely use the callbacks of the other models?

Or can anyone suggest a different way I should be approaching something like this?

Upvotes: 1

Views: 130

Answers (1)

Robin
Robin

Reputation: 21884

That's what I would do:

Create a module:

module MyCallbacks

    extend ActiveSupport::Concern

    included do
        after_create :my_method
    end

    def my_method
        #do stuff
    end

end

And then, you just need to include this module in the models of your choice:

class MyModel < ActiveRecord::Base
    include MyCallbacks
end

Upvotes: 3

Related Questions