Read more

Calling selected methods of a module from another module

Arne Hartherz
February 02, 2011Software engineer at makandra GmbH

Given those modules:

module A
  def foo; end
  def bar; end
end

module B
end
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

When you want to call methods from A inside B you would normally just include A into B:

module B
  include A
end

Including exposes all of A's methods into B. If you do not want this to happen, use Ruby's module_function Show archive.org snapshot : it makes a module's method accessible from the outside. You could put the module_function calls into A but it would remain unclear to people looking at B's code.

A cleaner way would be like this:

module B
  module Outside
    include ::A
    module_function :foo
  end
end

This allows you to use B::Outside.foo or just define a method inside B which casts some magic itself and refers to Outside.foo eventually.

Posted by Arne Hartherz to makandra dev (2011-02-02 09:11)