Modules are one of the most interesting features of Ruby. It is useful to avoid clashes with existing class, methods, etc. So that You can add(mix in) the functionality of modules into your classes. You can use them to attach specific behaviour on your classes, and organise your code using composition rather than inheritance.
Many Ruby developer are familiar with “extend” or “include“, to understand how prepend works, it’s important to know that how include/extend works in Ruby.
module Xyz
def test_method
puts "Hello from module."
end
end
Include
class Abc
include Xyz
It mixes in specified module methods as instance methods in the target class e.g. It adds the methods in Xyz to the Abc class as instance methods.
Extend
class Abc
extend Xyz
It mixes in specified module methods as class methods in the target class e.g. It adds the methods in Xyz to the Abc class as class methods.
When you call a method on an object, the Ruby interpreter tries to find that method definition in its class, if it doesn’t find it, it checks the class it inherits from (superclass), and so on till it does. So when you use Include in a module, Ruby interpreter does is to inserts the included module right above the current class. This means that Xyz module is the superclass or parent class of Abc class.
Prepend
But prepend is slightly different different from Include/Extend, it is just opposite of Include/Extend means it puts the prepended module below the current class. It means that Abc class is the superclass or parent class of Xyz module.
class Abc
prepend Xyz
How is it useful ?
module Xyz
def test_method
puts "Hello from module"
super
end
end
class Abc
prepend Xyz
def test_method
puts "Hello from classes"
OR
//your code
end
end
That's all for today!, Happy coding :)