Created
April 10, 2018 13:58
-
-
Save alebian/0b5c4432f7f8dcff00309870f0c2c9b8 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 |
This file contains hidden or 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
result = Gracefully.handle { ComplicatedService.new(foo, bar).process } | |
if result.success? | |
# do success stuff | |
use_value(result.value) | |
else | |
# do failure stuff | |
log_error(result.error) | |
end | |
Gracefully.handle { SomeComplicatedService.new.call }.on_success do |val| | |
val.update!(column_name: 'stuff') | |
end | |
Gracefully.handle { SomeComplicatedService.new.call }.on_failure do |e| | |
do_whatever_you_wish_with_the_error(e) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment