On 14.06.2008 12:48, Old E. wrote:
Here’s something I’ve been pondering lately and was hoping to get a good
response from someone out in the community. It’s about having two
modules which both implement a method with the same name, and then
including both modules into a class.
This is a bad idea. As others have pointed out, the last inclusion
wins. Ruby != Eiffel and Ruby != C++ - in a language like this you
better find other solutions to your problem. If you provide more
context we might come up with a solution that is better suited to Ruby.
Example:
Okay, so that’s a pretty contrived example,
Yes, it is. Your car can only be one make at a time, i.e. there is no
point in including both modules at the same time.
but here’s my question: how
can I can call the start method defined in Honda rather than the start
method defined in Ford? I feel like there’s something I’m missing here,
but I’m not sure what it is.
For the fun of it: you can find an incomplete solution at the end.
Kind regards
robert
#!/bin/env ruby
class Module
class Proxy
def initialize(mod, obj)
@mod = mod
@obj = obj
end
def method_missing(m,*a,&b)
@mod.instance_method(m).bind(@obj).call(*a,&b)
end
# other methods must be undefined
end
def scope(obj)
Proxy.new self, obj
end
end
module Honda
def start
puts “Wroom”
end
end
module Ford
def start
puts “Rrrooom”
end
end
class Car
include Honda
include Ford
end
car = Car.new
car.start
Ford.scope(car).start
Honda.scope(car).start