Skip to content

Instantly share code, notes, and snippets.

@alebian
Created April 10, 2018 13:58
Show Gist options
  • Save alebian/0b5c4432f7f8dcff00309870f0c2c9b8 to your computer and use it in GitHub Desktop.
Save alebian/0b5c4432f7f8dcff00309870f0c2c9b8 to your computer and use it in GitHub Desktop.
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
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