Skip to main content

Ruby Mixins

What’s a Mixin?

A mixin can basically be thought of as a set of code that can be added to one or more classes to add additional capabilities without using inheritance. In Ruby, a mixin is code wrapped up in a module that a class can include or extend. In fact, a single class can have many mixins.

When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance.

Ruby does not support multiple inheritance directly but Ruby Modules have another wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.

module A
  def a1
  def a2
module B
  def b1
  def b2

class Sample
include A
include B
  def s1
samp.a1 # From module A
samp.a2 # From module A
samp.b1 # From module B
samp.b2 # From module B
samp.s1 # Instance method

In the example above, the object of the class Sample is able to call the methods of the module A as well as module B. Hence, we get the multiple inheritance.

Include vs Extend

Modules can either be included or extended depending on whether the methods will be added as instance methods or class methods, respectively.

# Include the Module
module Calculator
 def add(x,y)
   x + y
class A
 include Calculator
 def calculate

p =
puts p.calculate # Puts 5

In the example above a Calculator module is defined which sums up two integers via the add method. The A class includes the Calculator module which will add its methods as instance methods to the A class. It’s worth noting that everything defined in the module is added to the class including methods (public, protected, private), attributes (e.g. attr_accessor :name) and constants.

If instead we wanted to provide a add via a class method I’d use the extend method as shown below.

# Extend the Module
module Calculator
 def add(x,y)
   x + y
class A
 extend Calculator

puts A.add(4,5) # Puts 9

It’s also possible to mixin a module to a single instance at runtime as shown in the following example.

# Extending the Module at the runtime
class B; end
b =
b.extend Calculator
puts b.add(5,2)

Another common pattern is to define a module that will mixin instance and class methods.

module AcmeModel
 def self.included(base)

 def brand

 module ClassMethods
    def all
     # get all of the AcmeModel instances

class Widget
 include AcmeModel

w =
w.brand # "acme" is the output,
Widget.all  # invoke the class method that was added

In this example the AcmeModel provides an instance method named brand. More importantly it overrides the included class method, provided by the Module class. The included method is a callback that gets invoked whenever the module is included by antoher class or module. At that point we extend the class that included the AcmeModel, the Widget class in this example, with the ClassMethods module.

Lastly, you should also know that your module can override the extended class method which acts as callback when the module is extended.



Popular posts from this blog

Rails: Grouping the records by group_by method

Many times we come across such situations where we need to group records, like when we want to display grouped messages, email, alerts .etc based on date or time. Here is the simple code which provides a significant use of group_by method.
Controller Part

classMessagesController < ApplicationController
@message = Message.all

#Retrives all messages and divides into two groups todays messages and other messages
@grouped_messages = @message.group_by{ |t| t.created_at.to_date == }

OOP Polymorphism

Definition: "Poly" stands for "many" and "morph" stands for "forms". Generally, polymorphism means one name different uses. Technically, it means being able to send the same message to different objects and get different result.
Polymorphism through Inheritance
We can achieve polymorphism through inheritance. For example
classGenericParser defparseraiseNotImplementedError, 'You must implement the parse method'endendclassJsonParser < GenericParserdefparseputs'An instance of the JsonParser class received the parse message'endendclassXmlParser < GenericParserdefparseputs'An instance of the XmlParser class received the parse message'endendHere the GenericParser is the base class. Class JsonParser and XmlParser are inherited from the GenericParser.
Now suppose we run the below code.
puts'Using the XmlParser' parser = parser.parse puts'Using the JsonParser' parser = parser.parseThe o…

List of Common mistakes in Ruby

Always use spaces around operators, after commas, colons and semicolons, around { and before }. White space might be (mostly) irrelevant to the Ruby interpreter, but its proper use is the key to writing easily readable code. Also it makes the design more readable and code much cleaner.
product = 1 * 2 array = [1, 2, 3, 4, 5] { |a| a + 2 }

There should be no spaces after (, [ or before ], ) these brackets.
['ankur', 'vyas'] sum(a, b)
Also don't use spaces in while providing the range.
Use5..9 over 5 .. 9Use'a'..'z' over 'a' .. 'z'
When using switch case statements use the following indentation.
casewhen input = '+'puts'The operation is addition'when'-'puts'The operation is subtraction'when'*'puts'The operation is multiplication'elseputs'The operation is division'end
Use following indentation if the parameters exceeds to more than one line.
defsend_mail(source) Mailer.deliver(…