Ruby | SimpleDelegator Methods

Derek Dyer
Nov 9, 2017 · 4 min read

Context

Basic Decorator Pattern

require 'date'
class Slurpee
attr_reader :flavor, :size, :cost
def initialize(flavor, size, cost)
@flavor = flavor
@size = size
@cost = cost
end
end
class SlurpeeDayDecorator < SimpleDelegator
def serve
"Serving one #{size} slurpee in a delicious flavor #{flavor} and it will cost you $#{cost}"
end
end
slurpee = Slurpee.new('🍉', 'massive', 5.00)
slurpee_day = SlurpeeDayDecorator.new(slurpee)

__getobj__

...def foo
puts __getobj__
end
...
def foo
puts __getobj__.cost
end
def cost
__getobj__.cost - __getobj__.cost
end
class Slurpee
attr_reader :flavor, :size, :cost
def initialize(flavor, size, cost)
@flavor = flavor
@size = size
@cost = cost
end
def free_slurpee_day
today = Date.today
year = today < Date.new(today.year, 8, 21) ? today.year : today.year + 1
Date.new(year, 8, 21)
end
end
def free_slurpee_day
number_of_days = __getobj__.free_slurpee_day — Date.today
“There are #{number_of_days.to_i} days until Free Slurpee Day”
end

__setobj__

class HotDog
attr_reader :size, :cost
def initialize(size, cost)
@cost = cost
@size = size
end
def free_day
today = Date.today
year = today < Date.new(today.year, 8, 21) ? today.year : today.year + 1
Date.new(year, 8, 21)
end
end
class FreeDecorator < SimpleDelegator
def free_day
number_of_days = __getobj__.free_day - Date.today
"There are #{number_of_days.to_i} days until Free #{format_constant} Day"
end
def serve
"Dispensing one #{size} #{format_constant} in a delicious flavor #{flavor} and it will cost you $#{cost}"
end
def cost
__getobj__.cost - __getobj__.cost
end
private def format_constant
__getobj__.class.name.gsub(/(?<=[a-z])(?=[A-Z])/, ' ')
end
end

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade