DEV Community

loading...
Cover image for Composition in Ruby

Composition in Ruby

topofocus profile image Hartmut B. ・1 min read

As Rubyists prepare for the most anticipated release of Ruby 3.0, its worth looking to unchanged principles.

Composition

One exiting feature of the ruby language is the presence of Modules.

module LimitOrder
  def price
    @price
  end
end
class Order 
   attr :what, :amount
  (...)
end
class StockOrder < Order
  include LimitOrder
  (...)
end
Enter fullscreen mode Exit fullscreen mode

StockOrder inheritances anything from Order and has access to properties and methods of LimitOrder.

  • include works on instances of an object. Thus, any object generated by Stockorder.new can access the price method.

  • extend on the other hand includes properties and methods to classes and modules.

Instantiate Objects without publicly calling new

Let's design a module OrderPrototype. Its main purpose is to provide a method order, which finally calls Order.new.

module OrderPrototype
  def defaults
   { }
  end
  def order  **fields
    (...)   ## process fields and fillup arguments
    Order.new **arguments
  end
end
Enter fullscreen mode Exit fullscreen mode

The composition process starts by defining a module Limit:

module Limit
 extend OrderPrototype

 class << self
   def defaults
     super.merge { order_type: :limit,  tif: :good_till_cancelled }
   end
 end
end
Enter fullscreen mode Exit fullscreen mode

class << self assigns the following methods to the class-level. defaults are processed by OrderProtoype.order.

Limit.order size: 1, (...) instantiates a specialized Order-Object without inheritance. Other useful order prototypes are Market.order, StopLimit.order a.s.o.

The Limit-object acts as a singleton
masquerading as constructor for conventional ruby objects.

The approach is implemented in: https://github.com/ib-ruby/ib-extensions/blob/master/lib/ib/order-prototypes.rb
and further documented here

Discussion (0)

pic
Editor guide