Skip to content

Instantly share code, notes, and snippets.

@Dagnan
Created October 24, 2012 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dagnan/3946684 to your computer and use it in GitHub Desktop.
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
# -*- 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