5

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)
Martin
  • 134
  • 1
  • 2
  • 12
  • What do you mean by "is this possible?"? Have you tried it? That would be the obvious way to check. The answer is probably "yes", but I don't understand why you haven't tried it. – Ken Y-N Sep 24 '13 at 05:57
  • i tried .. but no success yet – Martin Sep 24 '13 at 05:59
  • I apologise for my above comment - I see that you were actually having an error; please in future include any error messages that you see, thanks. – Ken Y-N Sep 24 '13 at 06:15
  • @KenY-N i edited question .. now you can see error message at bottom of question. – Martin Sep 24 '13 at 06:27

2 Answers2

13

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.

Community
  • 1
  • 1
tessi
  • 13,313
  • 3
  • 38
  • 50
0

I've looked at your problem in a bit more detail, and the issue is your module.rb file:

module CardExpiry
  def self.check_expiry value
    return true
  end
end

First, there was an end missing from the file - both def and module need to be closed.

Second, the magical self. in the def line turns the method into a pseudo-global function - this answer explains it better than I can.

Furthermore, to call the method, you need to use:

raise (CardExpiry::check_expiry 1203).inspect
Community
  • 1
  • 1
Ken Y-N
  • 14,644
  • 21
  • 71
  • 114