Skip to content

Instantly share code, notes, and snippets.

@colindensem
Created June 3, 2021 10:36
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 colindensem/f088c325baa599a7e9b8b18e06f12f65 to your computer and use it in GitHub Desktop.
Save colindensem/f088c325baa599a7e9b8b18e06f12f65 to your computer and use it in GitHub Desktop.
A result handling object
module Callable
extend ActiveSupport::Concern
class_methods do
def call(*args)
new(*args).call
end
end
end
> sp = ServicePoro.call('pass')
> sp.success?
> true
> sp.failure?
> false
> sp.errors
> []
> sp = ServicePoro.call('left')
> sp.success?
> false
> sp.failure?
> true
> sp.errors
> ['Given arg1 was not a pass']
class Result
def initialize(payload = {})
@payload = payload
@errors = []
@success = true
end
def successful?
@success && errors.empty?
end
alias success? successful?
def failure?
!successful?
end
def fail!
@success = false
end
def add_error(*errors)
@errors << errors
@errors.flatten!
nil
end
def errors
@errors.dup
end
def prepare!(payload)
@payload.merge!(payload)
self
end
protected
def method_missing(method_name, *)
@payload.fetch(method_name) { super }
end
end
class ServicePoro
include Callable
attr_reader :result
def initialize(arg1 = 'fail')
self.result = Result.new
self.arg1 = arg1
end
def call
result.prepare!(data: { arg1: arg1 })
if arg1 == 'pass'
result.prepare!(data: { status: 'pass' })
else
result.fail!
result.add_error('Given arg1 was not a pass')
result.prepare!(data: { status: 'fail' })
end
result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment