Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling module method into another module in Ruby

Tags:

ruby

FIle module.rb

module CardExpiry
  def check_expiry value
    return true
  end
end

file include.rb

#raise File.dirname(__FILE__).inspect
require "#{File.dirname(__FILE__)}/module.rb"

 module Include
     include CardExpiry
  def self.function 
    raise (check_expiry 1203).inspect
  end
end

calling

Include::function

is this possible ?

Error trigger when calling :

`function': undefined method `check_expiry' for Include:Module (NoMethodError)
like image 947
Akash Jain Avatar asked Sep 24 '13 05:09

Akash Jain


People also ask

How do you call a method inside a module in Ruby?

To access the instance method defined inside the module, the user has to include the module inside a class and then use the class instance to access that method.

Can a module include another module Ruby?

In Ruby we don't have multiple inheritance, but we can include as many modules as we want, so they give us the same feature, without all the hassle that multiple inheritance usually brings to a language.

Can Ruby modules have private methods?

You can only use private methods with:Other methods from the same class. Methods inherited from the parent class. Methods included from a module.


1 Answers

You stumbled over the difference of include and extend.

  • include makes the method in the included module available to instances of your class
  • extend makes the methods in the included module available in the class

When defining a method with self.method_name and you access self within that method, self is bound to the current class.

check_expiry, however, is included and thus only available on the instance side.

To fix the problem either extend CardExpiry, or make check_expiry a class method.

like image 107
tessi Avatar answered Sep 29 '22 20:09

tessi