rubyrefinements

Wrap block to use refinement


Given the following refinement:

module StringRefinement
  refine String do
    def bar
      length
    end
  end
end

I want to implement a module to execute blocks using my refinement:

module Demo
  using StringRefinement

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

And now I should be able to use it like this:

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

Which doesn't work :-(

I've been playing with the block binding, yield, context, singleton_class... but I still cannot get this to work. How can I do it?


Solution

  • You need to move your using StringRefinement statement outside of your module.

    Check the following paragraph from the docs:

    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