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.