Last active
April 28, 2017 17:37
-
-
Save andresf/7777697 to your computer and use it in GitHub Desktop.
Expose more information about validation errors in Rails
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
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 |
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
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