0
0
RubyHow-ToBeginner · 3 min read

How to Create Custom Mixin in Ruby: Simple Guide

In Ruby, you create a custom mixin by defining a module with methods you want to share, then include it in any class using include ModuleName. This lets multiple classes reuse the same code without inheritance.
📐

Syntax

A custom mixin in Ruby is created using a module. You define methods inside the module, then add it to a class with include ModuleName. This adds the module's methods as instance methods to the class.

  • module ModuleName: Defines the mixin container.
  • def method_name: Defines a method inside the module.
  • include ModuleName: Adds the module's methods to a class.
ruby
module Greetings
  def say_hello
    "Hello from mixin!"
  end
end

class Person
  include Greetings
end
💻

Example

This example shows a Greetings module mixed into two classes, Person and Robot. Both classes get the say_hello method from the mixin.

ruby
module Greetings
  def say_hello
    "Hello from mixin!"
  end
end

class Person
  include Greetings
end

class Robot
  include Greetings
end

p = Person.new
r = Robot.new
puts p.say_hello
puts r.say_hello
Output
Hello from mixin! Hello from mixin!
⚠️

Common Pitfalls

One common mistake is using extend instead of include when you want instance methods. extend adds methods as class methods, not instance methods. Also, avoid defining state (instance variables) in modules as it can cause confusion.

ruby
module Greetings
  def say_hello
    "Hello from mixin!"
  end
end

class Person
  extend Greetings  # Wrong if you want instance methods
end

p = Person.new
# p.say_hello  # This will cause an error

# Correct way:
class Person
  include Greetings
end

p = Person.new
puts p.say_hello
Output
Hello from mixin!
📊

Quick Reference

ActionSyntaxDescription
Define mixinmodule ModuleName ... endCreate a module to hold reusable methods
Add mixin to classinclude ModuleNameAdd module methods as instance methods
Add mixin as class methodsextend ModuleNameAdd module methods as class methods
Call mixin methodobject.method_nameUse the method from the mixin on an instance

Key Takeaways

Create a custom mixin by defining a module with methods.
Use include to add mixin methods as instance methods to a class.
Avoid using extend when you want instance methods from a mixin.
Mixins help share code without inheritance in Ruby.
Keep mixins focused on behavior, not state.