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 XyzIt 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 XyzIt 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 ?
Suppose you stuck in a situation that you have a number of classes which contain method name "test_method" which contain code and some lines of code are similar in all "test_methods" of all classes which you want to execute first and after you want to execute your code then you can do something like below. Here we define module name "Xyz" which have method "test_method" which print statement "Hello from module" and then it call super. Now prepend this module in any class where you want to use this feature. It means when you prepend "Xyz" module in your classes then firstly it will print the statement "Hello from module" and then by super it will invoke the same method name "test_method" in his superclass or parent class and will execute your line of codes e.g. "Hello from classes" after "Hello from module".
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 :)
No comments:
Post a Comment