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…

5 Useful Android Apps

There are many apps available for Android but these are some useful apps which I use regularly.
1. Money View: Financial Planning
Description: With the Free Money View app, you get a real-time visibility into your entire Personal Finances. It works by itself without any manual data entry - their daily expense manager app organizes our financial summary by analyzing SMS sent by our bank and billers to our phone. The app auto-tracks your expense, bills and account balances across all our financial accounts to help us stay on top of our money. The app is highly secure as it never reads any sensitive data - no full bank account numbers, no OTP, and no Netbanking login/password.
As it anaylzes the money transactions via the SMS in our phone it is highly useful app for tracking our expenses, so we can know our money is going in which direction so we can control it.

More information:

2. To-do List | Task List