Multiple Inheritance Using Ruby
I was recently surprised by Ruby, in a great way. I don't expect to find anything new or extremely different when I start using a new programming language. Ruby changed that.
I was trying to solve a problem where I needed to create an object that could include any combination of components. Think of an alerting system where an alert could execute an unknown set of actions. You can't just extend an Alert class because that would only give you one action, and you don't want to build a class that checks for each type of action. That would be immediately outdated. The solution, in Ruby, is to extend an object with multiple modules.
<code>
class Alert
def run
puts "Alert->run"
end
end
module EmailAction
def run
puts "EmailAction->run"
super()
end
end
module PageAction
def run
puts "PageAction->run"
super()
end
end
alert_object = Alert.new()
alert_object.extend(EmailAction)
alert_object.extend(PageAction)
alert_object.run()
</code>
<output>
PageAction->run
EmailAction->run
Alert->run
</output>
I don't know how you will use this fun little trick, but I know I've had more than a couple of instances where it would be useful.