是否可以获得包含在其类方法中的模块名称?
一些满足以下示例的代码:
module Helper
def module_name
# return module name for which method is being called
end
def new_module
name = module_name
define_method :initialize_module do
extend foo? ? Object.const_get("New#{name}") : Object.const_get("Old#{name}")
end
end
end
module A
extend Helper
new_module
module NewA
def some_method
'Successfully extended NewA'
end
end
module OldA
def some_method
'Successfully extended OldA'
end
end
end
class B
include A
def initialize
initialize_module
end
def foo?
true
end
end
class C
include A
def initialize
initialize_module
end
def foo?
false
end
end
B.new.some_method
#=> 'Successfully extended NewA'
C.new.some_method
#=> 'Successfully extended OldA'