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.