easierbycode
2/29/2012 - 4:25 AM

Monkey Patching done right

Monkey Patching done right

#now safely remove it

MonkeyPatch::MonkeyString.send(:remove_method, :empty?)
# => MonkeyPatch::MonkeyString

#now check if old empty method is again INCHARGE or NOT

str.method :empty?
# => #<Method: MyString(String)#empty?>
#whoop

#and see it back in action 

str.empty?
# => true 
module MonkeyPatch
  module MonkeyString
    def empty?
      "Safe monkeypatching"
    end
  end
end

#we register this module to MyString class
MyString.send(:include, MonkeyPatch::MonkeyString)

str = MyString.new
str.empty?
#=> "Safe monkeypatching" 

str.method :empty?
# => #<Method: MyString(MonkeyPatch::MonkeyString)#empty?> 
MyString.send(:undef_method, :empty?)
# => MyString
#now if we try
str.empty?
#=> whooop NoMethodError
#first we create a subclass of class string
class MyString < String
end

MyString.new
# => ""

#now we are going to override this method by some Ruby magic
MyString.class_eval do
  def empty?
    "It's monkey-patched. ha ha I did it."
  end
end

str = MyString.new

str.empty?
#=> It's monkey-patched. ha ha I did it.

str.method :empty?
#=> #<Method: MyString#empty?>