Skip to content

Instantly share code, notes, and snippets.

@andresf
Last active April 28, 2017 17:37
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andresf/7777697 to your computer and use it in GitHub Desktop.
Save andresf/7777697 to your computer and use it in GitHub Desktop.
Expose more information about validation errors in Rails
module ActiveModel
class Errors
def error_types
@_error_types ||= Hash.new { |hash, key| hash[key] = [] }
end
def add_with_save_names(attribute, message = nil, options = {})
message ||= :invalid
message = message.call if message.is_a?(Proc)
error_types[attribute] << message
add_without_save_names(attribute, message, options)
end
def to_representable
errors = self
error_types = errors.error_types.dup
full_messages = errors.old_full_messages.dup
error_types.each_key { |key| error_types[key].uniq! }
errors_as_struct = []
errors.messages.each do |attribute_key, error_messages|
error_messages.uniq.each do |error_message|
full_message = full_messages.shift
attribute = full_message.gsub(error_message, '').strip
attribute = attribute.gsub(/\[\d+\]/, "")
errors_as_struct <<
OpenStruct.new(attribute: attribute,
message: error_message,
error_code: error_types[attribute_key].shift,
attribute_key: attribute_key)
end
end
errors_as_struct
end
alias_method_chain :add, :save_names
end
end
module Representers
module Errors
module Collection
include Roar::Representer::JSON::HAL
property :time, getter: proc { DateTime.now.utc }
property :http_status_code, getter: proc { |options|
options[:http_status_code] }
collection :errors, {
:extend => Representers::Errors::Resource,
:getter => proc { self.to_representable }
}
end
end
end
module Representers
module Errors
module Resource
include Roar::Representer::JSON::HAL
#Intended for the end-user
property :message
property :attribute
#Intended for the developer
property :attribute_key
property :details
property :error_code
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment