Skip to content

Instantly share code, notes, and snippets.

@marioaquino
marioaquino / pilotable.rb
Last active December 19, 2015 10:09
The Pilotable proxy to the Drone (uses Forwardable to achieve ISP)
require 'forwardable'
class Pilotable
extend Forwardable
def_delegators :@aircraft, :take_off, :land, :fly_to
def initialize(aircraft)
@aircraft = aircraft
end
end
@marioaquino
marioaquino / drone.rb
Last active December 19, 2015 08:59
ISP in Ruby
class Drone
def launch_missiles_at(x, y, z)
end
def take_picture_of(x, y, z)
end
def take_off
puts 'taking off...'
end
#boom!!! a RecordNotFoundError is thrown out of this call
my_user = get_user("user id that will fail")
my_user_either = get_user("bogus user id")
if my_user_either.value?
#do whatever with my_user_either.value
else if my_user_either.invalid?
log.info("Didn't find the user...")
#do something with my_user_either.error
end
class Either
attr_reader :value, :error
def initialize(value: :none, error: :none)
raise ArgumentError.new("Either a value or an error please, not both") if (value != :none and error != :none)
raise ArgumentError.new("Either a value or an error please, please give me one") if (value == :none and error == :none)
@value = value
@error = error
end
def invalid?
class NullProduct < Product
def cost
'$0.00'
end
end
class PerishableProduct < Product
def shelf_life
#something
end
end
class Product
def cost
#some value
end
end
my_user = get_user('some_id_that_may_or_may_not_exist')
if my_user
#do some stuff
else
#do the equivalent of what the rescue block above did
end
begin
my_user = get_user("bogus user id")
rescue RecordNotFoundError
log.info("Didn't find the user...")
#return nil? return a "new" user object?
#re-raise the error wrapped in a different one?
#something else?
end