Monkey patching with limited scope
suggest changeMonkey patching’s main issue is that it pollutes the global scope. Your code works only if every module you load avoids stepping on the others. Refinements are monkey patches with a limited scope.
module Patches
refine Integer do
def plus_one
self + 1
end
def plus(num)
self + num
end
def concat_one
self.to_s + '1'
end
end
end
class RefinementTest
# has access to our patches
using Patches
def initialize
puts 1.plus_one
puts 3.concat_one
end
end
# The main scope does not have the changes.
RefinementTest.new
# prints:
# 2
# 31
1.plus_one
# NoMethodError: undefined method 'plus_one' for an instance of Integer
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents