Created
October 24, 2012 15:14
-
-
Save Dagnan/3946684 to your computer and use it in GitHub Desktop.
Building an API with better errors display with JSON. Must be places in config/initializers
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
# -*- encoding : utf-8 -*- | |
ActiveModel::Errors.module_eval do | |
def as_json options = nil | |
@api_errors | |
end | |
def initialize(base) | |
@base = base | |
@messages = ActiveSupport::OrderedHash.new | |
@api_errors = [] | |
end | |
def add(attribute, message = nil, options = {}) | |
message ||= :invalid | |
error_symbol = message if message.is_a?(Symbol) | |
if message.is_a?(Symbol) | |
message = generate_message(attribute, message, options.except(*ActiveModel::Errors::CALLBACKS_OPTIONS)) | |
elsif message.is_a?(Proc) | |
message = message.call | |
end | |
@api_errors << {:attribute => attribute, :error => error_symbol, :message => full_message(attribute, message)} | |
self[attribute] << message | |
end | |
def full_message attribute, message | |
if attribute == :base | |
message | |
else | |
attr_name = attribute.to_s.gsub('.', '_').humanize | |
attr_name = @base.class.human_attribute_name(attribute, :default => attr_name) | |
I18n.t(:"errors.format", { | |
:default => "%{attribute} %{message}", | |
:attribute => attr_name, | |
:message => message | |
}) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment