2009-07-26 5 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 여기에 싱글 톤 클래스에 대한

더 많은 정보 : http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html

이 멸종 _why 링크의
+0

보관 된 버전 : http://web.archive.org/web/20090615044849/http://whytheluckystiff.net/articles/seeingMetaclassesClearly .html – jordanpg

+0

그리고 여기에 보관되지 않은 버전 : http://dannytatom.me/metaid/ – alfasin

관련 문제