Skip to content

Instantly share code, notes, and snippets.

@tubbo
Created May 19, 2015 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tubbo/12a97a4f3f6b544e78f4 to your computer and use it in GitHub Desktop.
Save tubbo/12a97a4f3f6b544e78f4 to your computer and use it in GitHub Desktop.
Playing around with promises in Ruby, inspired by Sandi Metz' talk "Nothing Is Something"
class Promise
attr_reader :object
def initialize(object)
@object = object
end
def try(method)
@tries << method
self
end
def otherwise(method)
@catches << method
self
end
def call
@tries.each do |function|
function.call(object, self)
end
rescue StandardError => exception
@catches.each do |function|
function.call(exception, self)
end
end
def method_missing(_)
call
end
def respond_to?(_)
true
end
end
class Object
def try(&block)
Promise.new(self).try(block)
end
def otherwise(&block)
Promise.new(self).otherwise(block)
end
end
class MyObject
def initialize(name)
@name = name
end
def to_s
@name
end
end
obj = MyObj.new('name')
obj.try(&:to_s).try(&:what).otherwise do |error|
puts error.message
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment