Created
December 2, 2015 00:20
-
-
Save robjacoby/3d7b016fdb267e6ea0be to your computer and use it in GitHub Desktop.
Lotus / JSONAPI / Reform Errors
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
ErrorsRepresenter.new(@operation.errors).to_json |
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 Error | |
include Virtus.value_object | |
attribute :id | |
attribute :status | |
attribute :title | |
attribute :detail | |
def self.build_from_lotus(error) | |
new( | |
status: '400', | |
title: ErrorMessage.for(error), | |
detail: ErrorMessage.for(error) | |
) | |
end | |
end | |
Errors = Struct.new(:errors) | |
class ErrorRepresenter < Representable::Decorator | |
include Representable::JSON | |
property :id | |
property :status | |
property :title | |
property :detail | |
end | |
class ErrorsRepresenter < Representable::Decorator | |
include Representable::JSON | |
collection :errors, extend: ErrorRepresenter | |
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
require 'active_support/core_ext/string/inflections' | |
class ErrorMessage | |
DEFAULT_ERROR_MESSAGES = { | |
acceptance: ->(error) { "must be accepted" }, | |
confirmation: ->(error) { "doesn't match" }, | |
exclusion: ->(error) { "shouldn't belong to #{ Array(error.expected).join(', ') }" }, | |
format: ->(error) { "doesn't match expected format" }, | |
inclusion: ->(error) { "isn't included" }, | |
presence: ->(error) { "must be present" }, | |
size: ->(error) { "doesn't match expected size" }, | |
} | |
def self.for(error) | |
new(error).message | |
end | |
def initialize(lotus_error) | |
@lotus_error = lotus_error | |
end | |
def message | |
"#{lotus_error.attribute_name.capitalize} #{DEFAULT_ERROR_MESSAGES.fetch(lotus_error.validation).call(lotus_error)}" | |
end | |
private | |
attr_reader :lotus_error | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment