红宝石混入与类方法,实例方法和类变量
你知道如何定义@@method_names
类变量,这样既my_macro
和invoke_methods
可以使用它作为故意的吗?谢谢!红宝石混入与类方法,实例方法" title="实例方法">实例方法和类变量
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
回答:
这里有一个工作版本。变化被注释:
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
回答:
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
以上是 红宝石混入与类方法,实例方法和类变量 的全部内容, 来源链接: utcz.com/qa/257881.html