Despite Ruby's clean design and flexibility, the language has no native feature
that allows one to over-ride a method without irrevocably losing the original binding
of the method name.
alias
is a well-worn idiom that circumvents this limitation,
but blogger Jay Fields wrote an interesting post
that reminds us that alias
comes with some less-than-desireable side-effects
that may not be significant in small scripts and projects
but may become a problem for larger projects.
In the same post,
Jay offered an interesting alternative to alias
,
using instead Module#instance_method
and Module#define_method
.
This is much better, but I'm not quite satisfied.
While obvious enough to experienced Ruby-hands,
people who are newer to Ruby (like me!)
might have trouble remembering the syntax of x = self.instance_method(:x)
and x.bind(self).call
every time they need to use this.
What I'd really like is a way to override defined methods that's a no-brainer.
So I thought about how I could take Jay's example one step further and after some trial and lots of error came up with this.
Thanks and credit go to Jay Fields for his post.
A mix-in module that allows for super-clean method over-riding without resorting to alias
or making unbound methods visible.
class A
def hello
"hello"
end
end
# Later, I want to overide class A methods
class A
extend Overider
overide (:hello) do |*a|
overiden(*a) + " overide"
end
end
puts A.new.hello # ==> "hello overide"
- Ruby License
overider.gem by Lawrence Siden is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
Based on a work at github.com.