Making a module inherit from another module in Ruby
In fact you can define a module inside of another module, and then include it within the outer one.
so ross$ cat >> mods.rbmodule ApplicationHelper module Helper def time Time.now.year end end include Helperendclass Test include ApplicationHelper def run p time end selfend.new.runso ross$ ruby mods.rb2012
One potential gotcha is that if the included module attaches class methods, then those methods may be attached to the wrong object.
In some cases, it may be safer to include the 'parent' module directly on the base class, then include another module with the new methods. e.g.
module ApplicationHelper def self.included(base) base.class_eval do include Helper include InstanceMethods end end module InstanceMethods def new_method #.. end endend
The new methods are not defined directly in ApplicationHelper
as the include Helper
would be run after the method definitions, causing them to be overwritten by Helper
. One could alternatively define the methods inside the class_eval
block