Sunday, December 20, 2009

MetaClass _why

スーパークラスでサブクラスのクラスメソッド(シングルトンメソッド)を定義する
class Object
    def metaclass
        class << self
            self
        end
    end
    def meta_eval &blk
        metaclass.instance_eval &blk
    end
    def meta_def name, &blk
        meta_eval { define_method name, &blk }
    end
    def class_def name, &blk
        class_eval { define_method name, &blk }
    end
end

class MailTruck
    def self.company name
        meta_def :company do
            name
        end
    end
end

class HappyTruck < MailTruck
    company "Happy's -- We bring the mail!"
end

以下と等価
class MailTruck
    def self.company name
        class << self
            self.instance_eval do
                define_method :company do
                    name
                end
            end
        end
    end
end
class HappyTruck < MailTruck
    class << self
        def company
            "hello"
        end
    end
end

p HappyTruck.company

No comments: