Created
August 5, 2012 22:34
-
-
Save kalorz/3267549 to your computer and use it in GitHub Desktop.
ActiveModel::Errors patch for storing "raw" error messages/symbols in Errors object, before they are translated into human readable messages
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
# This patch is for storing "raw" error messages/symbols in Errors object, before they are translated into human | |
# readable messages. | |
# | |
# u = User.create | |
# u.errors.messages # => {:login => ["cannot be blank"], :year_of_birth => ["must be greater than 1900"]} | |
# u.errors.raw # => {:login => [{:blank => {}], :year_of_birth => [{:greater_than => {:value => 1618, :count => 1900}}]} | |
module ActiveModel | |
class Errors | |
attr_reader :raw | |
# All methods that add or delete original messages must be patched, so original and raw messages are synchronized. | |
def initialize_with_raw(base) | |
@raw = ActiveSupport::OrderedHash.new | |
initialize_without_raw(base) | |
end | |
alias_method_chain :initialize, :raw | |
def initialize_dup_with_raw(other) | |
@raw = other.raw.dup | |
initialize_dup_without_raw(other) | |
end | |
alias_method_chain :initialize_dup, :raw | |
def clear_with_raw | |
raw.clear | |
clear_without_raw | |
end | |
alias_method_chain :clear, :raw | |
def delete_with_raw(key) | |
raw.delete(key) | |
delete_without_raw(key) | |
end | |
alias_method_chain :delete, :raw | |
def add_with_raw(attribute, message = nil, options = {}) | |
add_raw(attribute, message, options) | |
add_without_raw(attribute, message, options) | |
end | |
alias_method_chain :add, :raw | |
private | |
def raw_errors(key) | |
raw[key] ||= [] | |
end | |
def add_raw(attribute, message = nil, options = {}) | |
raw_errors(attribute.to_sym) << {message => options.except(*CALLBACKS_OPTIONS)} | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment