user3179047
user3179047

Reputation: 324

How can I use a Ruby module in another module?

This code doesn't seem to work - it can't figure out some_func was defined. Why not?

# in file 1
def ModuleA
  def some_func
    "boo"
  end
end

# in file 2
def ModuleB
  include ModuleA

  MY_CONSTANT = some_func
end

Upvotes: 1

Views: 42

Answers (2)

Sigi
Sigi

Reputation: 1864

In your code example, you use the include directive.

This means that all the methods defined in ModuleA are included into ModuleB as instance methods.

However, by then invoking some_func in the module body of ModuleB, you try to invoke it as if it was defined as a class method on ModuleB (which it is not, since you have used include before).

If you actually want to define (and call) it as a class method, then you need to use extend ModuleA inside ModuleB to add the method definition.

Upvotes: 1

Alex Peachey
Alex Peachey

Reputation: 4676

You are declaring your modules wrong and you need to extend not include

module ModuleA
  def some_func
    "boo"
  end
end

module ModuleB
  extend ModuleA
  MY_CONSTANT = some_func
end

Upvotes: 1

Related Questions