ruby mixin с методами класса, методами экземпляра и переменными класса - PullRequest
1 голос
/ 23 июня 2011

Знаете ли вы, как определить переменную класса @@method_names, чтобы и my_macro, и invoke_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 ]

2 голосов
/ 24 июня 2011

Вот рабочая версия. Изменения комментируются:

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 голос
/ 24 июня 2011
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
...