Need some basic help with on-the-run model extension

Hi all

I want to create a method that - when called in a model definition -
adds some more methods to this model.

def MyModel < ActiveRecord::Base
  add_some_methods # This should add some methods
end

So I began with the following code...

def ActiveRecord::Base
  private
  def self.add_some_methods
    # Add some methods...
  end
end

But now I don't know how I can add those methods in the add_some_method
method. Any help is highly appreciated. :slight_smile:

Several ways:

Hi all

I want to create a method that - when called in a model definition -
adds some more methods to this model.

def MyModel < ActiveRecord::Base
  add_some_methods # This should add some methods
end

So I began with the following code...

class ActiveRecord::Base
   private
   def self.add_some_methods
       # using define method
        define_method(:new_meth1) {|arg| #code for method body here}
       # using class_eval
       class_eval(<<-HERE
           def new_meth2(arg)
                # Code for new_meth2
          end
     HERE
   end
end

You might want to check out Module#alias_method_chain which is added
by ActiveSupport, this is the idiomatic way to add extensions to
existing methods. Lets' say you wanted to extend
ActiveRecord::Base#find with some new feature called foo. You'd do
something like this inside your add_some_methods method

    alias_method_chain :find, :foo

and define your extension method as :find_with_foo, you can get at the
original find method by calling :find_without_foo since the alias
method chain expands to:

     alias_method :find_without_foo, :find
     alias_method :find, :find_with_foo

Ah yeah, and by the way: how can I determine the actual model's class
name in the add_some_methods method?

   Just invoke the Module#name method in your class method, either
with self or no receiver.