views:

81

answers:

1
class Product < ActiveRecord::Base
 set_table_name 'produce'
end

module ActiveRecord
 class Base
 def self.set_table_name name
 define_attr_method :table_name, name
end

def self.define_attr_method(name, value)
singleton_class.send :alias_method, "original_#{name}", name
singleton_class.class_eval do
 define_method(name) do
   value
 end
end
end
end
end

I'd like to understand how set_table_name becomes defined in this example.

Why is singleton_class.send needed here?

And why is class_eval called on singleton_class instead of on self?

+2  A: 

Hello Connor,

The reason for using "singleton_class" is because you do not want to modify the ActiveRecord::Base class, but the Product class.

More info about metaptogramming and singleton class here: http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html

Vlad Zloteanu