Featured image

One of the coolest features of Ruby is that you can implement composition in several different ways. For instance, beyond the classic approach of chaining nested objects, Ruby also allows you to build composition using modules (mixins). I realize that many developers might find this pattern controversial, but the fact that this exact concept powers the plugin architecture of gems like Roda and Shrine makes me pause and look at it in a different light. And since include is just a regular method, and Ruby objects possess their own singleton class (eigenclass), you can take it a step further and include a module for a specific instance:

module Insurance
  def price = super + (@price * 0.1).to_i
end

need_insurance = true
phone = Phone.new(1200)
phone.singleton_class.include(Insurance) if need_insurance
phone.price # => 1395

How do you implement composition in your projects? Do you know other approaches to achieve it?

class Product
  include(Base = Module.new do
    def initialize(price)
      @price = price
    end
    def price = @price
  end)
end

module Delivery
  def price = super + 70
end

module Tax
  def price = super + 5
end

Phone = Class.new(Product) do
  include Delivery
  include Tax
end

Phone.new(1000).price # => 1075