aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib/active_model/errors.rb
diff options
context:
space:
mode:
authorMartin Svalin <martin@lite.nu>2011-10-19 18:47:28 +0200
committerMartin Svalin <martin@lite.nu>2011-10-19 21:29:20 +0200
commitc9ca86c29d4f4d8e1181c20ac0da8e1027a14344 (patch)
tree9c973e42f16bb24ab09504b8bd5f8eddfdb7951f /activemodel/lib/active_model/errors.rb
parent89a164ab9b028d855023c88e4afcdf55276a1363 (diff)
downloadrails-c9ca86c29d4f4d8e1181c20ac0da8e1027a14344.tar.gz
rails-c9ca86c29d4f4d8e1181c20ac0da8e1027a14344.tar.bz2
rails-c9ca86c29d4f4d8e1181c20ac0da8e1027a14344.zip
New #added? method on ActiveModel::Errors
The #added? method makes it possible to check if a specific error has been added, using the same parameters as for #add.
Diffstat (limited to 'activemodel/lib/active_model/errors.rb')
-rw-r--r--activemodel/lib/active_model/errors.rb30
1 files changed, 23 insertions, 7 deletions
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index f90030641d..6aa0d2a16f 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -213,13 +213,7 @@ module ActiveModel
# If +message+ is a symbol, it will be translated using the appropriate scope (see +translate_error+).
# If +message+ is a proc, it will be called, allowing for things like <tt>Time.now</tt> to be used within an error.
def add(attribute, message = nil, options = {})
- message ||= :invalid
-
- if message.is_a?(Symbol)
- message = generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS))
- elsif message.is_a?(Proc)
- message = message.call
- end
+ message = normalize_message(attribute, message, options)
if options[:strict]
raise ActiveModel::StrictValidationFailed, message
end
@@ -244,6 +238,15 @@ module ActiveModel
end
end
+ # Returns true if an error on the attribute with the given message is present, false otherwise.
+ # +message+ is treated the same as for +add+.
+ # p.errors.add :name, :blank
+ # p.errors.added? :name, :blank # => true
+ def added?(attribute, message = nil, options = {})
+ message = normalize_message(attribute, message, options)
+ self[attribute].include? message
+ end
+
# Returns all the full error messages in an array.
#
# class Company
@@ -329,6 +332,19 @@ module ActiveModel
I18n.translate(key, options)
end
+
+ private
+ def normalize_message(attribute, message, options)
+ message ||= :invalid
+
+ if message.is_a?(Symbol)
+ generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS))
+ elsif message.is_a?(Proc)
+ message.call
+ else
+ message
+ end
+ end
end
class StrictValidationFailed < StandardError