Skip to content

Instantly share code, notes, and snippets.

@ErnestK
Last active January 9, 2018 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ErnestK/d89750e402a3ef6a6ffd41e3d3e10fb3 to your computer and use it in GitHub Desktop.
Save ErnestK/d89750e402a3ef6a6ffd41e3d3e10fb3 to your computer and use it in GitHub Desktop.
class OperationService
attr_reader :errors, :params
# always run
def sstep!(action)
begin
result = method(action).call
add_errors(step_name: action, errors: result) if NEGATIVE_RESULTS.include? result
rescue => ex
add_errors(step_name: action, errors: ex.message)
end
self
end
# run only if all prev result success
def ssuccess!(action)
sstep!(action) if @errors.nil?
self
end
# run only if fail occur in prev steps
def sfailure!(action)
sstep!(action) unless @errors.nil?
self
end
private
NEGATIVE_RESULTS = [nil, false].freeze
def success?
@errors.nil?
end
def failure?
!success?
end
def add_errors(step_name:, errors:)
@errors ||= []
@errors << { step_name: step_name, errors: errors }
end
end
class MyOperation < OperationService
def call
sstep! :throw_err
sstep! :hey
ssuccess! :add_x
sstep! :return_nil
sfailure! :add_y
ssuccess! :add_x
end
def hey
p 'hey!'
end
def add_x
@x = x + 1
end
def x
@x || 0
end
def add_y
@y = y + 1
end
def y
@y || 0
end
def throw_err
fail StandardError, 'error message!'
end
def return_nil
nil
end
end
v = MyOperation.new.call
v
v.errors
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment