如何使用Ruby在模块/类中定义原始名称范围
如何使用Ruby在模块/类中定义原始名称范围 我希望实现如下所示的类:如何使用Ruby在模块/类中定义原始名称范围,ruby,Ruby,如何使用Ruby在模块/类中定义原始名称范围 我希望实现如下所示的类: module SomeModule extend OriginalNameScope scope(:some) do def method1 puts 1 end def method2 puts 2 end end end class SomeClass include SomeModule end c = SomeClass.new # I
module SomeModule
extend OriginalNameScope
scope(:some) do
def method1
puts 1
end
def method2
puts 2
end
end
end
class SomeClass
include SomeModule
end
c = SomeClass.new
# I want to call methods like the following:
c.some_method1
c.some_method2
如何实现原始名称镜模块?我发现可以在这个方法中获得方法定义,但我不知道如何用前缀范围重新定义方法
module OriginalNameScope
def scope(name, &method_definition)
puts method_definition.class
# => Proc
end
end
这实际上只是一些简单的标准Ruby元编程模式和习惯用法的组合:
module OriginalNameScope
def scope(name)
singleton_class.prepend(Module.new do
define_method(:method_added) do |meth|
if name && !@__recursion_guard__
@__recursion_guard__ = meth
method = instance_method(meth)
undef_method(meth)
define_method(:"#{name}_#{meth}") do |*args, &block|
method.bind(self).(*args, &block)
end
end
@__recursion_guard__ = nil
super(meth)
end
end)
yield
end
end
我只是简单地总结了一下,可能还有很多地方可以改进(例如使用改进)和简化。这实际上只是一些简单的标准Ruby元编程模式和习惯用法的组合:
module OriginalNameScope
def scope(name)
singleton_class.prepend(Module.new do
define_method(:method_added) do |meth|
if name && !@__recursion_guard__
@__recursion_guard__ = meth
method = instance_method(meth)
undef_method(meth)
define_method(:"#{name}_#{meth}") do |*args, &block|
method.bind(self).(*args, &block)
end
end
@__recursion_guard__ = nil
super(meth)
end
end)
yield
end
end
我只是简单地总结了一下,可能还有很多地方可以改进(例如使用改进)和简化