public
Last active

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
module Kernel
def maybe(*path)
return path.inject(self) do |obj, method|
return nil if obj.nil?
if method.respond_to? :keys
obj.send(method.first[0], *method.first[1])
else
obj.respond_to?(:keys) ? obj[method] : obj.send(method)
end
end
end
end
 
 
class Cart
attr_reader :order
def initialize(order = nil)
@order = order
end
end
 
class Order
def initialize(lines = [])
@lines = lines
end
 
def size()
@lines.size
end
 
def line(index)
@lines[index]
end
end
 
class OrderLine
attr_reader :product, :qty
 
def initialize(product, qty=1)
@product = product
@qty = qty
end
end
 
class Product
attr_reader :name, :details
def initialize(name, details = {})
@name = name
@details = details
end
end
 
 
# no objects in call path are nil
cart = Cart.new(Order.new([ OrderLine.new(Product.new("Laptop"), 2), OrderLine.new(Product.new("Desktop"), 3) ]))
puts cart.maybe(:order, :size) # => 2
puts cart.maybe(:order, {:line => [1]}, :product, :name) # => Desktop
 
# the order is nil
emptyCart = Cart.new
puts emptyCart.maybe(:order, {:line => [1]}, :product, :name) # => nil
 
# the product on the first line item is nil
emptyLine = Cart.new Order.new([ OrderLine.new(nil) ])
puts emptyLine.maybe(:order, {:line => [0]}, :product, :name) # => nil
 
# retrieve hash values as well
line = OrderLine.new(Product.new("Keyboard", {:qwerty => true, :keys => 101}), 2)
puts line.maybe(:product, :details, :keys) # => 101

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.