I'm trying to use Ruby modules (mixins).
I have test.rb:
#!/usr/bin/env ruby require_relative 'lib/mymodule' class MyApp include MyModule self.hallo end
and lib/mymodule.rb:
module MyModule def hallo puts "hallo" end end
Quite simple setup. But it does not work :( :
ruby test.rb test.rb:8:in `<class:MyApp>': undefined method `hallo' for MyApp:Class (NoMethodError) from test.rb:6:in `<main>'
Where is my error?
What's the difference between "include" and "require" in Ruby? The include and require methods do very different things. The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice.
include is the most used and the simplest way of importing module code. When calling it in a class definition, Ruby will insert the module into the ancestors chain of the class, just after its superclass.
In simple words, the difference between include and extend is that 'include' is for adding methods only to an instance of a class and 'extend' is for adding methods to the class but not to its instance.
Indeed, a module can be included in another module or class by using the include , prepend and extend keywords. Before to start this section, feel free to read my article about the Ruby Object Model if you're unfamiliar with the ancestor chain in Ruby.
In short: you need to extend
instead of include
the module.
class MyApp extend MyModule self.hallo end
include
provides instance methods for the class that mixes it in.
extend
provides class methods for the class that mixes it in.
Give this a read.
The issue is that you are calling hallo
in the class definition, while you add it as an instance method (include
).
So you could either use extend
(hallo
would become a class method):
module MyModule def hallo puts "hallo" end end class MyApp extend MyModule self.hallo end
Or either call hallo
in an instance of MyApp:
module MyModule def hallo puts "hallo" end end class MyApp include MyModule end an_instance = MyApp.new an_instance.hallo
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