ruby

Extending Class methods with Module Mixins

01/02/2016

I’m about to finish the Eloquent Ruby book (excellent book by the way) and keep finding ruby pearls of wisdom. One of these is that you can actually use module mixins to extend class methods! You only need to declare a module mixin as normal, and then include it on the singleton class of your declared class (“Klass” in our example).

# module
module Findable
  def find_by_name(name)
    # find something
  end
end

# Class
class Klass
  # class stuff
  class << self
    include Findable
  end
end

Then we can use it just like any other class method.

Klass.find_by_name('John')