Safe monkey patching with refinements
suggest changeSince Ruby 2.0, refinements can limit a monkey patch to the scope that activates it with using.
First we create a refinement in a module:
module RefiningString
refine String do
def reverse
"Hell riders"
end
end
end
Then we can decide where to use it:
class AClassWithoutMP
def initialize(str)
@str = str
end
def reverse
@str.reverse
end
end
class AClassWithMP
using RefiningString
def initialize(str)
@str = str
end
def reverse
@str.reverse
end
end
AClassWithoutMP.new("hello").reverse # => "olleh"
AClassWithMP.new("hello").reverse # => "Hell riders"
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents