Friday, September 16, 2011

How to Extend a Ruby Module?

Modules in Ruby are like classes with a few important differences. One of the differences is, a module cannot inherit from another module using the same syntax as class inheritance. However, its pretty easy to inherit a module's method into another module, by just using the include ModuleToInclude syntax. Here's an example if you are looking for one:

#!/usr/bin/ruby
module BaseModule
def cry
p "wa wa wa waaa"
end
end
module ExtendedModule
include BaseModule
#override the cry method from BaseModule
def cry
super
p "aa waa aa waa"
end
end
class MyClass
include ExtendedModule
end
MyClass.new.cry #=> wa wa wa waaa aa waa aa waa