Making a module inherit from another module in Ruby

28,828

Solution 1

In fact you can define a module inside of another module, and then include it within the outer one.

so ross$ cat >> mods.rb
module ApplicationHelper
  module Helper
    def time
      Time.now.year
    end
  end
  include Helper
end

class Test
  include ApplicationHelper
  def run
    p time
  end
  self
end.new.run
so ross$ ruby mods.rb
2012

Solution 2

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
  end

end

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

Share:
28,828
beakr
Author by

beakr

Updated on July 24, 2020

Comments

  • beakr
    beakr almost 4 years

    I'm making a small program for Rails that includes some of my methods I've built inside of a module inside of the ApplicationHelper module. Here's an example:

    module Helper
        def time
            Time.now.year
        end
    end
    
    module ApplicationHelper
        # Inherit from Helper here...
    end
    

    I know that ApplicationHelper < Helper and include Helper would work in the context of a class, but what would you use for module-to-module inherits? Thanks.