【问题标题】:How to define an original name scope in module/class with Ruby如何使用 Ruby 在模块/类中定义原始名称范围
【发布时间】:2017-05-02 22:18:38
【问题描述】:

如何使用 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 want to call methods like the following:
c.some_method1
c.some_method2

如何实现 OriginalNameScope 模块?我发现在这个方法中获取方法定义,但是不知道如何重新定义带有前缀范围的方法。

module OriginalNameScope
  def scope(name, &method_definition)
    puts method_definition.class
    # => Proc
  end
end

【问题讨论】:

    标签: ruby


    【解决方案1】:

    这实际上只是一些简单的标准 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
    

    我只是把它放在一起,可能有很多可以改进(例如使用细化)和简化的地方。

    【讨论】:

      猜你喜欢
      • 2013-08-24
      • 1970-01-01
      • 2010-10-22
      • 1970-01-01
      • 2014-02-27
      • 1970-01-01
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      相关资源
      最近更新 更多