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)
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.
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.
You can only use private methods with:Other methods from the same class. Methods inherited from the parent class. Methods included from a module.
You stumbled over the difference of include
and extend
.
include
makes the method in the included module available to instances of your classextend
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With