Created
June 3, 2021 10:36
-
-
Save colindensem/f088c325baa599a7e9b8b18e06f12f65 to your computer and use it in GitHub Desktop.
A result handling object
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
module Callable | |
extend ActiveSupport::Concern | |
class_methods do | |
def call(*args) | |
new(*args).call | |
end | |
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
> 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'] | |
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 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 |
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 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