Ruby: module, require and include

Dakkar picture Dakkar · Feb 26, 2013 · Viewed 67.7k times · Source

I'm trying to use Ruby modules (mixins).

I have test.rb:

#!/usr/bin/env ruby
require_relative 'lib/mymodule'

class MyApp
  include MyModule
  self.hallo
end

and lib/mymodule.rb:

module MyModule
  def hallo
    puts "hallo"
  end
end

Quite simple setup. But it does not work :( :

ruby test.rb
test.rb:8:in `<class:MyApp>': undefined method `hallo' for MyApp:Class (NoMethodError)
        from test.rb:6:in `<main>'

Where is my error?

Answer

Kyle picture Kyle · Feb 26, 2013

In short: you need to extend instead of include the module.

class MyApp
  extend MyModule
  self.hallo
end

include provides instance methods for the class that mixes it in.

extend provides class methods for the class that mixes it in.

Give this a read.