ruby mixin与类方法,实例方法和类变量

时间:2011-06-23 19:29:30

标签: ruby mixins

您知道如何定义@@method_names类变量,以便my_macroinvoke_methods都可以按预期使用它吗?谢谢!

module MyModule

    module ClassMethods    
        def my_macro method_name, options = { }
            define_method method_name do
                puts "defining #{method_name} with #{options}"
            end
            @@method_names << method_name
        end    
    end

    def invoke_methods
        @@method_names.each { |method_name| send method_name }
    end

    def self.included includer
        includer.extend ClassMethods
    end

end

class MyClass
    include MyModule
    my_macro :method_foo, :bar => 5
    my_macro :method_baz, :wee => [3,4]
end

MyClass.new.invoke_methods

2 个答案:

答案 0 :(得分:2)

这是一个有效的版本。更改被评论:

module MyModule
    module ClassMethods
        @@method_names ||= [] #move this up here
        def my_macro method_name, options = { }
            define_method method_name do
                puts "defining #{method_name} with #{options}"
            end
            @@method_names << method_name
        end

        #added this (rename as required)
        def the_methods
          @@method_names
        end
    end

    def invoke_methods
        #changed this call
        self.class.the_methods.each { |method_name| send method_name }
    end

    def self.included includer
        includer.extend ClassMethods
    end
end

class MyClass
    include MyModule
    my_macro :method_foo, :bar => 5
    my_macro :method_baz, :wee => [3,4]
end

MyClass.new.invoke_methods

答案 1 :(得分:1)

module MyModule

    module ClassMethods    
        def my_macro method_name, options = { }
            define_method method_name do
                puts "defining #{method_name} with #{options}"
            end
            @method_names ||= []
            @method_names << method_name
        end  

        def method_names
          @method_names
        end  
    end

    def invoke_methods
        self.class.method_names.each { |method_name| send method_name }
    end

    def self.included includer
        includer.extend ClassMethods
    end

end

class MyClass
    include MyModule
    my_macro :method_foo, :bar => 5
    my_macro :method_baz, :wee => [3,4]
end

MyClass.new.invoke_methods