Created
July 18, 2013 04:18
-
-
Save anthonylewis/6026687 to your computer and use it in GitHub Desktop.
An example of a method decorator in Ruby
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 TrackMethods | |
def track(meth) | |
self.class_eval do | |
alias_method "old_#{meth}", meth | |
define_method meth do |*args| | |
puts "Calling #{meth} with #{args.join(', ')}" | |
self.send "old_#{meth}", *args | |
end | |
end | |
end | |
end | |
class Account | |
extend TrackMethods | |
def initialize(balance) | |
@balance = balance | |
end | |
def deposit(n) | |
@balance += n | |
puts "Balance is now #{@balance}" | |
end | |
track :deposit | |
end | |
a = Account.new(10) | |
a.deposit 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment