Calling selected methods of a module from another module

Updated . Posted . Visible to the public.

Given those modules:

module A
  def foo; end
  def bar; end
end

module B
end

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.

Arne Hartherz
Last edit
Arne Hartherz
Keywords
single
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2011-02-02 08:11)