How to Use Mixins and Modules in Your Ruby on Rails Application

Cleiviane Cleiviane Costa on

Modules and mixins are, without doubt, great resources that make Ruby so attractive. They give the application the ability to share the code that can be used with ease in other places. It also helps us organize our code by grouping functionalities and concerns, which improves the readability and maintainability of our code.

In this article, we will go through the concepts behind modules and mixins. We’ll learn how to create and mix modules into other classes and discuss the benefits of using them in a Ruby on Rails application.

I hope you’ll enjoy the journey!

What are Modules

Modules are one of the shiniest resources of Ruby because they provide two great benefits: we can create namespaces to prevent name clashes and we can use them as mixins to share code across the application.

In structural terms, a module is pretty similar to any Ruby class. In fact, for Ruby, a Class is a Module, as we can see below in an irb console:

1
2
> Class.is_a?(Module)
 => true

Similar to classes, with modules we also group methods and constants and share code. However, there are a few differences between a module and a plain Ruby class:

Modules are great places to have services, concerns, constants and any other code that, by having the same responsibility they should stay together.

This is how a module should look like:

1
2
3
4
5
6
7
8
9
10
11
12
13
# lib/modules/invoice_creator.rb
module InvoiceCreator
  TAX_FEE = 0.5

  def self.generate
    puts "Don't worry! I'll generate the invoice for you at #{TAX_FEE}%"
  end

  def invoice_total
    puts "I'll return the invoice total"
    1000
  end
end

In this example, we can observe that a module can provide two kinds of methods: module methods and instance methods.

The self.generate is a module method, which means that we can use it without having to include (or extend) the module in any other object. This is very common when we are creating service objects, for example. We can call our module method like this:

1
2
3
2.5.3 :006 > InvoiceCreator.generate
Don't worry! I'll generate the invoice for you
=> nil

The invoice_total is an instance method and to be able to use it we need to include the module to a class, like this:

1
2
3
4
5
6
7
8
9
10
# app/models/invoice.rb
class Invoice < ApplicationRecord
  include InvoiceCreator # This includes our module in the Invoice class

  def calculate_tax
    total = invoice_total # included method from our module
    tax = total * InvoiceCreator::TAX_FEE
    puts "This is the invoice tax: #{tax}"
  end
end

All instance methods from InvoiceCreator becomes available to the Invoice instances, so we can call the calculate_tax method pretty easily:

1
2
3
4
5
2.5.3 :008 > Invoice.new.calculate_tax
"I'll return the invoice total"
"This is the invoice tax: 500.0"
 => nil
2.5.3 :009 >

In addition, inside the calculate_tax you notice that we are using a constant that was defined inside our module. As I mentioned before, modules are great constant keepers!

Imagine now a scenario where we need to have two kinds of InvoiceCreator to generate totally different invoices for suppliers and customers. We would end up having a name classing, and to avoid this, we make use of the other great benefit of modules: namespaces. Let’s take a look in the next section.

Namespaces Everywhere

Namespaces can be defined as a way to organize our code when we want to create a local context for a given functionality, which is what we need for the scenario I just described: a different context for the customer’s invoice creator and another one for the supplier’s invoice creator.

Let’s get back to our code. We’ll need to create two different modules:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# lib/modules/customer/invoice_creator.rb
module Customer
  module InvoiceCreator
    def self.generate
      puts "Don't worry! I'll generate the customer invoice for you"
    end
  end
end

# lib/modules/supplier/invoice_creator.rb
module Supplier
  module InvoiceCreator
    def self.generate
      puts "Don't worry! I'll generate the supplier invoice for you"
    end
  end
end

Then we can use Customer::InvoiceCreator or Supplier::InvoiceCreator where we need it:

1
2
3
4
5
6
7
2.5.3 :014 > Customer::InvoiceCreator.generate
Don't worry! I'll generate the customer invoice for you
 => nil
2.5.3 :015 > Supplier::InvoiceCreator.generate
Don't worry! I'll generate the supplier invoice for you
 => nil
2.5.3 :016 >

