Macros in Ruby and Rails

Macros are class methods that create new instance methods. If you create a macro in a superclass, all of its subclasses can call that method, pass in arguments, and quickly have one or more customized instance methods.

Rails uses this technique to provide lots of functionality from very little code. For example the association methods such as has_many and belong_to use macros to produce instance methods that return the associated object(s).

In Ruby, macros depend on using the define_method method, which, when called, will define a method in the current scope. It takes an argument, which becomes the name of the new method, and a block, which is the code that goes inside the new method. Any parameters passed to the block will be arguments that the new method can take.

For instance, here's how you could made a macro that will create methods allowing you to access or set values in a class' attributes hash:

def make_columns(columms)
  columns.each do |col|
    define_method("#{col}") do
      attributes[col]
    end
  end
  
  columns.each do |col|
    define_method("#{col}=") do |value|
      attributes(col) = value
    end
  end
end