Ruby Mixins: Reuse Code Like a Pro (Without Inheritance Headaches)
Modules & Mixins in Ruby — Sharing is Caring (Without the Mess)
CodeCraft Diaries #8 • For Ruby Freshers, Students & Developers
"Code duplication is like wearing the same socks three days in a row — it gets smelly fast."
Ever copy-pasted a method from one class to another and thought: “I’ll clean this later...” Spoiler: You won’t. ๐
That’s where **Modules** and **Mixins** come in — Ruby’s way of letting you *share code like a pro*, without inheritance spaghetti or duplicate soup.
๐ค What Is a Module?
Think of a module as a toolbox. It’s not a class. You can’t make objects out of it. But you can pack it with reusable methods and include it wherever needed.
module Greetings
def hello
puts "Hello, Rubyist!"
end
end
Now you’ve got a method... just chilling inside a module, waiting to be mixed in.
๐งช Using Modules as Mixins (The Magic of include
)
class Student
include Greetings
end
s = Student.new
s.hello # "Hello, Rubyist!"
include
brings in the module’s methods as instance methods.
It’s like saying: “Yo class, here’s a new set of powers.” ๐ช
๐ What About extend
?
While include
adds methods to instances, extend
adds them to the class itself.
module AdminTools
def shutdown
puts "System is going down!"
end
end
class Server
extend AdminTools
end
Server.shutdown # works!
Summary:
include
= instance methodsextend
= class methods
๐จ๐ฉ๐ง Why Not Just Use Inheritance?
Inheritance is great... until it’s not.
- It ties you down to a hierarchy
- It leads to tight coupling
- Ruby doesn’t support multiple inheritance anyway ๐ฌ
Modules solve all of this. You can mix in multiple modules to one class and build behavior like LEGOs.
๐ง Real-World Example
Imagine a project with two types of users: students and admins. Both should be able to log in and log out. Instead of repeating code:
module Auth
def login
puts "#{self.class} logged in"
end
def logout
puts "#{self.class} logged out"
end
end
class Student
include Auth
end
class Admin
include Auth
end
Now both classes have login/logout abilities — no duplication, no drama.
๐ซ Common Mistakes
- Trying to instantiate a module (
Module.new
won’t help you ๐ ) - Forgetting whether you want
include
orextend
- Putting unrelated methods in one giant module (Modularity, remember?)
๐งช Mini Challenge
Create a module Logger
with a method log_info
that prints a message with a timestamp.
Mix it into a class and call it!
module Logger
def log_info(msg)
puts "[#{Time.now}] #{msg}"
end
end
๐ Quick Recap
- Modules help you group reusable code
include
for instance methodsextend
for class methods- Mixins let you avoid deep inheritance trees
๐ Related Reads
- Ruby Iterators — When Loops Just Aren’t Elegant Enough
- Procs & Lambdas in Ruby — The Cousins You Need to Know
๐ข Up Next on CodeCraft Diaries
CodeCraft Diaries #9: “File Handling in Ruby — Reading, Writing, and What Could Go Wrong”
Comments
Post a Comment