Created
January 29, 2011 05:53
-
-
Save bagwanpankaj/801582 to your computer and use it in GitHub Desktop.
Monkey Patching done right
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MyString.send(:undef_method, :empty?) | |
# => MyString | |
#now if we try | |
str.empty? | |
#=> whooop NoMethodError |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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