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)
4
  • 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. Commented Sep 24, 2013 at 5:57
  • i tried .. but no success yet Commented Sep 24, 2013 at 5: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. Commented Sep 24, 2013 at 6:15
  • @KenY-N i edited question .. now you can see error message at bottom of question. Commented Sep 24, 2013 at 6:27

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.