That way each specific code will be wrapped up inside its own module, respecting the separation of concerns principle. Besides that, namespacing everywhere is also a great way to keep our code well organized.

Let’s see now how we can make use of the other benefits of Ruby modules: mixins.

The Magic of Using Mixins

As you might already know, one characteristic of Ruby is that it implements the single inheritance mechanism, which means that a class can only inherit from one other class. We may often need to inherit from more classes. In Ruby, we can cover that need by using the composition over inheritance pattern.

This is doable by using the mixins. When we mix in a piece of code in another Ruby class we are adding to this class more behavior without using inheritance and this is amazing. Therefore, in Ruby, mixins are modules that we include in classes where they are needed. With that we gain by keeping our code clean and the responsibilities separated, as they should be.

For example, let’s say that our InvoiceCreator module is a service that needs to use functionalities provided by several other modules, such as InvoiceCalculator, InvoiceRenderer and InvoiceSender, they will be necessary to fulfill the invoice creation process.

We can achieve this by including a chain of modules as mixins in our code, so we can use the methods directly, like the example below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# lib/modules/invoice_calculator.rb
module InvoiceCalculator
  def calculate_items_total
    puts "imagine some math here"
  end
end

# lib/modules/invoice_renderer.rb
module InvoiceRenderer
  def generate_invoice_pdf
    puts "imagine that we are using some PDF generation magic here"
  end
end

# lib/modules/invoice_sender.rb
module InvoiceSender
  def send_invoice
    puts "imagine your favorite mail service being used here"
  end
end

Since we can’t make the InvoiceCreator inherit from all the other three modules, we are including them instead. This way the InvoiceCreator includes all the methods from the other Invoice modules, and we can call these in any class/module the InvoiceCreator module gets included in. Be careful though! If any of the modules have methods with the same name, they will overwrite each other.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# lib/modules/customer/invoice_creator.rb
module Customer
  module InvoiceCreator
    include InvoiceCalculator
    include InvoiceRenderer
    include InvoiceSender

    def generate_invoice
      calculate_items_total # from InvoiceCalculator
      generate_invoice_pdf # from InvoiceRenderer
      send_invoice # from InvoiceSender
    end
  end
end

Now we can call our service methods anywhere we include it by doing this:

1
2
3
4
5
6
7
8
9
# app/models/invoice.rb
class Invoice < ApplicationRecord
  include Customer::InvoiceCreator

  def send_invoice_to_customer
    puts "Don't worry! I'll generate the customer invoice for you"
    generate_invoice
  end
end

This will be the result, calling the methods from the included Invoice modules through the InvoiceCreator module:

1
2
3
4
5
6
2.5.3 :051 > Invoice.new.generate_invoice
Don't worry! I'll generate the supplier invoice for you
imagine some math here
imagine that we are using some PDF generation magic here
imagine your favorite mail service being used here
 => nil

Notice that this is how we use composition over inheritance principle. This principle stands that you should prefer to use composition whenever you can. In composition, we create classes that are responsible to provide specific functionalities to others, which is exactly what we are doing.

That’s all Folks!

As Ruby developers, we love to use its facilities and syntax sugar when planning, writing, maintaining and refactoring our code. I hope that through this article you can appreciate why modules are such a great resource to help improve the readability of our code, to keep things with only one responsibility and to keep our codebase clean and easy to maintain. And also that we can use the mixins magic to include modules in our code in cases where we would need to inherit from multiple sources.

We’ll keep talking about the greatest resources of Ruby and Rails here, so stay tuned!

P.S. If you’d like to read Ruby Magic posts as soon as they get off the press, subscribe to our Ruby Magic newsletter and never miss a single post!

Our guest author Cleiviane Costa is a software engineer with 10+ years of experience. She’s passionate for Ruby on Rails and loves to write about things that she discovers in her day-to-day activities.

5 favorite Ruby articles

10 latest Ruby articles

Go back
Ruby magic icon

Subscribe to

Ruby Magic

Magicians never share their secrets. But we do. Sign up for our Ruby Magic email series and receive deep insights about garbage collection, memory allocation, concurrency and much more.

We'd like to set cookies, read why.