Reputation: 2579
Do I need a heavy weight aspect oriented programming library to duck-type methods with before and after join point advice, or can I do it in a few lines of Ruby?
For example, I have the following function:
def add_them(a,b)
a + b
end
I want to duck-type add_them()
with a before join point so it type-checks before executing the main body:
if (a.class != b.class)
puts "DANGER"
end
The naive way of duck-typing destroys the original add_them()
. Ideally I want to end up with:
def foo
#before join point code
#original body of foo
#after join point code
end
Upvotes: 0
Views: 192
Reputation: 62668
There are two ways to do this.
First, if you're mixing a module into your class, you can simply call super
to call the overridden method:
class Foo
def bar(a, b)
a + b
end
end
module TypeEnforcer
def bar(a, b)
raise "Wrong type!" unless a.is_a? Fixnum && b.is_a? Fixnum
super
end
end
Foo.send :include, TypeEnforcer
If you're monkey patching by reopening the same class, though, you would use alias_method
to create a "backup" of the method you're overwriting:
class Foo
alias_method :orig_bar, :bar
def bar(a, b)
raise "Wrong type!" unless a.is_a? Fixnum && b.is_a? Fixnum
orig_bar(a, b)
end
end
Finally, while this doesn't answer your question, you might be interested in contracts.ruby which uses Ruby metaprogramming magic to add type contracts to methods. It does have a bit of performance overhead, but it's a very clean way to express this kind of behavior.
Upvotes: 3