PlankTon
PlankTon

Reputation: 12605

Rails & ActiveRecord: Appending methods to models that inherit from ActiveRecord::Base

I have a standard ActiveRecord model with the following:

class MyModel < ActiveRecord::Base
  custom_method :first_field, :second_field
end

At the moment, that custom_method is picked up by a module sent to ActiveRecord::Base. The functionality basically works, but of course, it attaches itself to every model class, not just MyModel. So if I have MyModel and MyOtherModel in the same action, it'll assume MyOtherModel has custom_method :first_field, :second_field as well.

So, my question is: How do I attach a method (eg: def custom_method(*args)) to every class that inherits from ActiveRecord::Base, but not by attaching it to ActiveRecord::Base itself?

Any ideas appreciated.

===

Edit

The custom_method is currently attached to ActiveRecord::Base by the following:

module MyCustomModule
  def self.included(base)
    base.extend(self)
  end

  def custom_method(*args)
    # Zippity doo dah - code goes here
  end
end

ActiveRecord::Base.send(:include, MyCustomModule)

Upvotes: 3

Views: 338

Answers (1)

joelparkerhenderson
joelparkerhenderson

Reputation: 35443

Do you know about descendants?

ActiveRecord::Base.descendants

You have to be sure to touch the models before calling it.

See excellent discussion here:

Is there a way to get a collection of all the Models in your Rails app?

I concur with the commentors above that you may want to consider adding your methods to the meta class, or an intermediary class, or a Module mixin.

Upvotes: 2

Related Questions