Created
April 5, 2018 14:34
-
-
Save katpadi/9aac974a760fc3f5f3a287bb75804de6 to your computer and use it in GitHub Desktop.
Gracefully
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 Gracefully | |
class << self | |
alias_method :handle, :new | |
end | |
attr_reader :error, :value | |
def initialize | |
@value = nil | |
@error = nil | |
begin | |
@value = yield | |
rescue => e | |
@error = e | |
end | |
end | |
def success? | |
error.nil? | |
end | |
def on_success | |
return self unless success? | |
result = yield(@value) | |
return result if result.is_a?(Gracefully) | |
Gracefully.handle { result } | |
end | |
def on_failure | |
return self if success? | |
result = yield(@error) | |
return result if result.is_a?(Gracefully) | |
Gracefully.handle { result } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment