tekknolagi
tekknolagi

Reputation: 11022

Function decorators in Ruby, as in Python

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

Answers (3)

Chazu
Chazu

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

seph
seph

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

tadman
tadman

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

Related Questions