Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gracefully
class Gracefully
class << self
alias_method :handle, :new
end
attr_reader :error, :value
# Accepts a block, invokes it, and wraps the return value in an
# exception-free `Gracefully` object
#
# Usage Example:
#
# result = Gracefully.handle { ComplicatedService.new(foo, bar).process }
# if result.success?
# do_cool_stuff_when_success
# use_result_value_of_complicated_service(value: result.value)
# # Return the value
# result.value
# else
# do_stuff_when_fail
# do_more_stuff_just_because_you_can
# # Return the error
# result.error
# end
def initialize
@value = nil
@error = nil
begin
@value = yield
rescue => e
@error = e
end
end
def success?
error.nil?
end
# Usage Example:
#
# Gracefully.handle { SomeComplicatedService.new.call }.on_success do |val|
# val.update!(column_name: 'stuff')
# end
#
def on_success
return self unless success?
result = yield(@value)
return result if result.is_a?(Gracefully)
Gracefully.handle { result }
end
# Usage Example:
#
# Gracefully.handle { SomeComplicatedService.new.call }.on_failure do |e|
# do_whatever_you_wish_with_the_error(e)
# 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
You can’t perform that action at this time.