now available

now available
Want fresh tech tips in your inbox?

Using Module Mixins to Extend Classes and Objects in Ruby


The module and class below demonstrate how to use instance methods and class methods from "module mixins". The thing to remember is scope. For instance, to use class methods within instance methods you need to call them from the class itself. This is accomplished something like this "self.class.class_method_you_want_to_call". The example below should make it more clear. It would be natural to assume using "self.method_name" within your module mixin, because after all, instance methods just work when included this way. However, you need to take an extra step when you want to "extend" the behavior of a class.

To extend a class with a mixin you use the method "self.included(base)". This method takes the parent class "base" as an argument. In the method body you use base.extend to attach class methods. Wrapping up class methods in a module is the easiest way to do it.

module Greeting
  # Instance Methods
  # Usage Martian.new.hello_world
  def hello_world
    "Martian says: Hello " + self.class.planet+"!"

  # Class Methods
  # Usage: Martian.planet
  def self.included(base)
    base.extend ClassMethods
  module ClassMethods
    def planet

class Martian
  include Greeting
  def self.location
    "Martian lives on "+self.planet

p Martian.new.hello_world
p Martian.location
Tagged w/ #base.extend #class methods #extending #including #instance methods #mixins #module mixins #modules #scopeprogramming

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app