Reputation: 2346
This is essentially a snippet from Ruby Metaprogramming 2. In the section they gloss over this example but there isn't really an 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 doesn't the refinement apply when you call my_method
from another method?
Upvotes: 4
Views: 594
Reputation: 3374
refine
keyword use to Refinements of the class locally. It's mean we can monkey patch any method by refinement of the class.
In your case, the process of refine/redfined/monkey patch only active when the method get call directly. Also Refinements are lexical in scope. When control is transferred outside the scope the refinement is deactivated.
To get better insight, read the scope
part of refinements from here: Refinements
Upvotes: 1
Reputation: 160170
It avoids "leaky" refinements, e.g., the refinement applies specifically to the method you refine.
http://yehudakatz.com/2010/11/30/ruby-2-0-refinements-in-practice/
Very near the bottom this functionality is explained; nutshell:
[the] refinement should not leak [...]. If it did, it would mean that any call into any method could leak a refinement into that method, which is the opposite of the purpose of the feature.
Upvotes: 3