calling module method into another module in Ruby

2020-06-23 06:39发布

问题:

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)

回答1:

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.



回答2:

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


标签: ruby