Skip to content

Instantly share code, notes, and snippets.

@robjacoby
Created December 2, 2015 00:20
Show Gist options
  • Save robjacoby/3d7b016fdb267e6ea0be to your computer and use it in GitHub Desktop.
Save robjacoby/3d7b016fdb267e6ea0be to your computer and use it in GitHub Desktop.
Lotus / JSONAPI / Reform Errors
ErrorsRepresenter.new(@operation.errors).to_json
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
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