2009-07-26 9 views
4
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 

set_table_nameがこの例でどのように定義されるかをご理解いただきたいと思います。このメタプログラミングの例では、singleton_class.sendとsingleton_class.class_evalの目的は何ですか?

なぜsingleton_class.sendが必要ですか?

ではなくsingleton_classを呼び出すのはなぜですか?class_eval

答えて

4

"singleton_class"を使用する理由は、ActiveRecord :: BaseクラスではなくProductクラスを変更したいからです。ここmetaptogrammingとシングルトンクラスに関する

詳細情報:この絶滅_whyリンクのhttp://whytheluckystiff.net/articles/seeingMetaclassesClearly.html

+0

アーカイブされたバージョン:http://web.archive.org/web/20090615044849/http://whytheluckystiff.net/articles/seeingMetaclassesClearly .html – jordanpg

+0

ここにアーカイブされていないバージョン:http://dannytatom.me/metaid/ – alfasin

関連する問題