Created
August 29, 2012 10:12
-
-
Save halfelf/3509753 to your computer and use it in GitHub Desktop.
Example to show how to define a hook before a method called
This file contains hidden or 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
class Base | |
def self.method_added(name) | |
if /hook/.match(name.to_s) or method_defined?("#{name}_without_hook") | |
return | |
end | |
hook = "def #{name}_hook\n p 'Method #{name} has been called'\n #{name}_without_hook\nend" | |
self.class_eval(hook) | |
a1 = "alias #{name}_without_hook #{name}" | |
self.class_eval(a1) | |
a2 = "alias #{name} #{name}_hook" | |
self.class_eval(a2) | |
end | |
def a | |
p "a called." | |
end | |
def b | |
p "b called." | |
end | |
end | |
t1 = Base.new | |
t1.a | |
t1.b | |
t1.a | |
t1.b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment