Dynamically add class methods in Rails

I have a Product class which has a small number of records in the db, each of which has a name, eg “millionaire”.  Rather than keep typing Product.find_by_name(“millionaire”) i want to type Product.millionaire.

I could use method_missing for this but that means every time Product gets a method it doesn’t recognise it loads all the products out of the db – not very good.  Instead, let’s use define_method.  Normally define_method adds instance methods to a class but we can add them at the class level like so.  In the product class:

class << self
  Product.find(:all, :select => "name").collect(&:name).each do |name|
    define_method name.to_sym do
      self.find_by_name(name)
    end
  end
end

Now, when the classes are loaded, which happens only at restart in production mode, the methods are created.  No method_missing required and no db access besides the single access at class load.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s