Created
September 8, 2021 11:34
-
-
Save rx/5f97dff42cbc924b6753431c40e8dc62 to your computer and use it in GitHub Desktop.
Response Object
This file contains 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 Response | |
SUCCESS = 0 | |
FAILURE = 1 | |
attr_reader :data, :status, :messages | |
def initialize(data: [], | |
status: SUCCESS, | |
messages: {}) | |
@data = data | |
@status = status | |
@messages = Messages.new(messages) | |
end | |
# If your data either is a hash or is an array containing one hash | |
# This helper allows you to treat the result object as a hash | |
# returns nil if there is more than one element in the data | |
# Or if the data is empty | |
def [](key) | |
return data[key] if data.respond_to?(:key?) #quacks like a hash | |
return data.send(key.to_sym) if data.respond_to?(key.to_sym) #behaves like a model/entity | |
return nil if data.empty? or data.size > 1 | |
data.first[key] if data.first.respond_to?(:key?) | |
end | |
def <<(output) | |
@data << output | |
end | |
def succeeded? | |
@status == SUCCESS | |
end | |
alias success? succeeded? | |
def failed? | |
!succeeded? | |
end | |
alias fail? failed? | |
def to_h | |
{data: data, | |
status: status, | |
message: messages.to_h} | |
end | |
def errors | |
@messages.errors | |
end | |
def warnings | |
@messages.warnings | |
end | |
class Messages | |
attr_reader :warnings, :errors | |
def initialize(errors: {}, warnings: {}) | |
@errors = errors | |
@warnings = warnings | |
end | |
def to_h | |
{ | |
errors: errors, | |
warnings: warnings | |
} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment