The following is a guest post by Samuel Owens and originally appeared on his blog. Samuel is currently in the Ruby-003 class at The Flatiron School. You can follow him on Twitter here.
Yesterday I found myself writing my first module. For those who don’t know, in ruby a module is a package of methods that you write and store in a seperate place, which you can call on inside a class to include the methods contained within. These are used when you want to have the exact same methods included in multiple places, using a module is cleaner and DRY’er than repeating the method definitions in every class.
There are two ways to add a module to a class, include and extend.
The include keyword will bring the module methods into the class as instance methods, allowing instances of the class to use the methods. The extend keyword will bring the module methods into the class as class methods, allowing the class itself to call those methods.
It’s important to understand which of these two are appropriate to use on the module and to design and structure your module so that it can be used correctly. If you use the wrong keyword to bring the module into a class you will not end up with the expected functionality. Additionally, modules should be designed and structured with this in mind, separating methods that are intended to be instance methods from those that are intended to be class methods.