包装块以使用细化

Wrap block to use refinement

鉴于以下细化:

module StringRefinement
  refine String do
    def bar
      length
    end
  end
end

我想使用我的优化实现一个模块来执行块:

module Demo
  using StringRefinement

  def self.wrap(*args, &block)
    instance_eval(&block)
  end
end

现在我应该可以像这样使用它了:

Demo.wrap { puts "some text".bar }

哪个不起作用:-(

我一直在研究块绑定、yield、context,singleton_class...但我仍然无法让它工作。我该怎么做?

您需要将 using StringRefinement 语句移出模块。

检查文档中的以下段落:

You may only activate refinements at top-level, not inside any class, module or method scope.

http://ruby-doc.org/core-2.1.1/doc/syntax/refinements_rdoc.html#label-Scope