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
  end
  def a2
  end
end
module B
  def b1
  end
  def b2
  end
end

class Sample
include A
include B
  def s1
  end
end

samp=Sample.new
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
 end
end
class A
 include Calculator
 def calculate
   add(2,3)
 end
end

p = A.new
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
 end
end
class A
 extend Calculator
end

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.new
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)
    base.extend(ClassMethods)
 end

 def brand
    "acme"
 end

 module ClassMethods
    def all
     # get all of the AcmeModel instances
     []
    end
 end
end

class Widget
 include AcmeModel
end

w = Widget.new
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.

References:


Comments

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 class MessagesController < ApplicationController   def index     @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 == DateTime .now.to_date }     if @grouped_messages [ false ].present?       #Create month wise groups of messages             @month_wise_sorted_alerts  = @grouped_messages [ false ].group_by{ |t| t.created_at.month}     end       end end @message .group_by{ |t| t.created_at.to_date...

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:  https://play.google.com/store/apps/details?id=com.whizdm.moneyview&hl=e...

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 ] array.map { |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. Use 5 .. 9 over 5 .. 9 Use 'a' .. 'z' over 'a' .. 'z' When using switch case statements use the following indentation. case when input = '+' puts 'The operation is addition' when '-' puts 'The operation is subtraction' when '*' puts 'The operation is multiplication' else puts 'The operat...