Skip to content

Instantly share code, notes, and snippets.

@bagwanpankaj
Created January 29, 2011 05:53
Show Gist options
  • Save bagwanpankaj/801582 to your computer and use it in GitHub Desktop.
Save bagwanpankaj/801582 to your computer and use it in GitHub Desktop.
Monkey Patching done right
#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?>
MyString.send(:undef_method, :empty?)
# => MyString
#now if we try
str.empty?
#=> whooop NoMethodError
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?>
#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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment