Dynamic refinements

suggest change

Refinements have special limitations.

refine can only be used in a module scope, but can be programmed using send :refine.

using is more limited. Call it at the top level of a file or in a class or module body, not inside a method. It can take a variable that points to a module, and it can be called in a loop.

An example showing these concepts:

module Patch
  def patched?; true; end
end

Patch.send(:refine, String) { import_methods Patch }

patch_classes = [Patch]

class Patched
  patch_classes.each { |klass| using klass }
  "".patched? # => true
end

using is lexical, so load order matters: the refinement module must already be defined. One way to delay the patched class is to build it in a proc. include inside refine was removed in Ruby 3.2; the example above uses import_methods.

module Patch
  refine String do
    def patched; true; end
  end
end

class Foo
end

# This is a proc since methods can't contain class definitions
create_patched_class = Proc.new do
  Foo.class_exec do
    class Bar
      using Patch
      def self.patched?; ''.patched == true; end
    end
  end
end
create_patched_class.call
Foo::Bar.patched? # => true

Calling the proc creates the patched class Foo::Bar. This can be delayed until after all the code has loaded.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents