3
votes

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)
1
Sounds like the key is what does custom_method do?Frederick Cheung
Opens up ActionView::Helpers::FormHelper --> fields_for & appends args from custom_method(*args) to the top of any form_for (wrapped in h1 tag). …Effectively a useless gem, but I'm trying to find my feet re: gem creation.PlankTon
Why not define a class that inherits from ActiveRecord::Base, and have your models inherit from that? Or is this something that you want completely hidden so that other developers can keep inheriting from ActiveRecord::Base and get the functionality without requesting it explicitly?Marc Talbot
I woud like to see the module you are including and how you are attaching attaching the method. You have strayed into the land of meta programming and I think what you have done is attached the methods to the base class, you should be attaching the methods to the meta class. check this out: reference.jumpingmonkey.org/programming_languages/ruby/…Ben Miller
If you were to call define_method from inside custom_method that would only add methods to the model in questionFrederick Cheung

1 Answers

2
votes

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.