Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: module, require and include

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?

like image 801
Dakkar Avatar asked Feb 26 '13 19:02

Dakkar


People also ask

What is difference between require and include in Ruby?

What's the difference between "include" and "require" in Ruby? The include and require methods do very different things. The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice.

What does including a module Do Ruby?

include is the most used and the simplest way of importing module code. When calling it in a class definition, Ruby will insert the module into the ancestors chain of the class, just after its superclass.

What is difference between include and extend in Ruby?

In simple words, the difference between include and extend is that 'include' is for adding methods only to an instance of a class and 'extend' is for adding methods to the class but not to its instance.

Can modules include other modules Ruby?

Indeed, a module can be included in another module or class by using the include , prepend and extend keywords. Before to start this section, feel free to read my article about the Ruby Object Model if you're unfamiliar with the ancestor chain in Ruby.


2 Answers

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.

like image 147
Kyle Avatar answered Oct 12 '22 01:10

Kyle


The issue is that you are calling hallo in the class definition, while you add it as an instance method (include).

So you could either use extend (hallo would become a class method):

module MyModule   def hallo     puts "hallo"   end end  class MyApp   extend MyModule   self.hallo end 

Or either call hallo in an instance of MyApp:

module MyModule   def hallo     puts "hallo"   end end  class MyApp   include MyModule end  an_instance = MyApp.new an_instance.hallo 
like image 25
CCD Avatar answered Oct 12 '22 02:10

CCD