Reputation: 11022
Is there a way to decorate a function in Ruby as it's done in Python? That is, have something execute at the beginning (and end?) of each function.
Like this: http://programmingbits.pythonblogs.com/27_programmingbits/archive/50_function_decorators.html
Upvotes: 3
Views: 2315
Reputation: 1018
Python's decorator syntax (which may not be exactly the functionality you're seeking to emulate) can be achieved in ruby by mixing in a module which modifies the decorated class' methods, as described succinctly in "Decorator Pattern with Ruby in 8 lines" by Luke Redpath.
Upvotes: 0
Reputation: 6076
If by function you mean closure, you could use a block:
def foo
puts 'before code'
yield
puts 'after code'
end
foo { puts 'here is the code' }
Upvotes: 4
Reputation: 211670
The alias_method
facility can be used to achieve this effect:
alias_method :old_foo, :foo
def foo
# ... before stuff ...
r = old_foo
# ... after stuff ...
return r
end
Within Ruby on Rails you can use alias_method_chain
to do some of this for you.
Upvotes: 2