[Solved] Are refinements in Ruby 2.0 totally useless? [closed]


You completely dismiss the fact that Refinements aren’t globally scoped, but that’s the very reason for their introduction. Of course, if you simply ignore the reason for something’s existence, then you obviously won’t see any value in it.

But, see the isolation in action. Here is your example modified to use Refinements:

module MyModule
  refine String do
    def my_locally_needed_func
      # do smth 
    end
  end
end

module MyOtherModule
  # The monkeypatch is invisible:
  "".my_locally_needed_func
  # NoMethodError: undefined method `my_locally_needed_func' for "":String

  # I first have to use the Refinement:
  using MyModule
  "".my_locally_needed_func
end

# The monkeypatch is scoped. Even though we were able to use 
# it in MyOtherModule, we still cannot use it at the top-level:
"".my_locally_needed_func
# NoMethodError: undefined method `my_locally_needed_func' for "":String

# We have to call `using` again, for the top-level:
using MyModule
"".my_locally_needed_func

Here is your example for comparison:

module MyModule
  class ::String
    def my_locally_needed_func
      # do smth 
    end
  end
end

# here I need it
"".my_locally_needed_func

Note: I removed the call to using which didn’t make sense since you didn’t use Refinements anyway.

In your case, the monkeypatch is available globally, because you simply modified the String class. This functionality is called an “open class”, and it is precisely what Refinements are there to avoid.

2

solved Are refinements in Ruby 2.0 totally useless? [closed]