eonil
eonil

Reputation: 85985

How to import module level functions into class instance in Ruby?

module AA
  def func1()
  end

  class BB
    def method2()
      func1()
    end
  end

end

Currently method2 cannot find func1 and raises an exception.

Why does this happen and what is the right way to do this?

Upvotes: 0

Views: 70

Answers (3)

The way that i follow is to include the module in your class definition

 module AA
   def func1
     puts "func1"
     end
   class BB
    include AA
     def method2
      func1()
       end
     end
   end

This is a Module Mixin strategy, works for any class outside or inside a module. Please read the Mixin section at: http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html

Upvotes: 0

Tass
Tass

Reputation: 1248

This happens for a couple of reasons.

Firstly, because things that belong to the AA module don't belong to the BB class.

Secondly, your syntax to define func1 isn't quite correct.

See this example below of both defining the function (2 different ways) and calling it.

module AA
  def self.func1
  end

  def AA.func2
  end

  class BB
    def method2()
      AA::func1()
    end
  end
end

Upvotes: 1

fmendez
fmendez

Reputation: 7338

Alternatively you could use the extend:

module AA
  def func1()
  end

  class BB
    extend AA
    def method2()
      func1()
    end

  end
end

Upvotes: 0

Related Questions