When to use Ruby DelegateClass instead of SimpleDelegator? (DelegateClass method vs. SimpleDelegator class)

Alexey picture Alexey · Oct 28, 2012 · Viewed 10k times · Source

Probably i am missing something simple, but i do not understand how to use Ruby's DelegateClass method, i mean when to use it instead of SimpleDelegator class. For example, all of the following seem to work mostly identically:

require 'delegate'

a = SimpleDelegator.new([0])
b = DelegateClass(Array).new([0])
c = DelegateClass(String).new([0])
a << 1
b << 2
c << 3
p a # => [0, 1]
p b # => [0, 2]
p c # => [0, 3]

Note that it does not seem to matter which class is passed to DelegateClass.

Answer

jtzero picture jtzero · Nov 12, 2012

Use subclass SimpleDelegator when you want an object that both has its own behavior and delegates to different objects during its lifetime.

Essentially saying use DelegateClass when the class you are creating is not going to get a different object. TempFile in Ruby is only going to decorate a File object SimpleDelegator can be reused on different objects.

Example:

require 'delegate'


class TicketSeller
  def sellTicket()
    'Here is a ticket'
  end
end


class NoTicketSeller
  def sellTicket()
    'Sorry-come back tomorrow'
  end
end


class TicketOffice < SimpleDelegator
  def initialize
    @seller = TicketSeller.new
    @noseller = NoTicketSeller.new
    super(@seller)
  end
  def allowSales(allow = true)
    __setobj__(allow ? @seller : @noseller)
    allow
  end
end

to = TicketOffice.new
to.sellTicket   »   "Here is a ticket"
to.allowSales(false)    »   false
to.sellTicket   »   "Sorry-come back tomorrow"
to.allowSales(true)     »   true
to.sellTicket   »   "Here is a ticket"

Here is another good explanation a-delegate-matter