Created
May 19, 2015 05:29
-
-
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"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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