How does the refinement area work?

This is essentially a snippet from Ruby Metaprogramming 2. They obscure this example in this section, but there is really no explanation.

module MyRefinement
  refine MyClass do
    def my_method
      "refined"
    end
  end
end

class MyClass
  def my_method
    "original"
  end

  def another_method
    my_method
  end
end

using MyRefinement

obj = MyClass.new

puts obj.my_method       #=> "refined"
puts obj.another_method  #=> "original"

      

Why isn't it clarified when you call my_method

from another method?

+3


source to share


2 answers


It avoids "leaking" qualifications, for example, the qualification refers specifically to the qualified method.

http://yehudakatz.com/2010/11/30/ruby-2-0-refinements-in-practice/



Very close to the bottom of this feature is explained; shell:

[the] clarification should not flow [...]. If that were the case, it would mean that any call to any method could leak into that method, which is the opposite of the purpose of this function.

+2


source


refine

Using a keyword to qualify a local class. This means that we can decapitate any method by qualifying the class.

In your case, the update process of / redfined / monkey patch is only active when the method gets called directly. Also, clarifications are lexical in scope. When control is transferred out of scope, the refinement is deactivated.



To get a better idea, read scope

some of the clarifications from here: Refinements

+1


source







All Articles