aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel
diff options
context:
space:
mode:
Diffstat (limited to 'activemodel')
-rw-r--r--activemodel/CHANGELOG.md118
-rw-r--r--activemodel/MIT-LICENSE2
-rw-r--r--activemodel/README.rdoc21
-rw-r--r--activemodel/Rakefile21
-rw-r--r--activemodel/activemodel.gemspec2
-rwxr-xr-xactivemodel/bin/test4
-rw-r--r--activemodel/lib/active_model.rb5
-rw-r--r--activemodel/lib/active_model/attribute_assignment.rb52
-rw-r--r--activemodel/lib/active_model/attribute_methods.rb38
-rw-r--r--activemodel/lib/active_model/callbacks.rb5
-rw-r--r--activemodel/lib/active_model/conversion.rb6
-rw-r--r--activemodel/lib/active_model/dirty.rb96
-rw-r--r--activemodel/lib/active_model/errors.rb166
-rw-r--r--activemodel/lib/active_model/gem_version.rb8
-rw-r--r--activemodel/lib/active_model/lint.rb60
-rw-r--r--activemodel/lib/active_model/locale/en.yml3
-rw-r--r--activemodel/lib/active_model/model.rb7
-rw-r--r--activemodel/lib/active_model/naming.rb10
-rw-r--r--activemodel/lib/active_model/secure_password.rb11
-rw-r--r--activemodel/lib/active_model/serialization.rb45
-rw-r--r--activemodel/lib/active_model/serializers/json.rb8
-rw-r--r--activemodel/lib/active_model/serializers/xml.rb238
-rw-r--r--activemodel/lib/active_model/validations.rb40
-rw-r--r--activemodel/lib/active_model/validations/absence.rb2
-rw-r--r--activemodel/lib/active_model/validations/acceptance.rb15
-rw-r--r--activemodel/lib/active_model/validations/callbacks.rb7
-rw-r--r--activemodel/lib/active_model/validations/exclusion.rb4
-rw-r--r--activemodel/lib/active_model/validations/format.rb4
-rw-r--r--activemodel/lib/active_model/validations/helper_methods.rb13
-rw-r--r--activemodel/lib/active_model/validations/inclusion.rb6
-rw-r--r--activemodel/lib/active_model/validations/length.rb65
-rw-r--r--activemodel/lib/active_model/validations/numericality.rb11
-rw-r--r--activemodel/lib/active_model/validations/validates.rb2
-rw-r--r--activemodel/lib/active_model/validations/with.rb10
-rw-r--r--activemodel/lib/active_model/validator.rb8
-rw-r--r--activemodel/lib/active_model/version.rb2
-rw-r--r--activemodel/test/cases/attribute_assignment_test.rb107
-rw-r--r--activemodel/test/cases/callbacks_test.rb29
-rw-r--r--activemodel/test/cases/dirty_test.rb34
-rw-r--r--activemodel/test/cases/errors_test.rb149
-rw-r--r--activemodel/test/cases/helper.rb17
-rw-r--r--activemodel/test/cases/model_test.rb4
-rw-r--r--activemodel/test/cases/serialization_test.rb25
-rw-r--r--activemodel/test/cases/serializers/json_serialization_test.rb4
-rw-r--r--activemodel/test/cases/serializers/xml_serialization_test.rb250
-rw-r--r--activemodel/test/cases/validations/absence_validation_test.rb1
-rw-r--r--activemodel/test/cases/validations/acceptance_validation_test.rb21
-rw-r--r--activemodel/test/cases/validations/callbacks_test.rb58
-rw-r--r--activemodel/test/cases/validations/conditional_validation_test.rb1
-rw-r--r--activemodel/test/cases/validations/confirmation_validation_test.rb1
-rw-r--r--activemodel/test/cases/validations/exclusion_validation_test.rb18
-rw-r--r--activemodel/test/cases/validations/format_validation_test.rb1
-rw-r--r--activemodel/test/cases/validations/i18n_generate_message_validation_test.rb2
-rw-r--r--activemodel/test/cases/validations/i18n_validation_test.rb162
-rw-r--r--activemodel/test/cases/validations/inclusion_validation_test.rb1
-rw-r--r--activemodel/test/cases/validations/length_validation_test.rb30
-rw-r--r--activemodel/test/cases/validations/numericality_validation_test.rb5
-rw-r--r--activemodel/test/cases/validations/presence_validation_test.rb1
-rw-r--r--activemodel/test/cases/validations/validates_test.rb2
-rw-r--r--activemodel/test/cases/validations/validations_context_test.rb1
-rw-r--r--activemodel/test/cases/validations/with_validation_test.rb9
-rw-r--r--activemodel/test/cases/validations_test.rb59
-rw-r--r--activemodel/test/models/contact.rb1
-rw-r--r--activemodel/test/models/topic.rb4
64 files changed, 1113 insertions, 999 deletions
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
index 5b0f2cd666..54fe5794e1 100644
--- a/activemodel/CHANGELOG.md
+++ b/activemodel/CHANGELOG.md
@@ -1,67 +1,111 @@
-* Passwords with spaces only allowed in `ActiveModel::SecurePassword`.
+* Add case_sensitive option for confirmation validator in models.
- Presence validation can be used to restore old behavior.
+ *Akshat Sharma*
- *Yevhene Shemet*
+* Ensure `method_missing` is called for methods passed to
+ `ActiveModel::Serialization#serializable_hash` that don't exist.
-* Validate options passed to `ActiveModel::Validations.validate`.
+ *Jay Elaraj*
- Preventing, in many cases, the simple mistake of using `validate` instead of `validates`.
+* Remove `ActiveModel::Serializers::Xml` from core.
- *Sonny Michaud*
+ *Zachary Scott*
-* Deprecate `reset_#{attribute}` in favor of `restore_#{attribute}`.
+* Add `ActiveModel::Dirty#[attr_name]_previously_changed?` and
+ `ActiveModel::Dirty#[attr_name]_previous_change` to improve access
+ to recorded changes after the model has been saved.
- These methods may cause confusion with the `reset_changes`, which has
- different behaviour.
+ It makes the dirty-attributes query methods consistent before and after
+ saving.
- *Rafael Mendonça França*
+ *Fernando Tapia Rico*
-* Deprecate `ActiveModel::Dirty#reset_changes` in favor of `#clear_changes_information`.
+* Deprecate the `:tokenizer` option for `validates_length_of`, in favor of
+ plain Ruby.
- Method's name is causing confusion with the `reset_#{attribute}` methods.
- While `reset_name` sets the value of the name attribute to previous value
- `reset_changes` only discards the changes.
+ *Sean Griffin*
- *Rafael Mendonça França*
+* Deprecate `ActiveModel::Errors#add_on_empty` and `ActiveModel::Errors#add_on_blank`
+ with no replacement.
-* Added `restore_attributes` method to `ActiveModel::Dirty` API which restores
- the value of changed attributes to previous value.
+ *Wojciech Wnętrzak*
- *Igor G.*
+* Deprecate `ActiveModel::Errors#get`, `ActiveModel::Errors#set` and
+ `ActiveModel::Errors#[]=` methods that have inconsistent behavior.
-* Allow proc and symbol as values for `only_integer` of `NumericalityValidator`
+ *Wojciech Wnętrzak*
- *Robin Mehner*
+* Allow symbol as values for `tokenize` of `LengthValidator`.
-* `has_secure_password` now verifies that the given password is less than 72
- characters if validations are enabled.
+ *Kensuke Naito*
- Fixes #14591.
+* Assigning an unknown attribute key to an `ActiveModel` instance during initialization
+ will now raise `ActiveModel::AttributeAssignment::UnknownAttributeError` instead of
+ `NoMethodError`.
- *Akshay Vishnoi*
+ Example:
-* Remove deprecated `Validator#setup` without replacement.
+ User.new(foo: 'some value')
+ # => ActiveModel::AttributeAssignment::UnknownAttributeError: unknown attribute 'foo' for User.
- See #10716.
+ *Eugene Gilburg*
- *Kuldeep Aggarwal*
+* Extracted `ActiveRecord::AttributeAssignment` to `ActiveModel::AttributeAssignment`
+ allowing to use it for any object as an includable module.
-* Add plural and singular form for length validator's default messages.
+ Example:
- *Abd ar-Rahman Hamid*
+ class Cat
+ include ActiveModel::AttributeAssignment
+ attr_accessor :name, :status
+ end
-* Introduce `validate` as an alias for `valid?`.
+ cat = Cat.new
+ cat.assign_attributes(name: "Gorby", status: "yawning")
+ cat.name # => 'Gorby'
+ cat.status # => 'yawning'
+ cat.assign_attributes(status: "sleeping")
+ cat.name # => 'Gorby'
+ cat.status # => 'sleeping'
- This is more intuitive when you want to run validations but don't care about
- the return value.
+ *Bogdan Gusiev*
- *Henrik Nyh*
+* Add `ActiveModel::Errors#details`
-* Add case_sensitive option for confirmation validator in models.
+ To be able to return type of used validator, one can now call `details`
+ on errors instance.
- See #17351
+ Example:
+
+ class User < ActiveRecord::Base
+ validates :name, presence: true
+ end
+
+ user = User.new; user.valid?; user.errors.details
+ => {name: [{error: :blank}]}
+
+ *Wojciech Wnętrzak*
+
+* Change validates_acceptance_of to accept true by default.
+
+ The default for validates_acceptance_of is now "1" and true.
+ In the past, only "1" was the default and you were required to add
+ accept: true.
+
+* Remove deprecated `ActiveModel::Dirty#reset_#{attribute}` and
+ `ActiveModel::Dirty#reset_changes`.
+
+ *Rafael Mendonça França*
+
+* Change the way in which callback chains can be halted.
+
+ The preferred method to halt a callback chain from now on is to explicitly
+ `throw(:abort)`.
+ In the past, returning `false` in an ActiveModel or ActiveModel::Validations
+ `before_` callback had the side effect of halting the callback chain.
+ This is not recommended anymore and, depending on the value of the
+ `config.active_support.halt_callback_chains_on_return_false` option, will
+ either not work at all or display a deprecation warning.
- *Akshat Sharma*
-Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/activemodel/CHANGELOG.md) for previous changes.
+Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activemodel/CHANGELOG.md) for previous changes.
diff --git a/activemodel/MIT-LICENSE b/activemodel/MIT-LICENSE
index d58dd9ed9b..3ec7a617cf 100644
--- a/activemodel/MIT-LICENSE
+++ b/activemodel/MIT-LICENSE
@@ -1,4 +1,4 @@
-Copyright (c) 2004-2014 David Heinemeier Hansson
+Copyright (c) 2004-2015 David Heinemeier Hansson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
diff --git a/activemodel/README.rdoc b/activemodel/README.rdoc
index f6beff14e1..20414c1d61 100644
--- a/activemodel/README.rdoc
+++ b/activemodel/README.rdoc
@@ -49,7 +49,7 @@ behavior out of the box:
send("#{attr}=", nil)
end
end
-
+
person = Person.new
person.clear_name
person.clear_age
@@ -132,7 +132,7 @@ behavior out of the box:
"Name"
end
end
-
+
person = Person.new
person.name = nil
person.validate!
@@ -154,8 +154,8 @@ behavior out of the box:
* Making objects serializable
- ActiveModel::Serialization provides a standard interface for your object
- to provide +to_json+ or +to_xml+ serialization.
+ <tt>ActiveModel::Serialization</tt> provides a standard interface for your object
+ to provide +to_json+ serialization.
class SerialPerson
include ActiveModel::Serialization
@@ -177,13 +177,6 @@ behavior out of the box:
s = SerialPerson.new
s.to_json # => "{\"name\":null}"
- class SerialPerson
- include ActiveModel::Serializers::Xml
- end
-
- s = SerialPerson.new
- s.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
-
{Learn more}[link:classes/ActiveModel/Serialization.html]
* Internationalization (i18n) support
@@ -216,10 +209,10 @@ behavior out of the box:
{Learn more}[link:classes/ActiveModel/Validations.html]
* Custom validators
-
+
class HasNameValidator < ActiveModel::Validator
def validate(record)
- record.errors[:name] = "must exist" if record.name.blank?
+ record.errors.add(:name, "must exist") if record.name.blank?
end
end
@@ -242,7 +235,7 @@ behavior out of the box:
The latest version of Active Model can be installed with RubyGems:
- % [sudo] gem install activemodel
+ % gem install activemodel
Source code can be downloaded as part of the Rails project on GitHub
diff --git a/activemodel/Rakefile b/activemodel/Rakefile
index c30a559ef5..5a67f0a151 100644
--- a/activemodel/Rakefile
+++ b/activemodel/Rakefile
@@ -1,12 +1,12 @@
-dir = File.dirname(__FILE__)
-
require 'rake/testtask'
+dir = File.dirname(__FILE__)
+
task :default => :test
Rake::TestTask.new do |t|
t.libs << "test"
- t.test_files = Dir.glob("#{dir}/test/cases/**/*_test.rb").sort
+ t.test_files = Dir.glob("#{dir}/test/cases/**/*_test.rb")
t.warning = true
t.verbose = true
t.ruby_opts = ["--dev"] if defined?(JRUBY_VERSION)
@@ -19,18 +19,3 @@ namespace :test do
end or raise "Failures"
end
end
-
-require 'rubygems/package_task'
-
-spec = eval(File.read("#{dir}/activemodel.gemspec"))
-
-Gem::PackageTask.new(spec) do |p|
- p.gem_spec = spec
-end
-
-desc "Release to rubygems"
-task :release => :package do
- require 'rake/gemcutter'
- Rake::Gemcutter::Tasks.new(spec).define
- Rake::Task['gem:push'].invoke
-end
diff --git a/activemodel/activemodel.gemspec b/activemodel/activemodel.gemspec
index 36e565f692..8d00b3aa27 100644
--- a/activemodel/activemodel.gemspec
+++ b/activemodel/activemodel.gemspec
@@ -7,7 +7,7 @@ Gem::Specification.new do |s|
s.summary = 'A toolkit for building modeling frameworks (part of Rails).'
s.description = 'A toolkit for building modeling frameworks like Active Record. Rich support for attributes, callbacks, validations, serialization, internationalization, and testing.'
- s.required_ruby_version = '>= 1.9.3'
+ s.required_ruby_version = '>= 2.2.2'
s.license = 'MIT'
diff --git a/activemodel/bin/test b/activemodel/bin/test
new file mode 100755
index 0000000000..404cabba51
--- /dev/null
+++ b/activemodel/bin/test
@@ -0,0 +1,4 @@
+#!/usr/bin/env ruby
+COMPONENT_ROOT = File.expand_path("../../", __FILE__)
+require File.expand_path("../tools/test", COMPONENT_ROOT)
+exit Minitest.run(ARGV)
diff --git a/activemodel/lib/active_model.rb b/activemodel/lib/active_model.rb
index feb3d9371d..4e1b3f7495 100644
--- a/activemodel/lib/active_model.rb
+++ b/activemodel/lib/active_model.rb
@@ -1,5 +1,5 @@
#--
-# Copyright (c) 2004-2014 David Heinemeier Hansson
+# Copyright (c) 2004-2015 David Heinemeier Hansson
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
@@ -28,6 +28,7 @@ require 'active_model/version'
module ActiveModel
extend ActiveSupport::Autoload
+ autoload :AttributeAssignment
autoload :AttributeMethods
autoload :BlockValidator, 'active_model/validator'
autoload :Callbacks
@@ -49,6 +50,7 @@ module ActiveModel
eager_autoload do
autoload :Errors
autoload :StrictValidationFailed, 'active_model/errors'
+ autoload :UnknownAttributeError, 'active_model/errors'
end
module Serializers
@@ -56,7 +58,6 @@ module ActiveModel
eager_autoload do
autoload :JSON
- autoload :Xml
end
end
diff --git a/activemodel/lib/active_model/attribute_assignment.rb b/activemodel/lib/active_model/attribute_assignment.rb
new file mode 100644
index 0000000000..087d11f708
--- /dev/null
+++ b/activemodel/lib/active_model/attribute_assignment.rb
@@ -0,0 +1,52 @@
+require 'active_support/core_ext/hash/keys'
+
+module ActiveModel
+ module AttributeAssignment
+ include ActiveModel::ForbiddenAttributesProtection
+
+ # Allows you to set all the attributes by passing in a hash of attributes with
+ # keys matching the attribute names.
+ #
+ # If the passed hash responds to <tt>permitted?</tt> method and the return value
+ # of this method is +false+ an <tt>ActiveModel::ForbiddenAttributesError</tt>
+ # exception is raised.
+ #
+ # class Cat
+ # include ActiveModel::AttributeAssignment
+ # attr_accessor :name, :status
+ # end
+ #
+ # cat = Cat.new
+ # cat.assign_attributes(name: "Gorby", status: "yawning")
+ # cat.name # => 'Gorby'
+ # cat.status => 'yawning'
+ # cat.assign_attributes(status: "sleeping")
+ # cat.name # => 'Gorby'
+ # cat.status => 'sleeping'
+ def assign_attributes(new_attributes)
+ if !new_attributes.respond_to?(:stringify_keys)
+ raise ArgumentError, "When assigning attributes, you must pass a hash as an argument."
+ end
+ return if new_attributes.blank?
+
+ attributes = new_attributes.stringify_keys
+ _assign_attributes(sanitize_for_mass_assignment(attributes))
+ end
+
+ private
+
+ def _assign_attributes(attributes)
+ attributes.each do |k, v|
+ _assign_attribute(k, v)
+ end
+ end
+
+ def _assign_attribute(k, v)
+ if respond_to?("#{k}=")
+ public_send("#{k}=", v)
+ else
+ raise UnknownAttributeError.new(self, k)
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/attribute_methods.rb b/activemodel/lib/active_model/attribute_methods.rb
index ea07c5c039..77e4ce3afe 100644
--- a/activemodel/lib/active_model/attribute_methods.rb
+++ b/activemodel/lib/active_model/attribute_methods.rb
@@ -23,7 +23,7 @@ module ActiveModel
# The requirements to implement <tt>ActiveModel::AttributeMethods</tt> are to:
#
# * <tt>include ActiveModel::AttributeMethods</tt> in your class.
- # * Call each of its method you want to add, such as +attribute_method_suffix+
+ # * Call each of its methods you want to add, such as +attribute_method_suffix+
# or +attribute_method_prefix+.
# * Call +define_attribute_methods+ after the other methods are called.
# * Define the various generic +_attribute+ methods that you have declared.
@@ -225,9 +225,9 @@ module ActiveModel
end
# Declares the attributes that should be prefixed and suffixed by
- # ActiveModel::AttributeMethods.
+ # <tt>ActiveModel::AttributeMethods</tt>.
#
- # To use, pass attribute names (as strings or symbols), be sure to declare
+ # To use, pass attribute names (as strings or symbols). Be sure to declare
# +define_attribute_methods+ after you define any prefix, suffix or affix
# methods, or they will not hook in.
#
@@ -239,7 +239,7 @@ module ActiveModel
#
# # Call to define_attribute_methods must appear after the
# # attribute_method_prefix, attribute_method_suffix or
- # # attribute_method_affix declares.
+ # # attribute_method_affix declarations.
# define_attribute_methods :name, :age, :address
#
# private
@@ -253,9 +253,9 @@ module ActiveModel
end
# Declares an attribute that should be prefixed and suffixed by
- # ActiveModel::AttributeMethods.
+ # <tt>ActiveModel::AttributeMethods</tt>.
#
- # To use, pass an attribute name (as string or symbol), be sure to declare
+ # To use, pass an attribute name (as string or symbol). Be sure to declare
# +define_attribute_method+ after you define any prefix, suffix or affix
# method, or they will not hook in.
#
@@ -267,7 +267,7 @@ module ActiveModel
#
# # Call to define_attribute_method must appear after the
# # attribute_method_prefix, attribute_method_suffix or
- # # attribute_method_affix declares.
+ # # attribute_method_affix declarations.
# define_attribute_method :name
#
# private
@@ -342,7 +342,7 @@ module ActiveModel
private
# The methods +method_missing+ and +respond_to?+ of this module are
# invoked often in a typical rails, both of which invoke the method
- # +match_attribute_method?+. The latter method iterates through an
+ # +matched_attribute_method+. The latter method iterates through an
# array doing regular expression matches, which results in a lot of
# object creations. Most of the time it returns a +nil+ match. As the
# match result is always the same given a +method_name+, this cache is
@@ -353,19 +353,17 @@ module ActiveModel
@attribute_method_matchers_cache ||= ThreadSafe::Cache.new(initial_capacity: 4)
end
- def attribute_method_matcher(method_name) #:nodoc:
+ def attribute_method_matchers_matching(method_name) #:nodoc:
attribute_method_matchers_cache.compute_if_absent(method_name) do
# Must try to match prefixes/suffixes first, or else the matcher with no prefix/suffix
# will match every time.
matchers = attribute_method_matchers.partition(&:plain?).reverse.flatten(1)
- match = nil
- matchers.detect { |method| match = method.match(method_name) }
- match
+ matchers.map { |method| method.match(method_name) }.compact
end
end
# Define a method `name` in `mod` that dispatches to `send`
- # using the given `extra` args. This fallbacks `define_method`
+ # using the given `extra` args. This falls back on `define_method`
# and `send` if the given names cannot be compiled.
def define_proxy_call(include_private, mod, name, send, *extra) #:nodoc:
defn = if name =~ NAME_COMPILABLE_REGEXP
@@ -374,7 +372,7 @@ module ActiveModel
"define_method(:'#{name}') do |*args|"
end
- extra = (extra.map!(&:inspect) << "*args").join(", ")
+ extra = (extra.map!(&:inspect) << "*args").join(", ".freeze)
target = if send =~ CALL_COMPILABLE_REGEXP
"#{"self." unless include_private}#{send}(#{extra})"
@@ -421,7 +419,7 @@ module ActiveModel
# returned by <tt>attributes</tt>, as though they were first-class
# methods. So a +Person+ class with a +name+ attribute can for example use
# <tt>Person#name</tt> and <tt>Person#name=</tt> and never directly use
- # the attributes hash -- except for multiple assigns with
+ # the attributes hash -- except for multiple assignments with
# <tt>ActiveRecord::Base#attributes=</tt>.
#
# It's also possible to instantiate related objects, so a <tt>Client</tt>
@@ -431,7 +429,7 @@ module ActiveModel
if respond_to_without_attributes?(method, true)
super
else
- match = match_attribute_method?(method.to_s)
+ match = matched_attribute_method(method.to_s)
match ? attribute_missing(match, *args, &block) : super
end
end
@@ -456,7 +454,7 @@ module ActiveModel
# but found among all methods. Which means that the given method is private.
false
else
- !match_attribute_method?(method.to_s).nil?
+ !matched_attribute_method(method.to_s).nil?
end
end
@@ -468,9 +466,9 @@ module ActiveModel
private
# Returns a struct representing the matching attribute method.
# The struct's attributes are prefix, base and suffix.
- def match_attribute_method?(method_name)
- match = self.class.send(:attribute_method_matcher, method_name)
- match if match && attribute_method?(match.attr_name)
+ def matched_attribute_method(method_name)
+ matches = self.class.send(:attribute_method_matchers_matching, method_name)
+ matches.detect { |match| attribute_method?(match.attr_name) }
end
def missing_attribute(attr_name, stack)
diff --git a/activemodel/lib/active_model/callbacks.rb b/activemodel/lib/active_model/callbacks.rb
index b3d70dc515..2cf39b68fb 100644
--- a/activemodel/lib/active_model/callbacks.rb
+++ b/activemodel/lib/active_model/callbacks.rb
@@ -6,7 +6,7 @@ module ActiveModel
# Provides an interface for any class to have Active Record like callbacks.
#
# Like the Active Record methods, the callback chain is aborted as soon as
- # one of the methods in the chain returns +false+.
+ # one of the methods throws +:abort+.
#
# First, extend ActiveModel::Callbacks from the class you are creating:
#
@@ -49,7 +49,7 @@ module ActiveModel
# puts 'block successfully called.'
# end
#
- # You can choose not to have all three callbacks by passing a hash to the
+ # You can choose to have only specific callbacks by passing a hash to the
# +define_model_callbacks+ method.
#
# define_model_callbacks :create, only: [:after, :before]
@@ -103,7 +103,6 @@ module ActiveModel
def define_model_callbacks(*callbacks)
options = callbacks.extract_options!
options = {
- terminator: ->(_,result) { result == false },
skip_after_callbacks_if_terminated: true,
scope: [:kind, :name],
only: [:before, :around, :after]
diff --git a/activemodel/lib/active_model/conversion.rb b/activemodel/lib/active_model/conversion.rb
index 9c9b6f4a77..9de6ea65be 100644
--- a/activemodel/lib/active_model/conversion.rb
+++ b/activemodel/lib/active_model/conversion.rb
@@ -22,7 +22,7 @@ module ActiveModel
module Conversion
extend ActiveSupport::Concern
- # If your object is already designed to implement all of the Active Model
+ # If your object is already designed to implement all of the \Active \Model
# you can use the default <tt>:to_model</tt> implementation, which simply
# returns +self+.
#
@@ -33,9 +33,9 @@ module ActiveModel
# person = Person.new
# person.to_model == person # => true
#
- # If your model does not act like an Active Model object, then you should
+ # If your model does not act like an \Active \Model object, then you should
# define <tt>:to_model</tt> yourself returning a proxy object that wraps
- # your object with Active Model compliant methods.
+ # your object with \Active \Model compliant methods.
def to_model
self
end
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb
index ca04f48c1c..0169c20e0b 100644
--- a/activemodel/lib/active_model/dirty.rb
+++ b/activemodel/lib/active_model/dirty.rb
@@ -12,7 +12,7 @@ module ActiveModel
# * <tt>include ActiveModel::Dirty</tt> in your object.
# * Call <tt>define_attribute_methods</tt> passing each method you want to
# track.
- # * Call <tt>attr_name_will_change!</tt> before each change to the tracked
+ # * Call <tt>[attr_name]_will_change!</tt> before each change to the tracked
# attribute.
# * Call <tt>changes_applied</tt> after the changes are persisted.
# * Call <tt>clear_changes_information</tt> when you want to reset the changes
@@ -52,10 +52,10 @@ module ActiveModel
# end
# end
#
- # A newly instantiated object is unchanged:
+ # A newly instantiated +Person+ object is unchanged:
#
- # person = Person.find_by(name: 'Uncle Bob')
- # person.changed? # => false
+ # person = Person.new
+ # person.changed? # => false
#
# Change the name:
#
@@ -71,55 +71,57 @@ module ActiveModel
# Save the changes:
#
# person.save
- # person.changed? # => false
- # person.name_changed? # => false
+ # person.changed? # => false
+ # person.name_changed? # => false
#
# Reset the changes:
#
- # person.previous_changes # => {"name" => ["Uncle Bob", "Bill"]}
+ # person.previous_changes # => {"name" => ["Uncle Bob", "Bill"]}
+ # person.name_previously_changed? # => true
+ # person.name_previous_change # => ["Uncle Bob", "Bill"]
# person.reload!
- # person.previous_changes # => {}
+ # person.previous_changes # => {}
#
# Rollback the changes:
#
# person.name = "Uncle Bob"
# person.rollback!
- # person.name # => "Bill"
- # person.name_changed? # => false
+ # person.name # => "Bill"
+ # person.name_changed? # => false
#
# Assigning the same value leaves the attribute unchanged:
#
# person.name = 'Bill'
- # person.name_changed? # => false
- # person.name_change # => nil
+ # person.name_changed? # => false
+ # person.name_change # => nil
#
# Which attributes have changed?
#
# person.name = 'Bob'
- # person.changed # => ["name"]
- # person.changes # => {"name" => ["Bill", "Bob"]}
+ # person.changed # => ["name"]
+ # person.changes # => {"name" => ["Bill", "Bob"]}
#
# If an attribute is modified in-place then make use of
- # +[attribute_name]_will_change!+ to mark that the attribute is changing.
- # Otherwise Active Model can't track changes to in-place attributes. Note
+ # <tt>[attribute_name]_will_change!</tt> to mark that the attribute is changing.
+ # Otherwise \Active \Model can't track changes to in-place attributes. Note
# that Active Record can detect in-place modifications automatically. You do
- # not need to call +[attribute_name]_will_change!+ on Active Record models.
+ # not need to call <tt>[attribute_name]_will_change!</tt> on Active Record models.
#
# person.name_will_change!
- # person.name_change # => ["Bill", "Bill"]
+ # person.name_change # => ["Bill", "Bill"]
# person.name << 'y'
- # person.name_change # => ["Bill", "Billy"]
+ # person.name_change # => ["Bill", "Billy"]
module Dirty
extend ActiveSupport::Concern
include ActiveModel::AttributeMethods
included do
attribute_method_suffix '_changed?', '_change', '_will_change!', '_was'
- attribute_method_affix prefix: 'reset_', suffix: '!'
+ attribute_method_suffix '_previously_changed?', '_previous_change'
attribute_method_affix prefix: 'restore_', suffix: '!'
end
- # Returns +true+ if any attribute have unsaved changes, +false+ otherwise.
+ # Returns +true+ if any of the attributes have unsaved changes, +false+ otherwise.
#
# person.changed? # => false
# person.name = 'bob'
@@ -167,19 +169,24 @@ module ActiveModel
@changed_attributes ||= ActiveSupport::HashWithIndifferentAccess.new
end
- # Handle <tt>*_changed?</tt> for +method_missing+.
+ # Handles <tt>*_changed?</tt> for +method_missing+.
def attribute_changed?(attr, options = {}) #:nodoc:
- result = changed_attributes.include?(attr)
+ result = changes_include?(attr)
result &&= options[:to] == __send__(attr) if options.key?(:to)
result &&= options[:from] == changed_attributes[attr] if options.key?(:from)
result
end
- # Handle <tt>*_was</tt> for +method_missing+.
+ # Handles <tt>*_was</tt> for +method_missing+.
def attribute_was(attr) # :nodoc:
attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
end
+ # Handles <tt>*_previously_changed?</tt> for +method_missing+.
+ def attribute_previously_changed?(attr, options = {}) #:nodoc:
+ previous_changes_include?(attr)
+ end
+
# Restore all previous data of the provided attributes.
def restore_attributes(attributes = changed)
attributes.each { |attr| restore_attribute! attr }
@@ -187,29 +194,41 @@ module ActiveModel
private
+ # Returns +true+ if attr_name is changed, +false+ otherwise.
+ def changes_include?(attr_name)
+ attributes_changed_by_setter.include?(attr_name)
+ end
+ alias attribute_changed_by_setter? changes_include?
+
+ # Returns +true+ if attr_name were changed before the model was saved,
+ # +false+ otherwise.
+ def previous_changes_include?(attr_name)
+ @previously_changed.include?(attr_name)
+ end
+
# Removes current changes and makes them accessible through +previous_changes+.
def changes_applied # :doc:
@previously_changed = changes
@changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
end
- # Clear all dirty data: current changes and previous changes.
+ # Clears all dirty data: current changes and previous changes.
def clear_changes_information # :doc:
@previously_changed = ActiveSupport::HashWithIndifferentAccess.new
@changed_attributes = ActiveSupport::HashWithIndifferentAccess.new
end
- def reset_changes
- ActiveSupport::Deprecation.warn "#reset_changes is deprecated and will be removed on Rails 5. Please use #clear_changes_information instead."
- clear_changes_information
- end
-
- # Handle <tt>*_change</tt> for +method_missing+.
+ # Handles <tt>*_change</tt> for +method_missing+.
def attribute_change(attr)
[changed_attributes[attr], __send__(attr)] if attribute_changed?(attr)
end
- # Handle <tt>*_will_change!</tt> for +method_missing+.
+ # Handles <tt>*_previous_change</tt> for +method_missing+.
+ def attribute_previous_change(attr)
+ @previously_changed[attr] if attribute_previously_changed?(attr)
+ end
+
+ # Handles <tt>*_will_change!</tt> for +method_missing+.
def attribute_will_change!(attr)
return if attribute_changed?(attr)
@@ -222,14 +241,7 @@ module ActiveModel
set_attribute_was(attr, value)
end
- # Handle <tt>reset_*!</tt> for +method_missing+.
- def reset_attribute!(attr)
- ActiveSupport::Deprecation.warn "#reset_#{attr}! is deprecated and will be removed on Rails 5. Please use #restore_#{attr}! instead."
-
- restore_attribute!(attr)
- end
-
- # Handle <tt>restore_*!</tt> for +method_missing+.
+ # Handles <tt>restore_*!</tt> for +method_missing+.
def restore_attribute!(attr)
if attribute_changed?(attr)
__send__("#{attr}=", changed_attributes[attr])
@@ -238,7 +250,7 @@ module ActiveModel
end
# This is necessary because `changed_attributes` might be overridden in
- # other implemntations (e.g. in `ActiveRecord`)
+ # other implementations (e.g. in `ActiveRecord`)
alias_method :attributes_changed_by_setter, :changed_attributes # :nodoc:
# Force an attribute to have a particular "before" value
@@ -247,7 +259,7 @@ module ActiveModel
end
# Remove changes information for the provided attributes.
- def clear_attribute_changes(attributes)
+ def clear_attribute_changes(attributes) # :doc:
attributes_changed_by_setter.except!(*attributes)
end
end
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index 9105ef5dd6..29e0c977ce 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -2,6 +2,8 @@
require 'active_support/core_ext/array/conversions'
require 'active_support/core_ext/string/inflections'
+require 'active_support/core_ext/object/deep_dup'
+require 'active_support/core_ext/string/filters'
module ActiveModel
# == Active \Model \Errors
@@ -23,7 +25,7 @@ module ActiveModel
# attr_reader :errors
#
# def validate!
- # errors.add(:name, "cannot be nil") if name.nil?
+ # errors.add(:name, :blank, message: "cannot be nil") if name.nil?
# end
#
# # The following methods are needed to be minimally implemented
@@ -32,20 +34,20 @@ module ActiveModel
# send(attr)
# end
#
- # def Person.human_attribute_name(attr, options = {})
+ # def self.human_attribute_name(attr, options = {})
# attr
# end
#
- # def Person.lookup_ancestors
+ # def self.lookup_ancestors
# [self]
# end
# end
#
- # The last three methods are required in your object for Errors to be
+ # The last three methods are required in your object for +Errors+ to be
# able to generate error messages correctly and also handle multiple
- # languages. Of course, if you extend your object with ActiveModel::Translation
+ # languages. Of course, if you extend your object with <tt>ActiveModel::Translation</tt>
# you will not need to implement the last two. Likewise, using
- # ActiveModel::Validations will handle the validation related methods
+ # <tt>ActiveModel::Validations</tt> will handle the validation related methods
# for you.
#
# The above allows you to do:
@@ -58,8 +60,9 @@ module ActiveModel
include Enumerable
CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict]
+ MESSAGE_OPTIONS = [:message]
- attr_reader :messages
+ attr_reader :messages, :details
# Pass in the instance of the object that is using the errors object.
#
@@ -70,11 +73,13 @@ module ActiveModel
# end
def initialize(base)
@base = base
- @messages = {}
+ @messages = Hash.new { |messages, attribute| messages[attribute] = [] }
+ @details = Hash.new { |details, attribute| details[attribute] = [] }
end
def initialize_dup(other) # :nodoc:
@messages = other.messages.dup
+ @details = other.details.deep_dup
super
end
@@ -85,6 +90,7 @@ module ActiveModel
# person.errors.full_messages # => []
def clear
messages.clear
+ details.clear
end
# Returns +true+ if the error messages include an error for the given key
@@ -96,35 +102,46 @@ module ActiveModel
def include?(attribute)
messages[attribute].present?
end
- # aliases include?
alias :has_key? :include?
- # aliases include?
alias :key? :include?
# Get messages for +key+.
#
# person.errors.messages # => {:name=>["cannot be nil"]}
# person.errors.get(:name) # => ["cannot be nil"]
- # person.errors.get(:age) # => nil
+ # person.errors.get(:age) # => []
def get(key)
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
+ ActiveModel::Errors#get is deprecated and will be removed in Rails 5.1.
+
+ To achieve the same use model.errors[:#{key}].
+ MESSAGE
+
messages[key]
end
# Set messages for +key+ to +value+.
#
- # person.errors.get(:name) # => ["cannot be nil"]
+ # person.errors[:name] # => ["cannot be nil"]
# person.errors.set(:name, ["can't be nil"])
- # person.errors.get(:name) # => ["can't be nil"]
+ # person.errors[:name] # => ["can't be nil"]
def set(key, value)
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
+ ActiveModel::Errors#set is deprecated and will be removed in Rails 5.1.
+
+ Use model.errors.add(:#{key}, #{value.inspect}) instead.
+ MESSAGE
+
messages[key] = value
end
# Delete messages for +key+. Returns the deleted messages.
#
- # person.errors.get(:name) # => ["cannot be nil"]
+ # person.errors[:name] # => ["cannot be nil"]
# person.errors.delete(:name) # => ["cannot be nil"]
- # person.errors.get(:name) # => nil
+ # person.errors[:name] # => []
def delete(key)
+ details.delete(key)
messages.delete(key)
end
@@ -134,7 +151,7 @@ module ActiveModel
# person.errors[:name] # => ["cannot be nil"]
# person.errors['name'] # => ["cannot be nil"]
def [](attribute)
- get(attribute.to_sym) || set(attribute.to_sym, [])
+ messages[attribute.to_sym]
end
# Adds to the supplied attribute the supplied error message.
@@ -142,38 +159,45 @@ module ActiveModel
# person.errors[:name] = "must be set"
# person.errors[:name] # => ['must be set']
def []=(attribute, error)
- self[attribute] << error
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
+ ActiveModel::Errors#[]= is deprecated and will be removed in Rails 5.1.
+
+ Use model.errors.add(:#{attribute}, #{error.inspect}) instead.
+ MESSAGE
+
+ messages[attribute.to_sym] << error
end
# Iterates through each error key, value pair in the error messages hash.
# Yields the attribute and the error for that attribute. If the attribute
# has more than one error message, yields once for each error message.
#
- # person.errors.add(:name, "can't be blank")
+ # person.errors.add(:name, :blank, message: "can't be blank")
# person.errors.each do |attribute, error|
# # Will yield :name and "can't be blank"
# end
#
- # person.errors.add(:name, "must be specified")
+ # person.errors.add(:name, :not_specified, message: "must be specified")
# person.errors.each do |attribute, error|
# # Will yield :name and "can't be blank"
# # then yield :name and "must be specified"
# end
def each
messages.each_key do |attribute|
- self[attribute].each { |error| yield attribute, error }
+ messages[attribute].each { |error| yield attribute, error }
end
end
# Returns the number of error messages.
#
- # person.errors.add(:name, "can't be blank")
+ # person.errors.add(:name, :blank, message: "can't be blank")
# person.errors.size # => 1
- # person.errors.add(:name, "must be specified")
+ # person.errors.add(:name, :not_specified, message: "must be specified")
# person.errors.size # => 2
def size
values.flatten.size
end
+ alias :count :size
# Returns all message values.
#
@@ -191,40 +215,20 @@ module ActiveModel
messages.keys
end
- # Returns an array of error messages, with the attribute name included.
- #
- # person.errors.add(:name, "can't be blank")
- # person.errors.add(:name, "must be specified")
- # person.errors.to_a # => ["name can't be blank", "name must be specified"]
- def to_a
- full_messages
- end
-
- # Returns the number of error messages.
- #
- # person.errors.add(:name, "can't be blank")
- # person.errors.count # => 1
- # person.errors.add(:name, "must be specified")
- # person.errors.count # => 2
- def count
- to_a.size
- end
-
# Returns +true+ if no errors are found, +false+ otherwise.
# If the error message is a string it can be empty.
#
# person.errors.full_messages # => ["name cannot be nil"]
# person.errors.empty? # => false
def empty?
- all? { |k, v| v && v.empty? && !v.is_a?(String) }
+ size.zero?
end
- # aliases empty?
- alias_method :blank?, :empty?
+ alias :blank? :empty?
# Returns an xml formatted representation of the Errors hash.
#
- # person.errors.add(:name, "can't be blank")
- # person.errors.add(:name, "must be specified")
+ # person.errors.add(:name, :blank, message: "can't be blank")
+ # person.errors.add(:name, :not_specified, message: "must be specified")
# person.errors.to_xml
# # =>
# # <?xml version=\"1.0\" encoding=\"UTF-8\"?>
@@ -261,17 +265,20 @@ module ActiveModel
end
end
- # Adds +message+ to the error messages on +attribute+. More than one error
- # can be added to the same +attribute+. If no +message+ is supplied,
- # <tt>:invalid</tt> is assumed.
+ # Adds +message+ to the error messages and used validator type to +details+ on +attribute+.
+ # More than one error can be added to the same +attribute+.
+ # If no +message+ is supplied, <tt>:invalid</tt> is assumed.
#
# person.errors.add(:name)
# # => ["is invalid"]
- # person.errors.add(:name, 'must be implemented')
+ # person.errors.add(:name, :not_implemented, message: "must be implemented")
# # => ["is invalid", "must be implemented"]
#
# person.errors.messages
- # # => {:name=>["must be implemented", "is invalid"]}
+ # # => {:name=>["is invalid", "must be implemented"]}
+ #
+ # person.errors.details
+ # # => {:name=>[{error: :not_implemented}, {error: :invalid}]}
#
# If +message+ is a symbol, it will be translated using the appropriate
# scope (see +generate_message+).
@@ -283,9 +290,9 @@ module ActiveModel
# ActiveModel::StrictValidationFailed instead of adding the error.
# <tt>:strict</tt> option can also be set to any other exception.
#
- # person.errors.add(:name, nil, strict: true)
+ # person.errors.add(:name, :invalid, strict: true)
# # => ActiveModel::StrictValidationFailed: name is invalid
- # person.errors.add(:name, nil, strict: NameIsInvalid)
+ # person.errors.add(:name, :invalid, strict: NameIsInvalid)
# # => NameIsInvalid: name is invalid
#
# person.errors.messages # => {}
@@ -293,17 +300,23 @@ module ActiveModel
# +attribute+ should be set to <tt>:base</tt> if the error is not
# directly associated with a single attribute.
#
- # person.errors.add(:base, "either name or email must be present")
+ # person.errors.add(:base, :name_or_email_blank,
+ # message: "either name or email must be present")
# person.errors.messages
# # => {:base=>["either name or email must be present"]}
+ # person.errors.details
+ # # => {:base=>[{error: :name_or_email_blank}]}
def add(attribute, message = :invalid, options = {})
+ message = message.call if message.respond_to?(:call)
+ detail = normalize_detail(attribute, message, options)
message = normalize_message(attribute, message, options)
if exception = options[:strict]
exception = ActiveModel::StrictValidationFailed if exception == true
raise exception, full_message(attribute, message)
end
- self[attribute] << message
+ details[attribute.to_sym] << detail
+ messages[attribute.to_sym] << message
end
# Will add an error message to each of the attributes in +attributes+
@@ -313,6 +326,14 @@ module ActiveModel
# person.errors.messages
# # => {:name=>["can't be empty"]}
def add_on_empty(attributes, options = {})
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
+ ActiveModel::Errors#add_on_empty is deprecated and will be removed in Rails 5.1
+
+ To achieve the same use:
+
+ errors.add(attribute, :empty, options) if value.nil? || value.empty?
+ MESSAGE
+
Array(attributes).each do |attribute|
value = @base.send(:read_attribute_for_validation, attribute)
is_empty = value.respond_to?(:empty?) ? value.empty? : false
@@ -327,6 +348,14 @@ module ActiveModel
# person.errors.messages
# # => {:name=>["can't be blank"]}
def add_on_blank(attributes, options = {})
+ ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
+ ActiveModel::Errors#add_on_blank is deprecated and will be removed in Rails 5.1
+
+ To achieve the same use:
+
+ errors.add(attribute, :empty, options) if value.blank?
+ MESSAGE
+
Array(attributes).each do |attribute|
value = @base.send(:read_attribute_for_validation, attribute)
add(attribute, :blank, options) if value.blank?
@@ -339,6 +368,7 @@ module ActiveModel
# person.errors.add :name, :blank
# person.errors.added? :name, :blank # => true
def added?(attribute, message = :invalid, options = {})
+ message = message.call if message.respond_to?(:call)
message = normalize_message(attribute, message, options)
self[attribute].include? message
end
@@ -356,6 +386,7 @@ module ActiveModel
def full_messages
map { |attribute, message| full_message(attribute, message) }
end
+ alias :to_a :full_messages
# Returns all the full error messages for a given attribute in an array.
#
@@ -368,7 +399,7 @@ module ActiveModel
# person.errors.full_messages_for(:name)
# # => ["Name is too short (minimum is 5 characters)", "Name can't be blank"]
def full_messages_for(attribute)
- (get(attribute) || []).map { |message| full_message(attribute, message) }
+ messages[attribute].map { |message| full_message(attribute, message) }
end
# Returns a full message for a given attribute.
@@ -388,8 +419,8 @@ module ActiveModel
# Translates an error message in its default scope
# (<tt>activemodel.errors.messages</tt>).
#
- # Error messages are first looked up in <tt>models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>,
- # if it's not there, it's looked up in <tt>models.MODEL.MESSAGE</tt> and if
+ # Error messages are first looked up in <tt>activemodel.errors.models.MODEL.attributes.ATTRIBUTE.MESSAGE</tt>,
+ # if it's not there, it's looked up in <tt>activemodel.errors.models.MODEL.MESSAGE</tt> and if
# that is not there also, it returns the translation of the default message
# (e.g. <tt>activemodel.errors.messages.MESSAGE</tt>). The translated model
# name, translated attribute name and the value are available for
@@ -421,7 +452,6 @@ module ActiveModel
defaults = []
end
- defaults << options.delete(:message)
defaults << :"#{@base.class.i18n_scope}.errors.messages.#{type}" if @base.class.respond_to?(:i18n_scope)
defaults << :"errors.attributes.#{attribute}.#{type}"
defaults << :"errors.messages.#{type}"
@@ -430,6 +460,7 @@ module ActiveModel
defaults.flatten!
key = defaults.shift
+ defaults = options.delete(:message) if options[:message]
value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil)
options = {
@@ -447,12 +478,14 @@ module ActiveModel
case message
when Symbol
generate_message(attribute, message, options.except(*CALLBACKS_OPTIONS))
- when Proc
- message.call
else
message
end
end
+
+ def normalize_detail(attribute, message, options)
+ { error: message }.merge(options.except(*CALLBACKS_OPTIONS + MESSAGE_OPTIONS))
+ end
end
# Raised when a validation cannot be corrected by end users and are considered
@@ -472,4 +505,15 @@ module ActiveModel
# # => ActiveModel::StrictValidationFailed: Name can't be blank
class StrictValidationFailed < StandardError
end
+
+ # Raised when unknown attributes are supplied via mass assignment.
+ class UnknownAttributeError < NoMethodError
+ attr_reader :record, :attribute
+
+ def initialize(record, attribute)
+ @record = record
+ @attribute = attribute
+ super("unknown attribute '#{attribute}' for #{@record.class}.")
+ end
+ end
end
diff --git a/activemodel/lib/active_model/gem_version.rb b/activemodel/lib/active_model/gem_version.rb
index e37edcf581..762f4fe939 100644
--- a/activemodel/lib/active_model/gem_version.rb
+++ b/activemodel/lib/active_model/gem_version.rb
@@ -1,14 +1,14 @@
module ActiveModel
- # Returns the version of the currently loaded Active Model as a <tt>Gem::Version</tt>
+ # Returns the version of the currently loaded \Active \Model as a <tt>Gem::Version</tt>
def self.gem_version
Gem::Version.new VERSION::STRING
end
module VERSION
- MAJOR = 4
- MINOR = 2
+ MAJOR = 5
+ MINOR = 0
TINY = 0
- PRE = "beta2"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/activemodel/lib/active_model/lint.rb b/activemodel/lib/active_model/lint.rb
index 38087521a2..010eaeb170 100644
--- a/activemodel/lib/active_model/lint.rb
+++ b/activemodel/lib/active_model/lint.rb
@@ -21,28 +21,27 @@ module ActiveModel
# +self+.
module Tests
- # == Responds to <tt>to_key</tt>
+ # Passes if the object's model responds to <tt>to_key</tt> and if calling
+ # this method returns +nil+ when the object is not persisted.
+ # Fails otherwise.
#
- # Returns an Enumerable of all (primary) key attributes
- # or nil if <tt>model.persisted?</tt> is false. This is used by
- # <tt>dom_id</tt> to generate unique ids for the object.
+ # <tt>to_key</tt> returns an Enumerable of all (primary) key attributes
+ # of the model, and is used to a generate unique DOM id for the object.
def test_to_key
assert model.respond_to?(:to_key), "The model should respond to to_key"
def model.persisted?() false end
assert model.to_key.nil?, "to_key should return nil when `persisted?` returns false"
end
- # == Responds to <tt>to_param</tt>
- #
- # Returns a string representing the object's key suitable for use in URLs
- # or +nil+ if <tt>model.persisted?</tt> is +false+.
+ # Passes if the object's model responds to <tt>to_param</tt> and if
+ # calling this method returns +nil+ when the object is not persisted.
+ # Fails otherwise.
#
+ # <tt>to_param</tt> is used to represent the object's key in URLs.
# Implementers can decide to either raise an exception or provide a
# default in case the record uses a composite primary key. There are no
# tests for this behavior in lint because it doesn't make sense to force
# any of the possible implementation strategies on the implementer.
- # However, if the resource is not persisted?, then <tt>to_param</tt>
- # should always return +nil+.
def test_to_param
assert model.respond_to?(:to_param), "The model should respond to to_param"
def model.to_key() [1] end
@@ -50,32 +49,34 @@ module ActiveModel
assert model.to_param.nil?, "to_param should return nil when `persisted?` returns false"
end
- # == Responds to <tt>to_partial_path</tt>
+ # Passes if the object's model responds to <tt>to_partial_path</tt> and if
+ # calling this method returns a string. Fails otherwise.
#
- # Returns a string giving a relative path. This is used for looking up
- # partials. For example, a BlogPost model might return "blog_posts/blog_post"
+ # <tt>to_partial_path</tt> is used for looking up partials. For example,
+ # a BlogPost model might return "blog_posts/blog_post".
def test_to_partial_path
assert model.respond_to?(:to_partial_path), "The model should respond to to_partial_path"
assert_kind_of String, model.to_partial_path
end
- # == Responds to <tt>persisted?</tt>
+ # Passes if the object's model responds to <tt>persisted?</tt> and if
+ # calling this method returns either +true+ or +false+. Fails otherwise.
#
- # Returns a boolean that specifies whether the object has been persisted
- # yet. This is used when calculating the URL for an object. If the object
- # is not persisted, a form for that object, for instance, will route to
- # the create action. If it is persisted, a form for the object will routes
- # to the update action.
+ # <tt>persisted?</tt> is used when calculating the URL for an object.
+ # If the object is not persisted, a form for that object, for instance,
+ # will route to the create action. If it is persisted, a form for the
+ # object will route to the update action.
def test_persisted?
assert model.respond_to?(:persisted?), "The model should respond to persisted?"
assert_boolean model.persisted?, "persisted?"
end
- # == \Naming
+ # Passes if the object's model responds to <tt>model_name</tt> both as
+ # an instance method and as a class method, and if calling this method
+ # returns a string with some convenience methods: <tt>:human</tt>,
+ # <tt>:singular</tt> and <tt>:plural</tt>.
#
- # Model.model_name and Model#model_name must return a string with some
- # convenience methods: # <tt>:human</tt>, <tt>:singular</tt> and
- # <tt>:plural</tt>. Check ActiveModel::Naming for more information.
+ # Check ActiveModel::Naming for more information.
def test_model_naming
assert model.class.respond_to?(:model_name), "The model class should respond to model_name"
model_name = model.class.model_name
@@ -88,12 +89,15 @@ module ActiveModel
assert_equal model.model_name, model.class.model_name
end
- # == \Errors Testing
+ # Passes if the object's model responds to <tt>errors</tt> and if calling
+ # <tt>[](attribute)</tt> on the result of this method returns an array.
+ # Fails otherwise.
#
- # Returns an object that implements [](attribute) defined which returns an
- # Array of Strings that are the errors for the attribute in question.
- # If localization is used, the Strings should be localized for the current
- # locale. If no error is present, this method should return an empty Array.
+ # <tt>errors[attribute]</tt> is used to retrieve the errors of a model
+ # for a given attribute. If errors are present, the method should return
+ # an array of strings that are the errors for the attribute in question.
+ # If localization is used, the strings should be localized for the current
+ # locale. If no error is present, the method should return an empty array.
def test_errors_aref
assert model.respond_to?(:errors), "The model should respond to errors"
assert model.errors[:hello].is_a?(Array), "errors#[] should return an Array"
diff --git a/activemodel/lib/active_model/locale/en.yml b/activemodel/lib/active_model/locale/en.yml
index bf07945fe1..061e35dd1e 100644
--- a/activemodel/lib/active_model/locale/en.yml
+++ b/activemodel/lib/active_model/locale/en.yml
@@ -6,6 +6,7 @@ en:
# The values :model, :attribute and :value are always available for interpolation
# The value :count is available when applicable. Can be used for pluralization.
messages:
+ model_invalid: "Validation failed: %{errors}"
inclusion: "is not included in the list"
exclusion: "is reserved"
invalid: "is invalid"
@@ -16,7 +17,7 @@ en:
present: "must be blank"
too_long:
one: "is too long (maximum is 1 character)"
- other: "is too long (maximum is %{count} characters)"
+ other: "is too long (maximum is %{count} characters)"
too_short:
one: "is too short (minimum is 1 character)"
other: "is too short (minimum is %{count} characters)"
diff --git a/activemodel/lib/active_model/model.rb b/activemodel/lib/active_model/model.rb
index d51d6ddcc9..dac8d549a7 100644
--- a/activemodel/lib/active_model/model.rb
+++ b/activemodel/lib/active_model/model.rb
@@ -57,6 +57,7 @@ module ActiveModel
# (see below).
module Model
extend ActiveSupport::Concern
+ include ActiveModel::AttributeAssignment
include ActiveModel::Validations
include ActiveModel::Conversion
@@ -75,10 +76,8 @@ module ActiveModel
# person = Person.new(name: 'bob', age: '18')
# person.name # => "bob"
# person.age # => "18"
- def initialize(params={})
- params.each do |attr, value|
- self.public_send("#{attr}=", value)
- end if params
+ def initialize(attributes={})
+ assign_attributes(attributes) if attributes
super()
end
diff --git a/activemodel/lib/active_model/naming.rb b/activemodel/lib/active_model/naming.rb
index 4e6b02c246..213f2d5b6a 100644
--- a/activemodel/lib/active_model/naming.rb
+++ b/activemodel/lib/active_model/naming.rb
@@ -1,5 +1,7 @@
require 'active_support/core_ext/hash/except'
require 'active_support/core_ext/module/introspection'
+require 'active_support/core_ext/module/remove_method'
+require 'active_support/core_ext/module/delegation'
module ActiveModel
class Name
@@ -129,7 +131,7 @@ module ActiveModel
#
# Equivalent to +to_s+.
delegate :==, :===, :<=>, :=~, :"!~", :eql?, :to_s,
- :to_str, to: :name
+ :to_str, :as_json, to: :name
# Returns a new ActiveModel::Name instance. By default, the +namespace+
# and +name+ option will take the namespace and name of the given class
@@ -189,8 +191,8 @@ module ActiveModel
private
- def _singularize(string, replacement='_')
- ActiveSupport::Inflector.underscore(string).tr('/', replacement)
+ def _singularize(string)
+ ActiveSupport::Inflector.underscore(string).tr('/'.freeze, '_'.freeze)
end
end
@@ -211,7 +213,7 @@ module ActiveModel
# BookModule::BookCover.model_name.i18n_key # => :"book_module/book_cover"
#
# Providing the functionality that ActiveModel::Naming provides in your object
- # is required to pass the Active Model Lint test. So either extending the
+ # is required to pass the \Active \Model Lint test. So either extending the
# provided method below, or rolling your own is required.
module Naming
def self.extended(base) #:nodoc:
diff --git a/activemodel/lib/active_model/secure_password.rb b/activemodel/lib/active_model/secure_password.rb
index 8f2a069ba3..89da74efa8 100644
--- a/activemodel/lib/active_model/secure_password.rb
+++ b/activemodel/lib/active_model/secure_password.rb
@@ -26,7 +26,7 @@ module ActiveModel
# it). When this attribute has a +nil+ value, the validation will not be
# triggered.
#
- # For further customizability, it is possible to supress the default
+ # For further customizability, it is possible to suppress the default
# validations by passing <tt>validations: false</tt> as an argument.
#
# Add bcrypt (~> 3.1.7) to Gemfile to use #has_secure_password:
@@ -77,13 +77,6 @@ module ActiveModel
validates_length_of :password, maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED
validates_confirmation_of :password, allow_blank: true
end
-
- # This code is necessary as long as the protected_attributes gem is supported.
- if respond_to?(:attributes_protected_by_default)
- def self.attributes_protected_by_default #:nodoc:
- super + ['password_digest']
- end
- end
end
end
@@ -99,7 +92,7 @@ module ActiveModel
# user.authenticate('notright') # => false
# user.authenticate('mUc3m00RsqyRe') # => user
def authenticate(unencrypted_password)
- BCrypt::Password.new(password_digest) == unencrypted_password && self
+ BCrypt::Password.new(password_digest).is_password?(unencrypted_password) && self
end
attr_reader :password
diff --git a/activemodel/lib/active_model/serialization.rb b/activemodel/lib/active_model/serialization.rb
index 976f50b13e..341651d00d 100644
--- a/activemodel/lib/active_model/serialization.rb
+++ b/activemodel/lib/active_model/serialization.rb
@@ -31,16 +31,14 @@ module ActiveModel
# of the attributes hash's keys. In order to override this behavior, take a look
# at the private method +read_attribute_for_serialization+.
#
- # Most of the time though, either the JSON or XML serializations are needed.
- # Both of these modules automatically include the
- # <tt>ActiveModel::Serialization</tt> module, so there is no need to
- # explicitly include it.
+ # The JSON serialization is provided by default when you include the
+ # <tt>ActiveModel::Serialization</tt> module, so there is no need to explicitly
+ # include it.
#
- # A minimal implementation including XML and JSON would be:
+ # A minimal implementation including JSON would be:
#
# class Person
# include ActiveModel::Serializers::JSON
- # include ActiveModel::Serializers::Xml
#
# attr_accessor :name
#
@@ -55,13 +53,11 @@ module ActiveModel
# person.serializable_hash # => {"name"=>nil}
# person.as_json # => {"name"=>nil}
# person.to_json # => "{\"name\":null}"
- # person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
#
# person.name = "Bob"
# person.serializable_hash # => {"name"=>"Bob"}
# person.as_json # => {"name"=>"Bob"}
# person.to_json # => "{\"name\":\"Bob\"}"
- # person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<serial-person...
#
# Valid options are <tt>:only</tt>, <tt>:except</tt>, <tt>:methods</tt> and
# <tt>:include</tt>. The following are all valid examples:
@@ -94,6 +90,37 @@ module ActiveModel
# person.serializable_hash(except: :name) # => {"age"=>22}
# person.serializable_hash(methods: :capitalized_name)
# # => {"name"=>"bob", "age"=>22, "capitalized_name"=>"Bob"}
+ #
+ # Example with <tt>:include</tt> option
+ #
+ # class User
+ # include ActiveModel::Serializers::JSON
+ # attr_accessor :name, :notes # Emulate has_many :notes
+ # def attributes
+ # {'name' => nil}
+ # end
+ # end
+ #
+ # class Note
+ # include ActiveModel::Serializers::JSON
+ # attr_accessor :title, :text
+ # def attributes
+ # {'title' => nil, 'text' => nil}
+ # end
+ # end
+ #
+ # note = Note.new
+ # note.title = 'Battle of Austerlitz'
+ # note.text = 'Some text here'
+ #
+ # user = User.new
+ # user.name = 'Napoleon'
+ # user.notes = [note]
+ #
+ # user.serializable_hash
+ # # => {"name" => "Napoleon"}
+ # user.serializable_hash(include: { notes: { only: 'title' }})
+ # # => {"name" => "Napoleon", "notes" => [{"title"=>"Battle of Austerlitz"}]}
def serializable_hash(options = nil)
options ||= {}
@@ -107,7 +134,7 @@ module ActiveModel
hash = {}
attribute_names.each { |n| hash[n] = read_attribute_for_serialization(n) }
- Array(options[:methods]).each { |m| hash[m.to_s] = send(m) if respond_to?(m) }
+ Array(options[:methods]).each { |m| hash[m.to_s] = send(m) }
serializable_add_includes(options) do |association, records, opts|
hash[association.to_s] = if records.respond_to?(:to_ary)
diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb
index 77f2a64b11..b66dbf1afe 100644
--- a/activemodel/lib/active_model/serializers/json.rb
+++ b/activemodel/lib/active_model/serializers/json.rb
@@ -130,10 +130,10 @@ module ActiveModel
#
# json = { person: { name: 'bob', age: 22, awesome:true } }.to_json
# person = Person.new
- # person.from_json(json) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
- # person.name # => "bob"
- # person.age # => 22
- # person.awesome # => true
+ # person.from_json(json, true) # => #<Person:0x007fec5e7a0088 @age=22, @awesome=true, @name="bob">
+ # person.name # => "bob"
+ # person.age # => 22
+ # person.awesome # => true
def from_json(json, include_root=include_root_in_json)
hash = ActiveSupport::JSON.decode(json)
hash = hash.values.first if include_root
diff --git a/activemodel/lib/active_model/serializers/xml.rb b/activemodel/lib/active_model/serializers/xml.rb
deleted file mode 100644
index 3ad3bf30ad..0000000000
--- a/activemodel/lib/active_model/serializers/xml.rb
+++ /dev/null
@@ -1,238 +0,0 @@
-require 'active_support/core_ext/module/attribute_accessors'
-require 'active_support/core_ext/array/conversions'
-require 'active_support/core_ext/hash/conversions'
-require 'active_support/core_ext/hash/slice'
-require 'active_support/core_ext/time/acts_like'
-
-module ActiveModel
- module Serializers
- # == Active Model XML Serializer
- module Xml
- extend ActiveSupport::Concern
- include ActiveModel::Serialization
-
- included do
- extend ActiveModel::Naming
- end
-
- class Serializer #:nodoc:
- class Attribute #:nodoc:
- attr_reader :name, :value, :type
-
- def initialize(name, serializable, value)
- @name, @serializable = name, serializable
-
- if value.acts_like?(:time) && value.respond_to?(:in_time_zone)
- value = value.in_time_zone
- end
-
- @value = value
- @type = compute_type
- end
-
- def decorations
- decorations = {}
- decorations[:encoding] = 'base64' if type == :binary
- decorations[:type] = (type == :string) ? nil : type
- decorations[:nil] = true if value.nil?
- decorations
- end
-
- protected
-
- def compute_type
- return if value.nil?
- type = ActiveSupport::XmlMini::TYPE_NAMES[value.class.name]
- type ||= :string if value.respond_to?(:to_str)
- type ||= :yaml
- type
- end
- end
-
- class MethodAttribute < Attribute #:nodoc:
- end
-
- attr_reader :options
-
- def initialize(serializable, options = nil)
- @serializable = serializable
- @options = options ? options.dup : {}
- end
-
- def serializable_hash
- @serializable.serializable_hash(@options.except(:include))
- end
-
- def serializable_collection
- methods = Array(options[:methods]).map(&:to_s)
- serializable_hash.map do |name, value|
- name = name.to_s
- if methods.include?(name)
- self.class::MethodAttribute.new(name, @serializable, value)
- else
- self.class::Attribute.new(name, @serializable, value)
- end
- end
- end
-
- def serialize
- require 'builder' unless defined? ::Builder
-
- options[:indent] ||= 2
- options[:builder] ||= ::Builder::XmlMarkup.new(indent: options[:indent])
-
- @builder = options[:builder]
- @builder.instruct! unless options[:skip_instruct]
-
- root = (options[:root] || @serializable.model_name.element).to_s
- root = ActiveSupport::XmlMini.rename_key(root, options)
-
- args = [root]
- args << { xmlns: options[:namespace] } if options[:namespace]
- args << { type: options[:type] } if options[:type] && !options[:skip_types]
-
- @builder.tag!(*args) do
- add_attributes_and_methods
- add_includes
- add_extra_behavior
- add_procs
- yield @builder if block_given?
- end
- end
-
- private
-
- def add_extra_behavior
- end
-
- def add_attributes_and_methods
- serializable_collection.each do |attribute|
- key = ActiveSupport::XmlMini.rename_key(attribute.name, options)
- ActiveSupport::XmlMini.to_tag(key, attribute.value,
- options.merge(attribute.decorations))
- end
- end
-
- def add_includes
- @serializable.send(:serializable_add_includes, options) do |association, records, opts|
- add_associations(association, records, opts)
- end
- end
-
- # TODO: This can likely be cleaned up to simple use ActiveSupport::XmlMini.to_tag as well.
- def add_associations(association, records, opts)
- merged_options = opts.merge(options.slice(:builder, :indent))
- merged_options[:skip_instruct] = true
-
- [:skip_types, :dasherize, :camelize].each do |key|
- merged_options[key] = options[key] if merged_options[key].nil? && !options[key].nil?
- end
-
- if records.respond_to?(:to_ary)
- records = records.to_ary
-
- tag = ActiveSupport::XmlMini.rename_key(association.to_s, options)
- type = options[:skip_types] ? { } : { type: "array" }
- association_name = association.to_s.singularize
- merged_options[:root] = association_name
-
- if records.empty?
- @builder.tag!(tag, type)
- else
- @builder.tag!(tag, type) do
- records.each do |record|
- if options[:skip_types]
- record_type = {}
- else
- record_class = (record.class.to_s.underscore == association_name) ? nil : record.class.name
- record_type = { type: record_class }
- end
-
- record.to_xml merged_options.merge(record_type)
- end
- end
- end
- else
- merged_options[:root] = association.to_s
-
- unless records.class.to_s.underscore == association.to_s
- merged_options[:type] = records.class.name
- end
-
- records.to_xml merged_options
- end
- end
-
- def add_procs
- if procs = options.delete(:procs)
- Array(procs).each do |proc|
- if proc.arity == 1
- proc.call(options)
- else
- proc.call(options, @serializable)
- end
- end
- end
- end
- end
-
- # Returns XML representing the model. Configuration can be
- # passed through +options+.
- #
- # Without any +options+, the returned XML string will include all the
- # model's attributes.
- #
- # user = User.find(1)
- # user.to_xml
- #
- # <?xml version="1.0" encoding="UTF-8"?>
- # <user>
- # <id type="integer">1</id>
- # <name>David</name>
- # <age type="integer">16</age>
- # <created-at type="dateTime">2011-01-30T22:29:23Z</created-at>
- # </user>
- #
- # The <tt>:only</tt> and <tt>:except</tt> options can be used to limit the
- # attributes included, and work similar to the +attributes+ method.
- #
- # To include the result of some method calls on the model use <tt>:methods</tt>.
- #
- # To include associations use <tt>:include</tt>.
- #
- # For further documentation, see <tt>ActiveRecord::Serialization#to_xml</tt>
- def to_xml(options = {}, &block)
- Serializer.new(self, options).serialize(&block)
- end
-
- # Sets the model +attributes+ from an XML string. Returns +self+.
- #
- # class Person
- # include ActiveModel::Serializers::Xml
- #
- # attr_accessor :name, :age, :awesome
- #
- # def attributes=(hash)
- # hash.each do |key, value|
- # instance_variable_set("@#{key}", value)
- # end
- # end
- #
- # def attributes
- # instance_values
- # end
- # end
- #
- # xml = { name: 'bob', age: 22, awesome:true }.to_xml
- # person = Person.new
- # person.from_xml(xml) # => #<Person:0x007fec5e3b3c40 @age=22, @awesome=true, @name="bob">
- # person.name # => "bob"
- # person.age # => 22
- # person.awesome # => true
- def from_xml(xml)
- self.attributes = Hash.from_xml(xml).values.first
- self
- end
- end
- end
-end
diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb
index 1116f6b8ee..5f1dde4aa3 100644
--- a/activemodel/lib/active_model/validations.rb
+++ b/activemodel/lib/active_model/validations.rb
@@ -87,7 +87,7 @@ module ActiveModel
validates_with BlockValidator, _merge_attributes(attr_names), &block
end
- VALID_OPTIONS_FOR_VALIDATE = [:on, :if, :unless].freeze
+ VALID_OPTIONS_FOR_VALIDATE = [:on, :if, :unless, :prepend].freeze # :nodoc:
# Adds a validation method or block to the class. This is useful when
# overriding the +validate+ instance method becomes too unwieldy and
@@ -129,6 +129,9 @@ module ActiveModel
# end
# end
#
+ # Note that the return value of validation methods is not relevant.
+ # It's not possible to halt the validate callback chain.
+ #
# Options:
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
# Runs in all validation contexts by default (nil). You can pass a symbol
@@ -371,6 +374,15 @@ module ActiveModel
!valid?(context)
end
+ # Runs all the validations within the specified context. Returns +true+ if
+ # no errors are found, raises +ValidationError+ otherwise.
+ #
+ # Validations with no <tt>:on</tt> option will run no matter the context. Validations with
+ # some <tt>:on</tt> option will only run in the specified context.
+ def validate!(context = nil)
+ valid?(context) || raise_validation_error
+ end
+
# Hook method defining how an attribute value should be retrieved. By default
# this is assumed to be an instance named after the attribute. Override this
# method in subclasses should you need to retrieve the value for a given
@@ -392,9 +404,33 @@ module ActiveModel
protected
def run_validations! #:nodoc:
- run_validate_callbacks
+ _run_validate_callbacks
errors.empty?
end
+
+ def raise_validation_error
+ raise(ValidationError.new(self))
+ end
+ end
+
+ # = Active Model ValidationError
+ #
+ # Raised by <tt>validate!</tt> when the model is invalid. Use the
+ # +model+ method to retrieve the record which did not validate.
+ #
+ # begin
+ # complex_operation_that_internally_calls_validate!
+ # rescue ActiveModel::ValidationError => invalid
+ # puts invalid.model.errors
+ # end
+ class ValidationError < StandardError
+ attr_reader :model
+
+ def initialize(model)
+ @model = model
+ errors = @model.errors.full_messages.join(", ")
+ super(I18n.t(:"#{@model.class.i18n_scope}.errors.messages.model_invalid", errors: errors, default: :"errors.messages.model_invalid"))
+ end
end
end
diff --git a/activemodel/lib/active_model/validations/absence.rb b/activemodel/lib/active_model/validations/absence.rb
index 9b5416fb1d..75bf655578 100644
--- a/activemodel/lib/active_model/validations/absence.rb
+++ b/activemodel/lib/active_model/validations/absence.rb
@@ -1,6 +1,6 @@
module ActiveModel
module Validations
- # == Active Model Absence Validator
+ # == \Active \Model Absence Validator
class AbsenceValidator < EachValidator #:nodoc:
def validate_each(record, attr_name, value)
record.errors.add(attr_name, :present, options) if value.present?
diff --git a/activemodel/lib/active_model/validations/acceptance.rb b/activemodel/lib/active_model/validations/acceptance.rb
index ac5e79859b..1bcfedb35d 100644
--- a/activemodel/lib/active_model/validations/acceptance.rb
+++ b/activemodel/lib/active_model/validations/acceptance.rb
@@ -3,12 +3,12 @@ module ActiveModel
module Validations
class AcceptanceValidator < EachValidator # :nodoc:
def initialize(options)
- super({ allow_nil: true, accept: "1" }.merge!(options))
+ super({ allow_nil: true, accept: ["1", true] }.merge!(options))
setup!(options[:class])
end
def validate_each(record, attribute, value)
- unless value == options[:accept]
+ unless acceptable_option?(value)
record.errors.add(attribute, :accepted, options.except(:accept, :allow_nil))
end
end
@@ -20,6 +20,10 @@ module ActiveModel
klass.send(:attr_reader, *attr_readers)
klass.send(:attr_writer, *attr_writers)
end
+
+ def acceptable_option?(value)
+ Array(options[:accept]).include?(value)
+ end
end
module HelperMethods
@@ -38,9 +42,10 @@ module ActiveModel
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "must be
# accepted").
- # * <tt>:accept</tt> - Specifies value that is considered accepted.
- # The default value is a string "1", which makes it easy to relate to
- # an HTML checkbox. This should be set to +true+ if you are validating
+ # * <tt>:accept</tt> - Specifies a value that is considered accepted.
+ # Also accepts an array of possible values. The default value is
+ # an array ["1", true], which makes it easy to relate to an HTML
+ # checkbox. This should be set to, or include, +true+ if you are validating
# a database column, since the attribute is typecast from "1" to +true+
# before validation.
#
diff --git a/activemodel/lib/active_model/validations/callbacks.rb b/activemodel/lib/active_model/validations/callbacks.rb
index 1a5192b0ff..4b58ef66e3 100644
--- a/activemodel/lib/active_model/validations/callbacks.rb
+++ b/activemodel/lib/active_model/validations/callbacks.rb
@@ -15,15 +15,14 @@ module ActiveModel
# after_validation :do_stuff_after_validation
# end
#
- # Like other <tt>before_*</tt> callbacks if +before_validation+ returns
- # +false+ then <tt>valid?</tt> will not be called.
+ # Like other <tt>before_*</tt> callbacks if +before_validation+ throws
+ # +:abort+ then <tt>valid?</tt> will not be called.
module Callbacks
extend ActiveSupport::Concern
included do
include ActiveSupport::Callbacks
define_callbacks :validation,
- terminator: ->(_,result) { result == false },
skip_after_callbacks_if_terminated: true,
scope: [:kind, :name]
end
@@ -110,7 +109,7 @@ module ActiveModel
# Overwrite run validations to include callbacks.
def run_validations! #:nodoc:
- run_validation_callbacks { super }
+ _run_validation_callbacks { super }
end
end
end
diff --git a/activemodel/lib/active_model/validations/exclusion.rb b/activemodel/lib/active_model/validations/exclusion.rb
index f342d27275..6f4276cc2a 100644
--- a/activemodel/lib/active_model/validations/exclusion.rb
+++ b/activemodel/lib/active_model/validations/exclusion.rb
@@ -29,7 +29,9 @@ module ActiveModel
# Configuration options:
# * <tt>:in</tt> - An enumerable object of items that the value shouldn't
# be part of. This can be supplied as a proc, lambda or symbol which returns an
- # enumerable. If the enumerable is a range the test is performed with
+ # enumerable. If the enumerable is a numerical, time or datetime range the test
+ # is performed with <tt>Range#cover?</tt>, otherwise with <tt>include?</tt>. When
+ # using a proc or lambda the instance under validation is passed as an argument.
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
# <tt>Range#cover?</tt>, otherwise with <tt>include?</tt>.
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
diff --git a/activemodel/lib/active_model/validations/format.rb b/activemodel/lib/active_model/validations/format.rb
index ff3e95da34..46a2e54fba 100644
--- a/activemodel/lib/active_model/validations/format.rb
+++ b/activemodel/lib/active_model/validations/format.rb
@@ -54,7 +54,7 @@ module ActiveModel
module HelperMethods
# Validates whether the value of the specified attribute is of the correct
- # form, going by the regular expression provided.You can require that the
+ # form, going by the regular expression provided. You can require that the
# attribute matches the regular expression:
#
# class Person < ActiveRecord::Base
@@ -77,7 +77,7 @@ module ActiveModel
# with: ->(person) { person.admin? ? /\A[a-z0-9][a-z0-9_\-]*\z/i : /\A[a-z][a-z0-9_\-]*\z/i }
# end
#
- # Note: use <tt>\A</tt> and <tt>\Z</tt> to match the start and end of the
+ # Note: use <tt>\A</tt> and <tt>\z</tt> to match the start and end of the
# string, <tt>^</tt> and <tt>$</tt> match the start/end of a line.
#
# Due to frequent misuse of <tt>^</tt> and <tt>$</tt>, you need to pass
diff --git a/activemodel/lib/active_model/validations/helper_methods.rb b/activemodel/lib/active_model/validations/helper_methods.rb
new file mode 100644
index 0000000000..2176115334
--- /dev/null
+++ b/activemodel/lib/active_model/validations/helper_methods.rb
@@ -0,0 +1,13 @@
+module ActiveModel
+ module Validations
+ module HelperMethods # :nodoc:
+ private
+ def _merge_attributes(attr_names)
+ options = attr_names.extract_options!.symbolize_keys
+ attr_names.flatten!
+ options[:attributes] = attr_names
+ options
+ end
+ end
+ end
+end
diff --git a/activemodel/lib/active_model/validations/inclusion.rb b/activemodel/lib/active_model/validations/inclusion.rb
index c84025f083..03e0ef56d8 100644
--- a/activemodel/lib/active_model/validations/inclusion.rb
+++ b/activemodel/lib/active_model/validations/inclusion.rb
@@ -28,9 +28,9 @@ module ActiveModel
# Configuration options:
# * <tt>:in</tt> - An enumerable object of available items. This can be
# supplied as a proc, lambda or symbol which returns an enumerable. If the
- # enumerable is a numerical range the test is performed with <tt>Range#cover?</tt>,
- # otherwise with <tt>include?</tt>. When using a proc or lambda the instance
- # under validation is passed as an argument.
+ # enumerable is a numerical, time or datetime range the test is performed
+ # with <tt>Range#cover?</tt>, otherwise with <tt>include?</tt>. When using
+ # a proc or lambda the instance under validation is passed as an argument.
# * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
# * <tt>:message</tt> - Specifies a custom error message (default is: "is
# not included in the list").
diff --git a/activemodel/lib/active_model/validations/length.rb b/activemodel/lib/active_model/validations/length.rb
index a96b30cadd..910cca2f49 100644
--- a/activemodel/lib/active_model/validations/length.rb
+++ b/activemodel/lib/active_model/validations/length.rb
@@ -1,6 +1,6 @@
-module ActiveModel
+require "active_support/core_ext/string/strip"
- # == Active \Model Length Validator
+module ActiveModel
module Validations
class LengthValidator < EachValidator # :nodoc:
MESSAGES = { is: :wrong_length, minimum: :too_short, maximum: :too_long }.freeze
@@ -18,6 +18,27 @@ module ActiveModel
options[:minimum] = 1
end
+ if options[:tokenizer]
+ ActiveSupport::Deprecation.warn(<<-EOS.strip_heredoc)
+ The `:tokenizer` option is deprecated, and will be removed in Rails 5.1.
+ You can achieve the same functionality by defining an instance method
+ with the value that you want to validate the length of. For example,
+
+ validates_length_of :essay, minimum: 100,
+ tokenizer: ->(str) { str.scan(/\w+/) }
+
+ should be written as
+
+ validates_length_of :words_in_essay, minimum: 100
+
+ private
+
+ def words_in_essay
+ essay.scan(/\w+/)
+ end
+ EOS
+ end
+
super
end
@@ -38,7 +59,7 @@ module ActiveModel
end
def validate_each(record, attribute, value)
- value = tokenize(value)
+ value = tokenize(record, value)
value_length = value.respond_to?(:length) ? value.length : value.to_s.length
errors_options = options.except(*RESERVED_OPTIONS)
@@ -59,10 +80,14 @@ module ActiveModel
end
private
-
- def tokenize(value)
- if options[:tokenizer] && value.kind_of?(String)
- options[:tokenizer].call(value)
+ def tokenize(record, value)
+ tokenizer = options[:tokenizer]
+ if tokenizer && value.kind_of?(String)
+ if tokenizer.kind_of?(Proc)
+ tokenizer.call(value)
+ elsif record.respond_to?(tokenizer)
+ record.send(tokenizer, value)
+ end
end || value
end
@@ -73,8 +98,9 @@ module ActiveModel
module HelperMethods
- # Validates that the specified attribute matches the length restrictions
- # supplied. Only one option can be used at a time:
+ # Validates that the specified attributes match the length restrictions
+ # supplied. Only one constraint option can be used at a time apart from
+ # +:minimum+ and +:maximum+ that can be combined together:
#
# class Person < ActiveRecord::Base
# validates_length_of :first_name, maximum: 30
@@ -84,18 +110,27 @@ module ActiveModel
# validates_length_of :user_name, within: 6..20, too_long: 'pick a shorter name', too_short: 'pick a longer name'
# validates_length_of :zip_code, minimum: 5, too_short: 'please enter at least 5 characters'
# validates_length_of :smurf_leader, is: 4, message: "papa is spelled with 4 characters... don't play me."
- # validates_length_of :essay, minimum: 100, too_short: 'Your essay must be at least 100 words.',
- # tokenizer: ->(str) { str.scan(/\w+/) }
+ # validates_length_of :words_in_essay, minimum: 100, too_short: 'Your essay must be at least 100 words.'
+ #
+ # private
+ #
+ # def words_in_essay
+ # essay.scan(/\w+/)
+ # end
# end
#
- # Configuration options:
+ # Constraint options:
+ #
# * <tt>:minimum</tt> - The minimum size of the attribute.
# * <tt>:maximum</tt> - The maximum size of the attribute. Allows +nil+ by
- # default if not used with :minimum.
+ # default if not used with +:minimum+.
# * <tt>:is</tt> - The exact size of the attribute.
# * <tt>:within</tt> - A range specifying the minimum and maximum size of
# the attribute.
# * <tt>:in</tt> - A synonym (or alias) for <tt>:within</tt>.
+ #
+ # Other options:
+ #
# * <tt>:allow_nil</tt> - Attribute may be +nil+; skip validation.
# * <tt>:allow_blank</tt> - Attribute may be blank; skip validation.
# * <tt>:too_long</tt> - The error message if the attribute goes over the
@@ -108,10 +143,6 @@ module ActiveModel
# * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>,
# <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate
# <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message.
- # * <tt>:tokenizer</tt> - Specifies how to split up the attribute string.
- # (e.g. <tt>tokenizer: ->(str) { str.scan(/\w+/) }</tt> to count words
- # as in above example). Defaults to <tt>->(value) { value.split(//) }</tt>
- # which counts individual characters.
#
# There is also a list of default options supported by every validator:
# +:if+, +:unless+, +:on+ and +:strict+.
diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb
index 13d6a966c0..4ba4e3e8f7 100644
--- a/activemodel/lib/active_model/validations/numericality.rb
+++ b/activemodel/lib/active_model/validations/numericality.rb
@@ -23,6 +23,10 @@ module ActiveModel
raw_value = record.send(before_type_cast) if record.respond_to?(before_type_cast)
raw_value ||= value
+ if record_attribute_changed_in_place?(record, attr_name)
+ raw_value = value
+ end
+
return if options[:allow_nil] && raw_value.nil?
unless value = parse_raw_value_as_a_number(raw_value)
@@ -86,6 +90,13 @@ module ActiveModel
options[:only_integer]
end
end
+
+ private
+
+ def record_attribute_changed_in_place?(record, attr_name)
+ record.respond_to?(:attribute_changed_in_place?) &&
+ record.attribute_changed_in_place?(attr_name.to_s)
+ end
end
module HelperMethods
diff --git a/activemodel/lib/active_model/validations/validates.rb b/activemodel/lib/active_model/validations/validates.rb
index bda436d8d0..1da4df21e7 100644
--- a/activemodel/lib/active_model/validations/validates.rb
+++ b/activemodel/lib/active_model/validations/validates.rb
@@ -115,7 +115,7 @@ module ActiveModel
key = "#{key.to_s.camelize}Validator"
begin
- validator = key.include?('::') ? key.constantize : const_get(key)
+ validator = key.include?('::'.freeze) ? key.constantize : const_get(key)
rescue NameError
raise ArgumentError, "Unknown validator: '#{key}'"
end
diff --git a/activemodel/lib/active_model/validations/with.rb b/activemodel/lib/active_model/validations/with.rb
index a2531327bf..6de01b3392 100644
--- a/activemodel/lib/active_model/validations/with.rb
+++ b/activemodel/lib/active_model/validations/with.rb
@@ -1,15 +1,5 @@
module ActiveModel
module Validations
- module HelperMethods
- private
- def _merge_attributes(attr_names)
- options = attr_names.extract_options!.symbolize_keys
- attr_names.flatten!
- options[:attributes] = attr_names
- options
- end
- end
-
class WithValidator < EachValidator # :nodoc:
def validate_each(record, attr, val)
method_name = options[:with]
diff --git a/activemodel/lib/active_model/validator.rb b/activemodel/lib/active_model/validator.rb
index 0116de68ab..1d2888a818 100644
--- a/activemodel/lib/active_model/validator.rb
+++ b/activemodel/lib/active_model/validator.rb
@@ -15,7 +15,7 @@ module ActiveModel
# class MyValidator < ActiveModel::Validator
# def validate(record)
# if some_complex_logic
- # record.errors[:base] = "This record is invalid"
+ # record.errors.add(:base, "This record is invalid")
# end
# end
#
@@ -127,7 +127,7 @@ module ActiveModel
# in the options hash invoking the <tt>validate_each</tt> method passing in the
# record, attribute and value.
#
- # All Active Model validations are built on top of this validator.
+ # All \Active \Model validations are built on top of this validator.
class EachValidator < Validator #:nodoc:
attr_reader :attributes
@@ -163,6 +163,10 @@ module ActiveModel
# +ArgumentError+ when invalid options are supplied.
def check_validity!
end
+
+ def should_validate?(record) # :nodoc:
+ !record.persisted? || record.changed? || record.marked_for_destruction?
+ end
end
# +BlockValidator+ is a special +EachValidator+ which receives a block on initialization
diff --git a/activemodel/lib/active_model/version.rb b/activemodel/lib/active_model/version.rb
index b1f9082ea7..6da3b4117b 100644
--- a/activemodel/lib/active_model/version.rb
+++ b/activemodel/lib/active_model/version.rb
@@ -1,7 +1,7 @@
require_relative 'gem_version'
module ActiveModel
- # Returns the version of the currently loaded ActiveModel as a <tt>Gem::Version</tt>
+ # Returns the version of the currently loaded \Active \Model as a <tt>Gem::Version</tt>
def self.version
gem_version
end
diff --git a/activemodel/test/cases/attribute_assignment_test.rb b/activemodel/test/cases/attribute_assignment_test.rb
new file mode 100644
index 0000000000..64a85e01eb
--- /dev/null
+++ b/activemodel/test/cases/attribute_assignment_test.rb
@@ -0,0 +1,107 @@
+require "cases/helper"
+require "active_support/hash_with_indifferent_access"
+
+class AttributeAssignmentTest < ActiveModel::TestCase
+ class Model
+ include ActiveModel::AttributeAssignment
+
+ attr_accessor :name, :description
+
+ def initialize(attributes = {})
+ assign_attributes(attributes)
+ end
+
+ def broken_attribute=(value)
+ raise ErrorFromAttributeWriter
+ end
+
+ protected
+
+ attr_writer :metadata
+ end
+
+ class ErrorFromAttributeWriter < StandardError
+ end
+
+ class ProtectedParams < ActiveSupport::HashWithIndifferentAccess
+ def permit!
+ @permitted = true
+ end
+
+ def permitted?
+ @permitted ||= false
+ end
+
+ def dup
+ super.tap do |duplicate|
+ duplicate.instance_variable_set :@permitted, permitted?
+ end
+ end
+ end
+
+ test "simple assignment" do
+ model = Model.new
+
+ model.assign_attributes(name: "hello", description: "world")
+ assert_equal "hello", model.name
+ assert_equal "world", model.description
+ end
+
+ test "assign non-existing attribute" do
+ model = Model.new
+ error = assert_raises(ActiveModel::UnknownAttributeError) do
+ model.assign_attributes(hz: 1)
+ end
+
+ assert_equal model, error.record
+ assert_equal "hz", error.attribute
+ end
+
+ test "assign private attribute" do
+ model = Model.new
+ assert_raises(ActiveModel::UnknownAttributeError) do
+ model.assign_attributes(metadata: { a: 1 })
+ end
+ end
+
+ test "does not swallow errors raised in an attribute writer" do
+ assert_raises(ErrorFromAttributeWriter) do
+ Model.new(broken_attribute: 1)
+ end
+ end
+
+ test "an ArgumentError is raised if a non-hash-like obejct is passed" do
+ assert_raises(ArgumentError) do
+ Model.new(1)
+ end
+ end
+
+ test "forbidden attributes cannot be used for mass assignment" do
+ params = ProtectedParams.new(name: "Guille", description: "m")
+
+ assert_raises(ActiveModel::ForbiddenAttributesError) do
+ Model.new(params)
+ end
+ end
+
+ test "permitted attributes can be used for mass assignment" do
+ params = ProtectedParams.new(name: "Guille", description: "desc")
+ params.permit!
+ model = Model.new(params)
+
+ assert_equal "Guille", model.name
+ assert_equal "desc", model.description
+ end
+
+ test "regular hash should still be used for mass assignment" do
+ model = Model.new(name: "Guille", description: "m")
+
+ assert_equal "Guille", model.name
+ assert_equal "m", model.description
+ end
+
+ test "assigning no attributes should not raise, even if the hash is un-permitted" do
+ model = Model.new
+ assert_nil model.assign_attributes(ProtectedParams.new({}))
+ end
+end
diff --git a/activemodel/test/cases/callbacks_test.rb b/activemodel/test/cases/callbacks_test.rb
index 5fede098d1..85455c112c 100644
--- a/activemodel/test/cases/callbacks_test.rb
+++ b/activemodel/test/cases/callbacks_test.rb
@@ -7,6 +7,7 @@ class CallbacksTest < ActiveModel::TestCase
model.callbacks << :before_around_create
yield
model.callbacks << :after_around_create
+ false
end
end
@@ -24,16 +25,22 @@ class CallbacksTest < ActiveModel::TestCase
after_create do |model|
model.callbacks << :after_create
+ false
end
after_create "@callbacks << :final_callback"
- def initialize(valid=true)
- @callbacks, @valid = [], valid
+ def initialize(options = {})
+ @callbacks = []
+ @valid = options[:valid]
+ @before_create_returns = options.fetch(:before_create_returns, true)
+ @before_create_throws = options[:before_create_throws]
end
def before_create
@callbacks << :before_create
+ throw(@before_create_throws) if @before_create_throws
+ @before_create_returns
end
def create
@@ -51,14 +58,28 @@ class CallbacksTest < ActiveModel::TestCase
:after_around_create, :after_create, :final_callback]
end
- test "after callbacks are always appended" do
+ test "the callback chain is not halted when around or after callbacks return false" do
model = ModelCallbacks.new
model.create
assert_equal model.callbacks.last, :final_callback
end
+ test "the callback chain is halted when a before callback returns false (deprecated)" do
+ model = ModelCallbacks.new(before_create_returns: false)
+ assert_deprecated do
+ model.create
+ assert_equal model.callbacks.last, :before_create
+ end
+ end
+
+ test "the callback chain is halted when a callback throws :abort" do
+ model = ModelCallbacks.new(before_create_throws: :abort)
+ model.create
+ assert_equal model.callbacks, [:before_create]
+ end
+
test "after callbacks are not executed if the block returns false" do
- model = ModelCallbacks.new(false)
+ model = ModelCallbacks.new(valid: false)
model.create
assert_equal model.callbacks, [ :before_create, :before_around_create,
:create, :after_around_create]
diff --git a/activemodel/test/cases/dirty_test.rb b/activemodel/test/cases/dirty_test.rb
index db2cd885e2..d17a12ad12 100644
--- a/activemodel/test/cases/dirty_test.rb
+++ b/activemodel/test/cases/dirty_test.rb
@@ -45,10 +45,6 @@ class DirtyTest < ActiveModel::TestCase
def reload
clear_changes_information
end
-
- def deprecated_reload
- reset_changes
- end
end
setup do
@@ -141,6 +137,19 @@ class DirtyTest < ActiveModel::TestCase
assert_equal [nil, "Jericho Cane"], @model.previous_changes['name']
end
+ test "setting new attributes should not affect previous changes" do
+ @model.name = "Jericho Cane"
+ @model.save
+ @model.name = "DudeFella ManGuy"
+ assert_equal [nil, "Jericho Cane"], @model.name_previous_change
+ end
+
+ test "saving should preserve model's previous changed status" do
+ @model.name = "Jericho Cane"
+ @model.save
+ assert @model.name_previously_changed?
+ end
+
test "previous value is preserved when changed after save" do
assert_equal({}, @model.changed_attributes)
@model.name = "Paul"
@@ -181,23 +190,6 @@ class DirtyTest < ActiveModel::TestCase
assert_equal ActiveSupport::HashWithIndifferentAccess.new, @model.changed_attributes
end
- test "reset_changes is deprecated" do
- @model.name = 'Dmitry'
- @model.name_changed?
- @model.save
- @model.name = 'Bob'
-
- assert_equal [nil, 'Dmitry'], @model.previous_changes['name']
- assert_equal 'Dmitry', @model.changed_attributes['name']
-
- assert_deprecated do
- @model.deprecated_reload
- end
-
- assert_equal ActiveSupport::HashWithIndifferentAccess.new, @model.previous_changes
- assert_equal ActiveSupport::HashWithIndifferentAccess.new, @model.changed_attributes
- end
-
test "restore_attributes should restore all previous data" do
@model.name = 'Dmitry'
@model.color = 'Red'
diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb
index efedd9055f..f6d171bec6 100644
--- a/activemodel/test/cases/errors_test.rb
+++ b/activemodel/test/cases/errors_test.rb
@@ -29,28 +29,28 @@ class ErrorsTest < ActiveModel::TestCase
def test_delete
errors = ActiveModel::Errors.new(self)
- errors[:foo] = 'omg'
+ errors[:foo] << 'omg'
errors.delete(:foo)
assert_empty errors[:foo]
end
def test_include?
errors = ActiveModel::Errors.new(self)
- errors[:foo] = 'omg'
+ errors[:foo] << 'omg'
assert errors.include?(:foo), 'errors should include :foo'
end
def test_dup
errors = ActiveModel::Errors.new(self)
- errors[:foo] = 'bar'
+ errors[:foo] << 'bar'
errors_dup = errors.dup
- errors_dup[:bar] = 'omg'
+ errors_dup[:bar] << 'omg'
assert_not_same errors_dup.messages, errors.messages
end
def test_has_key?
errors = ActiveModel::Errors.new(self)
- errors[:foo] = 'omg'
+ errors[:foo] << 'omg'
assert_equal true, errors.has_key?(:foo), 'errors should have key :foo'
end
@@ -61,7 +61,7 @@ class ErrorsTest < ActiveModel::TestCase
def test_key?
errors = ActiveModel::Errors.new(self)
- errors[:foo] = 'omg'
+ errors[:foo] << 'omg'
assert_equal true, errors.key?(:foo), 'errors should have key :foo'
end
@@ -81,37 +81,41 @@ class ErrorsTest < ActiveModel::TestCase
test "get returns the errors for the provided key" do
errors = ActiveModel::Errors.new(self)
- errors[:foo] = "omg"
+ errors[:foo] << "omg"
- assert_equal ["omg"], errors.get(:foo)
+ assert_deprecated do
+ assert_equal ["omg"], errors.get(:foo)
+ end
end
test "sets the error with the provided key" do
errors = ActiveModel::Errors.new(self)
- errors.set(:foo, "omg")
+ assert_deprecated do
+ errors.set(:foo, "omg")
+ end
assert_equal({ foo: "omg" }, errors.messages)
end
test "error access is indifferent" do
errors = ActiveModel::Errors.new(self)
- errors[:foo] = "omg"
+ errors[:foo] << "omg"
assert_equal ["omg"], errors["foo"]
end
test "values returns an array of messages" do
errors = ActiveModel::Errors.new(self)
- errors.set(:foo, "omg")
- errors.set(:baz, "zomg")
+ errors.messages[:foo] = "omg"
+ errors.messages[:baz] = "zomg"
assert_equal ["omg", "zomg"], errors.values
end
test "keys returns the error keys" do
errors = ActiveModel::Errors.new(self)
- errors.set(:foo, "omg")
- errors.set(:baz, "zomg")
+ errors.messages[:foo] << "omg"
+ errors.messages[:baz] << "zomg"
assert_equal [:foo, :baz], errors.keys
end
@@ -133,7 +137,9 @@ class ErrorsTest < ActiveModel::TestCase
test "assign error" do
person = Person.new
- person.errors[:name] = 'should not be nil'
+ assert_deprecated do
+ person.errors[:name] = 'should not be nil'
+ end
assert_equal ["should not be nil"], person.errors[:name]
end
@@ -143,6 +149,12 @@ class ErrorsTest < ActiveModel::TestCase
assert_equal ["cannot be blank"], person.errors[:name]
end
+ test "add an error message on a specific attribute with a defined type" do
+ person = Person.new
+ person.errors.add(:name, :blank, message: "cannot be blank")
+ assert_equal ["cannot be blank"], person.errors[:name]
+ end
+
test "add an error with a symbol" do
person = Person.new
person.errors.add(:name, :blank)
@@ -206,6 +218,12 @@ class ErrorsTest < ActiveModel::TestCase
assert_equal 1, person.errors.size
end
+ test "count calculates the number of error messages" do
+ person = Person.new
+ person.errors.add(:name, "cannot be blank")
+ assert_equal 1, person.errors.count
+ end
+
test "to_a returns the list of errors with complete messages containing the attribute names" do
person = Person.new
person.errors.add(:name, "cannot be blank")
@@ -281,46 +299,115 @@ class ErrorsTest < ActiveModel::TestCase
test "add_on_empty generates message" do
person = Person.new
- person.errors.expects(:generate_message).with(:name, :empty, {})
- person.errors.add_on_empty :name
+ assert_called_with(person.errors, :generate_message, [:name, :empty, {}]) do
+ assert_deprecated do
+ person.errors.add_on_empty :name
+ end
+ end
end
test "add_on_empty generates message for multiple attributes" do
person = Person.new
- person.errors.expects(:generate_message).with(:name, :empty, {})
- person.errors.expects(:generate_message).with(:age, :empty, {})
- person.errors.add_on_empty [:name, :age]
+ expected_calls = [ [:name, :empty, {}], [:age, :empty, {}] ]
+ assert_called_with(person.errors, :generate_message, expected_calls) do
+ assert_deprecated do
+ person.errors.add_on_empty [:name, :age]
+ end
+ end
end
test "add_on_empty generates message with custom default message" do
person = Person.new
- person.errors.expects(:generate_message).with(:name, :empty, { message: 'custom' })
- person.errors.add_on_empty :name, message: 'custom'
+ assert_called_with(person.errors, :generate_message, [:name, :empty, { message: 'custom' }]) do
+ assert_deprecated do
+ person.errors.add_on_empty :name, message: 'custom'
+ end
+ end
end
test "add_on_empty generates message with empty string value" do
person = Person.new
person.name = ''
- person.errors.expects(:generate_message).with(:name, :empty, {})
- person.errors.add_on_empty :name
+ assert_called_with(person.errors, :generate_message, [:name, :empty, {}]) do
+ assert_deprecated do
+ person.errors.add_on_empty :name
+ end
+ end
end
test "add_on_blank generates message" do
person = Person.new
- person.errors.expects(:generate_message).with(:name, :blank, {})
- person.errors.add_on_blank :name
+ assert_called_with(person.errors, :generate_message, [:name, :blank, {}]) do
+ assert_deprecated do
+ person.errors.add_on_blank :name
+ end
+ end
end
test "add_on_blank generates message for multiple attributes" do
person = Person.new
- person.errors.expects(:generate_message).with(:name, :blank, {})
- person.errors.expects(:generate_message).with(:age, :blank, {})
- person.errors.add_on_blank [:name, :age]
+ expected_calls = [ [:name, :blank, {}], [:age, :blank, {}] ]
+ assert_called_with(person.errors, :generate_message, expected_calls) do
+ assert_deprecated do
+ person.errors.add_on_blank [:name, :age]
+ end
+ end
end
test "add_on_blank generates message with custom default message" do
person = Person.new
- person.errors.expects(:generate_message).with(:name, :blank, { message: 'custom' })
- person.errors.add_on_blank :name, message: 'custom'
+ assert_called_with(person.errors, :generate_message, [:name, :blank, { message: 'custom' }]) do
+ assert_deprecated do
+ person.errors.add_on_blank :name, message: 'custom'
+ end
+ end
+ end
+
+ test "details returns added error detail" do
+ person = Person.new
+ person.errors.add(:name, :invalid)
+ assert_equal({ name: [{ error: :invalid }] }, person.errors.details)
+ end
+
+ test "details returns added error detail with custom option" do
+ person = Person.new
+ person.errors.add(:name, :greater_than, count: 5)
+ assert_equal({ name: [{ error: :greater_than, count: 5 }] }, person.errors.details)
+ end
+
+ test "details do not include message option" do
+ person = Person.new
+ person.errors.add(:name, :invalid, message: "is bad")
+ assert_equal({ name: [{ error: :invalid }] }, person.errors.details)
+ end
+
+ test "dup duplicates details" do
+ errors = ActiveModel::Errors.new(Person.new)
+ errors.add(:name, :invalid)
+ errors_dup = errors.dup
+ errors_dup.add(:name, :taken)
+ assert_not_equal errors_dup.details, errors.details
+ end
+
+ test "delete removes details on given attribute" do
+ errors = ActiveModel::Errors.new(Person.new)
+ errors.add(:name, :invalid)
+ errors.delete(:name)
+ assert_empty errors.details[:name]
+ end
+
+ test "delete returns the deleted messages" do
+ errors = ActiveModel::Errors.new(Person.new)
+ errors.add(:name, :invalid)
+ assert_equal ["is invalid"], errors.delete(:name)
+ end
+
+ test "clear removes details" do
+ person = Person.new
+ person.errors.add(:name, :invalid)
+
+ assert_equal 1, person.errors.details.count
+ person.errors.clear
+ assert person.errors.details.empty?
end
end
diff --git a/activemodel/test/cases/helper.rb b/activemodel/test/cases/helper.rb
index 4ce6103593..0cd80be66f 100644
--- a/activemodel/test/cases/helper.rb
+++ b/activemodel/test/cases/helper.rb
@@ -11,10 +11,17 @@ ActiveSupport::Deprecation.debug = true
I18n.enforce_available_locales = false
require 'active_support/testing/autorun'
+require 'active_support/testing/method_call_assertions'
-require 'mocha/setup' # FIXME: stop using mocha
+# Skips the current run on Rubinius using Minitest::Assertions#skip
+def rubinius_skip(message = '')
+ skip message if RUBY_ENGINE == 'rbx'
+end
+# Skips the current run on JRuby using Minitest::Assertions#skip
+def jruby_skip(message = '')
+ skip message if defined?(JRUBY_VERSION)
+end
-# FIXME: we have tests that depend on run order, we should fix that and
-# remove this method call.
-require 'active_support/test_case'
-ActiveSupport::TestCase.test_order = :sorted
+class ActiveModel::TestCase
+ include ActiveSupport::Testing::MethodCallAssertions
+end
diff --git a/activemodel/test/cases/model_test.rb b/activemodel/test/cases/model_test.rb
index ee0fa26546..3017f3541b 100644
--- a/activemodel/test/cases/model_test.rb
+++ b/activemodel/test/cases/model_test.rb
@@ -70,6 +70,8 @@ class ModelTest < ActiveModel::TestCase
end
def test_mixin_initializer_when_args_dont_exist
- assert_raises(NoMethodError) { SimpleModel.new(hello: 'world') }
+ assert_raises(ActiveModel::UnknownAttributeError) do
+ SimpleModel.new(hello: 'world')
+ end
end
end
diff --git a/activemodel/test/cases/serialization_test.rb b/activemodel/test/cases/serialization_test.rb
index 4ae41aa19c..8d3165cd78 100644
--- a/activemodel/test/cases/serialization_test.rb
+++ b/activemodel/test/cases/serialization_test.rb
@@ -16,6 +16,14 @@ class SerializationTest < ActiveModel::TestCase
instance_values.except("address", "friends")
end
+ def method_missing(method_name, *args)
+ if method_name == :bar
+ 'i_am_bar'
+ else
+ super
+ end
+ end
+
def foo
'i_am_foo'
end
@@ -58,23 +66,22 @@ class SerializationTest < ActiveModel::TestCase
end
def test_method_serializable_hash_should_work_with_methods_option
- expected = {"name"=>"David", "gender"=>"male", "foo"=>"i_am_foo", "email"=>"david@example.com"}
- assert_equal expected, @user.serializable_hash(methods: [:foo])
+ expected = {"name"=>"David", "gender"=>"male", "foo"=>"i_am_foo", "bar"=>"i_am_bar", "email"=>"david@example.com"}
+ assert_equal expected, @user.serializable_hash(methods: [:foo, :bar])
end
def test_method_serializable_hash_should_work_with_only_and_methods
- expected = {"foo"=>"i_am_foo"}
- assert_equal expected, @user.serializable_hash(only: [], methods: [:foo])
+ expected = {"foo"=>"i_am_foo", "bar"=>"i_am_bar"}
+ assert_equal expected, @user.serializable_hash(only: [], methods: [:foo, :bar])
end
def test_method_serializable_hash_should_work_with_except_and_methods
- expected = {"gender"=>"male", "foo"=>"i_am_foo"}
- assert_equal expected, @user.serializable_hash(except: [:name, :email], methods: [:foo])
+ expected = {"gender"=>"male", "foo"=>"i_am_foo", "bar"=>"i_am_bar"}
+ assert_equal expected, @user.serializable_hash(except: [:name, :email], methods: [:foo, :bar])
end
- def test_should_not_call_methods_that_dont_respond
- expected = {"name"=>"David", "gender"=>"male", "email"=>"david@example.com"}
- assert_equal expected, @user.serializable_hash(methods: [:bar])
+ def test_should_raise_NoMethodError_for_non_existing_method
+ assert_raise(NoMethodError) { @user.serializable_hash(methods: [:nada]) }
end
def test_should_use_read_attribute_for_serialization
diff --git a/activemodel/test/cases/serializers/json_serialization_test.rb b/activemodel/test/cases/serializers/json_serialization_test.rb
index e2eb91eeb0..d765a47636 100644
--- a/activemodel/test/cases/serializers/json_serialization_test.rb
+++ b/activemodel/test/cases/serializers/json_serialization_test.rb
@@ -195,4 +195,8 @@ class JsonSerializationTest < ActiveModel::TestCase
assert_no_match %r{"awesome":}, json
assert_no_match %r{"preferences":}, json
end
+
+ test "Class.model_name should be json encodable" do
+ assert_match %r{"Contact"}, Contact.model_name.to_json
+ end
end
diff --git a/activemodel/test/cases/serializers/xml_serialization_test.rb b/activemodel/test/cases/serializers/xml_serialization_test.rb
deleted file mode 100644
index 22fca5bd17..0000000000
--- a/activemodel/test/cases/serializers/xml_serialization_test.rb
+++ /dev/null
@@ -1,250 +0,0 @@
-require 'cases/helper'
-require 'models/contact'
-require 'active_support/core_ext/object/instance_variables'
-require 'ostruct'
-
-module Admin
- class Contact < ::Contact
- end
-end
-
-class Customer < Struct.new(:name)
-end
-
-class Address
- include ActiveModel::Serializers::Xml
-
- attr_accessor :street, :city, :state, :zip, :apt_number
-
- def attributes
- instance_values
- end
-end
-
-class SerializableContact < Contact
- def serializable_hash(options={})
- super(options.merge(only: [:name, :age]))
- end
-end
-
-class XmlSerializationTest < ActiveModel::TestCase
- def setup
- @contact = Contact.new
- @contact.name = 'aaron stack'
- @contact.age = 25
- @contact.created_at = Time.utc(2006, 8, 1)
- @contact.awesome = false
- customer = Customer.new
- customer.name = "John"
- @contact.preferences = customer
- @contact.address = Address.new
- @contact.address.city = "Springfield"
- @contact.address.apt_number = 35
- @contact.friends = [Contact.new, Contact.new]
- @contact.contact = SerializableContact.new
- end
-
- test "should serialize default root" do
- xml = @contact.to_xml
- assert_match %r{^<contact>}, xml
- assert_match %r{</contact>$}, xml
- end
-
- test "should serialize namespaced root" do
- xml = Admin::Contact.new(@contact.attributes).to_xml
- assert_match %r{^<contact>}, xml
- assert_match %r{</contact>$}, xml
- end
-
- test "should serialize default root with namespace" do
- xml = @contact.to_xml namespace: "http://xml.rubyonrails.org/contact"
- assert_match %r{^<contact xmlns="http://xml.rubyonrails.org/contact">}, xml
- assert_match %r{</contact>$}, xml
- end
-
- test "should serialize custom root" do
- xml = @contact.to_xml root: 'xml_contact'
- assert_match %r{^<xml-contact>}, xml
- assert_match %r{</xml-contact>$}, xml
- end
-
- test "should allow undasherized tags" do
- xml = @contact.to_xml root: 'xml_contact', dasherize: false
- assert_match %r{^<xml_contact>}, xml
- assert_match %r{</xml_contact>$}, xml
- assert_match %r{<created_at}, xml
- end
-
- test "should allow camelized tags" do
- xml = @contact.to_xml root: 'xml_contact', camelize: true
- assert_match %r{^<XmlContact>}, xml
- assert_match %r{</XmlContact>$}, xml
- assert_match %r{<CreatedAt}, xml
- end
-
- test "should allow lower-camelized tags" do
- xml = @contact.to_xml root: 'xml_contact', camelize: :lower
- assert_match %r{^<xmlContact>}, xml
- assert_match %r{</xmlContact>$}, xml
- assert_match %r{<createdAt}, xml
- end
-
- test "should use serializable hash" do
- @contact = SerializableContact.new
- @contact.name = 'aaron stack'
- @contact.age = 25
-
- xml = @contact.to_xml
- assert_match %r{<name>aaron stack</name>}, xml
- assert_match %r{<age type="integer">25</age>}, xml
- assert_no_match %r{<awesome>}, xml
- end
-
- test "should allow skipped types" do
- xml = @contact.to_xml skip_types: true
- assert_match %r{<age>25</age>}, xml
- end
-
- test "should include yielded additions" do
- xml_output = @contact.to_xml do |xml|
- xml.creator "David"
- end
- assert_match %r{<creator>David</creator>}, xml_output
- end
-
- test "should serialize string" do
- assert_match %r{<name>aaron stack</name>}, @contact.to_xml
- end
-
- test "should serialize nil" do
- assert_match %r{<pseudonyms nil="true"/>}, @contact.to_xml(methods: :pseudonyms)
- end
-
- test "should serialize integer" do
- assert_match %r{<age type="integer">25</age>}, @contact.to_xml
- end
-
- test "should serialize datetime" do
- assert_match %r{<created-at type="dateTime">2006-08-01T00:00:00Z</created-at>}, @contact.to_xml
- end
-
- test "should serialize boolean" do
- assert_match %r{<awesome type="boolean">false</awesome>}, @contact.to_xml
- end
-
- test "should serialize array" do
- assert_match %r{<social type="array">\s*<social>twitter</social>\s*<social>github</social>\s*</social>}, @contact.to_xml(methods: :social)
- end
-
- test "should serialize hash" do
- assert_match %r{<network>\s*<git type="symbol">github</git>\s*</network>}, @contact.to_xml(methods: :network)
- end
-
- test "should serialize yaml" do
- assert_match %r{<preferences type="yaml">--- !ruby/struct:Customer(\s*)\nname: John\n</preferences>}, @contact.to_xml
- end
-
- test "should call proc on object" do
- proc = Proc.new { |options| options[:builder].tag!('nationality', 'unknown') }
- xml = @contact.to_xml(procs: [ proc ])
- assert_match %r{<nationality>unknown</nationality>}, xml
- end
-
- test "should supply serializable to second proc argument" do
- proc = Proc.new { |options, record| options[:builder].tag!('name-reverse', record.name.reverse) }
- xml = @contact.to_xml(procs: [ proc ])
- assert_match %r{<name-reverse>kcats noraa</name-reverse>}, xml
- end
-
- test "should serialize string correctly when type passed" do
- xml = @contact.to_xml type: 'Contact'
- assert_match %r{<contact type="Contact">}, xml
- assert_match %r{<name>aaron stack</name>}, xml
- end
-
- test "include option with singular association" do
- xml = @contact.to_xml include: :address, indent: 0
- assert xml.include?(@contact.address.to_xml(indent: 0, skip_instruct: true))
- end
-
- test "include option with plural association" do
- xml = @contact.to_xml include: :friends, indent: 0
- assert_match %r{<friends type="array">}, xml
- assert_match %r{<friend type="Contact">}, xml
- end
-
- class FriendList
- def initialize(friends)
- @friends = friends
- end
-
- def to_ary
- @friends
- end
- end
-
- test "include option with ary" do
- @contact.friends = FriendList.new(@contact.friends)
- xml = @contact.to_xml include: :friends, indent: 0
- assert_match %r{<friends type="array">}, xml
- assert_match %r{<friend type="Contact">}, xml
- end
-
- test "multiple includes" do
- xml = @contact.to_xml indent: 0, skip_instruct: true, include: [ :address, :friends ]
- assert xml.include?(@contact.address.to_xml(indent: 0, skip_instruct: true))
- assert_match %r{<friends type="array">}, xml
- assert_match %r{<friend type="Contact">}, xml
- end
-
- test "include with options" do
- xml = @contact.to_xml indent: 0, skip_instruct: true, include: { address: { only: :city } }
- assert xml.include?(%(><address><city>Springfield</city></address>))
- end
-
- test "propagates skip_types option to included associations" do
- xml = @contact.to_xml include: :friends, indent: 0, skip_types: true
- assert_match %r{<friends>}, xml
- assert_match %r{<friend>}, xml
- end
-
- test "propagates skip-types option to included associations and attributes" do
- xml = @contact.to_xml skip_types: true, include: :address, indent: 0
- assert_match %r{<address>}, xml
- assert_match %r{<apt-number>}, xml
- end
-
- test "propagates camelize option to included associations and attributes" do
- xml = @contact.to_xml camelize: true, include: :address, indent: 0
- assert_match %r{<Address>}, xml
- assert_match %r{<AptNumber type="integer">}, xml
- end
-
- test "propagates dasherize option to included associations and attributes" do
- xml = @contact.to_xml dasherize: false, include: :address, indent: 0
- assert_match %r{<apt_number type="integer">}, xml
- end
-
- test "don't propagate skip_types if skip_types is defined at the included association level" do
- xml = @contact.to_xml skip_types: true, include: { address: { skip_types: false } }, indent: 0
- assert_match %r{<address>}, xml
- assert_match %r{<apt-number type="integer">}, xml
- end
-
- test "don't propagate camelize if camelize is defined at the included association level" do
- xml = @contact.to_xml camelize: true, include: { address: { camelize: false } }, indent: 0
- assert_match %r{<address>}, xml
- assert_match %r{<apt-number type="integer">}, xml
- end
-
- test "don't propagate dasherize if dasherize is defined at the included association level" do
- xml = @contact.to_xml dasherize: false, include: { address: { dasherize: true } }, indent: 0
- assert_match %r{<address>}, xml
- assert_match %r{<apt-number type="integer">}, xml
- end
-
- test "association with sti" do
- xml = @contact.to_xml(include: :contact)
- assert xml.include?(%(<contact type="SerializableContact">))
- end
-end
diff --git a/activemodel/test/cases/validations/absence_validation_test.rb b/activemodel/test/cases/validations/absence_validation_test.rb
index ebfe1cf4e4..9cbc77dfb5 100644
--- a/activemodel/test/cases/validations/absence_validation_test.rb
+++ b/activemodel/test/cases/validations/absence_validation_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'cases/helper'
require 'models/topic'
require 'models/person'
diff --git a/activemodel/test/cases/validations/acceptance_validation_test.rb b/activemodel/test/cases/validations/acceptance_validation_test.rb
index e78aa1adaf..d3995ad5af 100644
--- a/activemodel/test/cases/validations/acceptance_validation_test.rb
+++ b/activemodel/test/cases/validations/acceptance_validation_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'cases/helper'
require 'models/topic'
@@ -51,6 +50,20 @@ class AcceptanceValidationTest < ActiveModel::TestCase
assert t.valid?
end
+ def test_terms_of_service_agreement_with_multiple_accept_values
+ Topic.validates_acceptance_of(:terms_of_service, accept: [1, "I concur."])
+
+ t = Topic.new("title" => "We should be confirmed", "terms_of_service" => "")
+ assert t.invalid?
+ assert_equal ["must be accepted"], t.errors[:terms_of_service]
+
+ t.terms_of_service = 1
+ assert t.valid?
+
+ t.terms_of_service = "I concur."
+ assert t.valid?
+ end
+
def test_validates_acceptance_of_for_ruby_class
Person.validates_acceptance_of :karma
@@ -65,4 +78,10 @@ class AcceptanceValidationTest < ActiveModel::TestCase
ensure
Person.clear_validators!
end
+
+ def test_validates_acceptance_of_true
+ Topic.validates_acceptance_of(:terms_of_service)
+
+ assert Topic.new(terms_of_service: true).valid?
+ end
end
diff --git a/activemodel/test/cases/validations/callbacks_test.rb b/activemodel/test/cases/validations/callbacks_test.rb
index 6cd0f4ed4d..75eb18e795 100644
--- a/activemodel/test/cases/validations/callbacks_test.rb
+++ b/activemodel/test/cases/validations/callbacks_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'cases/helper'
class Dog
@@ -30,16 +29,34 @@ class DogWithTwoValidators < Dog
before_validation { self.history << 'before_validation_marker2' }
end
-class DogValidatorReturningFalse < Dog
+class DogDeprecatedBeforeValidatorReturningFalse < Dog
before_validation { false }
before_validation { self.history << 'before_validation_marker2' }
end
+class DogBeforeValidatorThrowingAbort < Dog
+ before_validation { throw :abort }
+ before_validation { self.history << 'before_validation_marker2' }
+end
+
+class DogAfterValidatorReturningFalse < Dog
+ after_validation { false }
+ after_validation { self.history << 'after_validation_marker' }
+end
+
class DogWithMissingName < Dog
before_validation { self.history << 'before_validation_marker' }
validates_presence_of :name
end
+class DogValidatorWithOnCondition < Dog
+ before_validation :set_before_validation_marker, on: :create
+ after_validation :set_after_validation_marker, on: :create
+
+ def set_before_validation_marker; self.history << 'before_validation_marker'; end
+ def set_after_validation_marker; self.history << 'after_validation_marker' ; end
+end
+
class DogValidatorWithIfCondition < Dog
before_validation :set_before_validation_marker1, if: -> { true }
before_validation :set_before_validation_marker2, if: -> { false }
@@ -63,6 +80,24 @@ class CallbacksWithMethodNamesShouldBeCalled < ActiveModel::TestCase
assert_equal ["before_validation_marker1", "after_validation_marker1"], d.history
end
+ def test_on_condition_is_respected_for_validation_with_matching_context
+ d = DogValidatorWithOnCondition.new
+ d.valid?(:create)
+ assert_equal ["before_validation_marker", "after_validation_marker"], d.history
+ end
+
+ def test_on_condition_is_respected_for_validation_without_matching_context
+ d = DogValidatorWithOnCondition.new
+ d.valid?(:save)
+ assert_equal [], d.history
+ end
+
+ def test_on_condition_is_respected_for_validation_without_context
+ d = DogValidatorWithOnCondition.new
+ d.valid?
+ assert_equal [], d.history
+ end
+
def test_before_validation_and_after_validation_callbacks_should_be_called
d = DogWithMethodCallbacks.new
d.valid?
@@ -81,13 +116,28 @@ class CallbacksWithMethodNamesShouldBeCalled < ActiveModel::TestCase
assert_equal ['before_validation_marker1', 'before_validation_marker2'], d.history
end
- def test_further_callbacks_should_not_be_called_if_before_validation_returns_false
- d = DogValidatorReturningFalse.new
+ def test_further_callbacks_should_not_be_called_if_before_validation_throws_abort
+ d = DogBeforeValidatorThrowingAbort.new
output = d.valid?
assert_equal [], d.history
assert_equal false, output
end
+ def test_deprecated_further_callbacks_should_not_be_called_if_before_validation_returns_false
+ d = DogDeprecatedBeforeValidatorReturningFalse.new
+ assert_deprecated do
+ output = d.valid?
+ assert_equal [], d.history
+ assert_equal false, output
+ end
+ end
+
+ def test_further_callbacks_should_be_called_if_after_validation_returns_false
+ d = DogAfterValidatorReturningFalse.new
+ d.valid?
+ assert_equal ['after_validation_marker'], d.history
+ end
+
def test_validation_test_should_be_done
d = DogWithMissingName.new
output = d.valid?
diff --git a/activemodel/test/cases/validations/conditional_validation_test.rb b/activemodel/test/cases/validations/conditional_validation_test.rb
index 1261937b56..296d3b4407 100644
--- a/activemodel/test/cases/validations/conditional_validation_test.rb
+++ b/activemodel/test/cases/validations/conditional_validation_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'cases/helper'
require 'models/topic'
diff --git a/activemodel/test/cases/validations/confirmation_validation_test.rb b/activemodel/test/cases/validations/confirmation_validation_test.rb
index 65a2a1eb49..c1431548f7 100644
--- a/activemodel/test/cases/validations/confirmation_validation_test.rb
+++ b/activemodel/test/cases/validations/confirmation_validation_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'cases/helper'
require 'models/topic'
diff --git a/activemodel/test/cases/validations/exclusion_validation_test.rb b/activemodel/test/cases/validations/exclusion_validation_test.rb
index 1ce41f9bc9..005bc15df5 100644
--- a/activemodel/test/cases/validations/exclusion_validation_test.rb
+++ b/activemodel/test/cases/validations/exclusion_validation_test.rb
@@ -1,5 +1,5 @@
-# encoding: utf-8
require 'cases/helper'
+require 'active_support/core_ext/numeric/time'
require 'models/topic'
require 'models/person'
@@ -65,6 +65,22 @@ class ExclusionValidationTest < ActiveModel::TestCase
assert t.valid?
end
+ def test_validates_exclusion_of_with_range
+ Topic.validates_exclusion_of :content, in: ("a".."g")
+
+ assert Topic.new(content: 'g').invalid?
+ assert Topic.new(content: 'h').valid?
+ end
+
+ def test_validates_exclusion_of_with_time_range
+ Topic.validates_exclusion_of :created_at, in: 6.days.ago..2.days.ago
+
+ assert Topic.new(created_at: 5.days.ago).invalid?
+ assert Topic.new(created_at: 3.days.ago).invalid?
+ assert Topic.new(created_at: 7.days.ago).valid?
+ assert Topic.new(created_at: 1.day.ago).valid?
+ end
+
def test_validates_inclusion_of_with_symbol
Person.validates_exclusion_of :karma, in: :reserved_karmas
diff --git a/activemodel/test/cases/validations/format_validation_test.rb b/activemodel/test/cases/validations/format_validation_test.rb
index 0f91b73cd7..86bbbe6ebe 100644
--- a/activemodel/test/cases/validations/format_validation_test.rb
+++ b/activemodel/test/cases/validations/format_validation_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'cases/helper'
require 'models/topic'
diff --git a/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb b/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb
index 3eeb80a48b..da63df9152 100644
--- a/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb
+++ b/activemodel/test/cases/validations/i18n_generate_message_validation_test.rb
@@ -62,7 +62,7 @@ class I18nGenerateMessageValidationTest < ActiveModel::TestCase
assert_equal 'custom message', @person.errors.generate_message(:title, :empty, message: 'custom message')
end
- # add_on_blank: generate_message(attr, :blank, message: custom_message)
+ # validates_presence_of: generate_message(attr, :blank, message: custom_message)
def test_generate_message_blank_with_default_message
assert_equal "can't be blank", @person.errors.generate_message(:title, :blank)
end
diff --git a/activemodel/test/cases/validations/i18n_validation_test.rb b/activemodel/test/cases/validations/i18n_validation_test.rb
index 96084a32ba..09d7226b5a 100644
--- a/activemodel/test/cases/validations/i18n_validation_test.rb
+++ b/activemodel/test/cases/validations/i18n_validation_test.rb
@@ -1,5 +1,3 @@
-# -*- coding: utf-8 -*-
-
require "cases/helper"
require 'models/person'
@@ -32,8 +30,9 @@ class I18nValidationTest < ActiveModel::TestCase
def test_errors_full_messages_translates_human_attribute_name_for_model_attributes
@person.errors.add(:name, 'not found')
- Person.expects(:human_attribute_name).with(:name, default: 'Name').returns("Person's name")
- assert_equal ["Person's name not found"], @person.errors.full_messages
+ assert_called_with(Person, :human_attribute_name, [:name, default: 'Name'], returns: "Person's name") do
+ assert_equal ["Person's name not found"], @person.errors.full_messages
+ end
end
def test_errors_full_messages_uses_format
@@ -56,176 +55,175 @@ class I18nValidationTest < ActiveModel::TestCase
[ "given option that is not reserved", { format: "jpg" }, { format: "jpg" }]
]
- # validates_confirmation_of w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_confirmation_of on generated message #{name}" do
Person.validates_confirmation_of :title, validation_options
@person.title_confirmation = 'foo'
- @person.errors.expects(:generate_message).with(:title_confirmation, :confirmation, generate_message_options.merge(attribute: 'Title'))
- @person.valid?
+ call = [:title_confirmation, :confirmation, generate_message_options.merge(attribute: 'Title')]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_acceptance_of w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_acceptance_of on generated message #{name}" do
Person.validates_acceptance_of :title, validation_options.merge(allow_nil: false)
- @person.errors.expects(:generate_message).with(:title, :accepted, generate_message_options)
- @person.valid?
+ call = [:title, :accepted, generate_message_options]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_presence_of w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_presence_of on generated message #{name}" do
Person.validates_presence_of :title, validation_options
- @person.errors.expects(:generate_message).with(:title, :blank, generate_message_options)
- @person.valid?
+ call = [:title, :blank, generate_message_options]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_length_of :within too short w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
- test "validates_length_of for :withing on generated message when too short #{name}" do
+ test "validates_length_of for :within on generated message when too short #{name}" do
Person.validates_length_of :title, validation_options.merge(within: 3..5)
- @person.errors.expects(:generate_message).with(:title, :too_short, generate_message_options.merge(count: 3))
- @person.valid?
+ call = [:title, :too_short, generate_message_options.merge(count: 3)]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_length_of :within too long w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_length_of for :too_long generated message #{name}" do
Person.validates_length_of :title, validation_options.merge(within: 3..5)
@person.title = 'this title is too long'
- @person.errors.expects(:generate_message).with(:title, :too_long, generate_message_options.merge(count: 5))
- @person.valid?
+ call = [:title, :too_long, generate_message_options.merge(count: 5)]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_length_of :is w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_length_of for :is on generated message #{name}" do
Person.validates_length_of :title, validation_options.merge(is: 5)
- @person.errors.expects(:generate_message).with(:title, :wrong_length, generate_message_options.merge(count: 5))
- @person.valid?
+ call = [:title, :wrong_length, generate_message_options.merge(count: 5)]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_format_of w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_format_of on generated message #{name}" do
Person.validates_format_of :title, validation_options.merge(with: /\A[1-9][0-9]*\z/)
@person.title = '72x'
- @person.errors.expects(:generate_message).with(:title, :invalid, generate_message_options.merge(value: '72x'))
- @person.valid?
+ call = [:title, :invalid, generate_message_options.merge(value: '72x')]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_inclusion_of w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_inclusion_of on generated message #{name}" do
Person.validates_inclusion_of :title, validation_options.merge(in: %w(a b c))
@person.title = 'z'
- @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(value: 'z'))
- @person.valid?
+ call = [:title, :inclusion, generate_message_options.merge(value: 'z')]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_inclusion_of using :within w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_inclusion_of using :within on generated message #{name}" do
Person.validates_inclusion_of :title, validation_options.merge(within: %w(a b c))
@person.title = 'z'
- @person.errors.expects(:generate_message).with(:title, :inclusion, generate_message_options.merge(value: 'z'))
- @person.valid?
+ call = [:title, :inclusion, generate_message_options.merge(value: 'z')]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_exclusion_of w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_exclusion_of generated message #{name}" do
Person.validates_exclusion_of :title, validation_options.merge(in: %w(a b c))
@person.title = 'a'
- @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(value: 'a'))
- @person.valid?
+ call = [:title, :exclusion, generate_message_options.merge(value: 'a')]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_exclusion_of using :within w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_exclusion_of using :within generated message #{name}" do
Person.validates_exclusion_of :title, validation_options.merge(within: %w(a b c))
@person.title = 'a'
- @person.errors.expects(:generate_message).with(:title, :exclusion, generate_message_options.merge(value: 'a'))
- @person.valid?
+ call = [:title, :exclusion, generate_message_options.merge(value: 'a')]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_numericality_of without :only_integer w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_numericality_of generated message #{name}" do
Person.validates_numericality_of :title, validation_options
@person.title = 'a'
- @person.errors.expects(:generate_message).with(:title, :not_a_number, generate_message_options.merge(value: 'a'))
- @person.valid?
+ call = [:title, :not_a_number, generate_message_options.merge(value: 'a')]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_numericality_of with :only_integer w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_numericality_of for :only_integer on generated message #{name}" do
Person.validates_numericality_of :title, validation_options.merge(only_integer: true)
@person.title = '0.0'
- @person.errors.expects(:generate_message).with(:title, :not_an_integer, generate_message_options.merge(value: '0.0'))
- @person.valid?
+ call = [:title, :not_an_integer, generate_message_options.merge(value: '0.0')]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_numericality_of :odd w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_numericality_of for :odd on generated message #{name}" do
Person.validates_numericality_of :title, validation_options.merge(only_integer: true, odd: true)
@person.title = 0
- @person.errors.expects(:generate_message).with(:title, :odd, generate_message_options.merge(value: 0))
- @person.valid?
+ call = [:title, :odd, generate_message_options.merge(value: 0)]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
- # validates_numericality_of :less_than w/ mocha
-
COMMON_CASES.each do |name, validation_options, generate_message_options|
test "validates_numericality_of for :less_than on generated message #{name}" do
Person.validates_numericality_of :title, validation_options.merge(only_integer: true, less_than: 0)
@person.title = 1
- @person.errors.expects(:generate_message).with(:title, :less_than, generate_message_options.merge(value: 1, count: 0))
- @person.valid?
+ call = [:title, :less_than, generate_message_options.merge(value: 1, count: 0)]
+ assert_called_with(@person.errors, :generate_message, call) do
+ @person.valid?
+ end
end
end
-
- # To make things DRY this macro is defined to define 3 tests for every validation case.
+ # To make things DRY this macro is created to define 3 tests for every validation case.
def self.set_expectations_for_validation(validation, error_type, &block_that_sets_validation)
if error_type == :confirmation
attribute = :title_confirmation
else
attribute = :title
end
- # test "validates_confirmation_of finds custom model key translation when blank"
+
test "#{validation} finds custom model key translation when #{error_type}" do
I18n.backend.store_translations 'en', activemodel: { errors: { models: { person: { attributes: { attribute => { error_type => 'custom message' } } } } } }
I18n.backend.store_translations 'en', errors: { messages: { error_type => 'global message'}}
@@ -235,7 +233,6 @@ class I18nValidationTest < ActiveModel::TestCase
assert_equal ['custom message'], @person.errors[attribute]
end
- # test "validates_confirmation_of finds custom model key translation with interpolation when blank"
test "#{validation} finds custom model key translation with interpolation when #{error_type}" do
I18n.backend.store_translations 'en', activemodel: { errors: { models: { person: { attributes: { attribute => { error_type => 'custom message with %{extra}' } } } } } }
I18n.backend.store_translations 'en', errors: { messages: {error_type => 'global message'} }
@@ -245,7 +242,6 @@ class I18nValidationTest < ActiveModel::TestCase
assert_equal ['custom message with extra information'], @person.errors[attribute]
end
- # test "validates_confirmation_of finds global default key translation when blank"
test "#{validation} finds global default key translation when #{error_type}" do
I18n.backend.store_translations 'en', errors: { messages: {error_type => 'global message'} }
@@ -255,27 +251,19 @@ class I18nValidationTest < ActiveModel::TestCase
end
end
- # validates_confirmation_of w/o mocha
-
set_expectations_for_validation "validates_confirmation_of", :confirmation do |person, options_to_merge|
Person.validates_confirmation_of :title, options_to_merge
person.title_confirmation = 'foo'
end
- # validates_acceptance_of w/o mocha
-
set_expectations_for_validation "validates_acceptance_of", :accepted do |person, options_to_merge|
Person.validates_acceptance_of :title, options_to_merge.merge(allow_nil: false)
end
- # validates_presence_of w/o mocha
-
set_expectations_for_validation "validates_presence_of", :blank do |person, options_to_merge|
Person.validates_presence_of :title, options_to_merge
end
- # validates_length_of :within w/o mocha
-
set_expectations_for_validation "validates_length_of", :too_short do |person, options_to_merge|
Person.validates_length_of :title, options_to_merge.merge(within: 3..5)
end
@@ -285,61 +273,43 @@ class I18nValidationTest < ActiveModel::TestCase
person.title = "too long"
end
- # validates_length_of :is w/o mocha
-
set_expectations_for_validation "validates_length_of", :wrong_length do |person, options_to_merge|
Person.validates_length_of :title, options_to_merge.merge(is: 5)
end
- # validates_format_of w/o mocha
-
set_expectations_for_validation "validates_format_of", :invalid do |person, options_to_merge|
Person.validates_format_of :title, options_to_merge.merge(with: /\A[1-9][0-9]*\z/)
end
- # validates_inclusion_of w/o mocha
-
set_expectations_for_validation "validates_inclusion_of", :inclusion do |person, options_to_merge|
Person.validates_inclusion_of :title, options_to_merge.merge(in: %w(a b c))
end
- # validates_exclusion_of w/o mocha
-
set_expectations_for_validation "validates_exclusion_of", :exclusion do |person, options_to_merge|
Person.validates_exclusion_of :title, options_to_merge.merge(in: %w(a b c))
person.title = 'a'
end
- # validates_numericality_of without :only_integer w/o mocha
-
set_expectations_for_validation "validates_numericality_of", :not_a_number do |person, options_to_merge|
Person.validates_numericality_of :title, options_to_merge
person.title = 'a'
end
- # validates_numericality_of with :only_integer w/o mocha
-
set_expectations_for_validation "validates_numericality_of", :not_an_integer do |person, options_to_merge|
Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true)
person.title = '1.0'
end
- # validates_numericality_of :odd w/o mocha
-
set_expectations_for_validation "validates_numericality_of", :odd do |person, options_to_merge|
Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true, odd: true)
person.title = 0
end
- # validates_numericality_of :less_than w/o mocha
-
set_expectations_for_validation "validates_numericality_of", :less_than do |person, options_to_merge|
Person.validates_numericality_of :title, options_to_merge.merge(only_integer: true, less_than: 0)
person.title = 1
end
- # test with validates_with
-
def test_validations_with_message_symbol_must_translate
I18n.backend.store_translations 'en', errors: { messages: { custom_error: "I am a custom error" } }
Person.validates_presence_of :title, message: :custom_error
diff --git a/activemodel/test/cases/validations/inclusion_validation_test.rb b/activemodel/test/cases/validations/inclusion_validation_test.rb
index 3a8f3080e1..55d1fb4dcb 100644
--- a/activemodel/test/cases/validations/inclusion_validation_test.rb
+++ b/activemodel/test/cases/validations/inclusion_validation_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'cases/helper'
require 'active_support/all'
diff --git a/activemodel/test/cases/validations/length_validation_test.rb b/activemodel/test/cases/validations/length_validation_test.rb
index 046ffcb16f..ee901b75fb 100644
--- a/activemodel/test/cases/validations/length_validation_test.rb
+++ b/activemodel/test/cases/validations/length_validation_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'cases/helper'
require 'models/topic'
@@ -320,8 +319,33 @@ class LengthValidationTest < ActiveModel::TestCase
end
def test_validates_length_of_with_block
- Topic.validates_length_of :content, minimum: 5, too_short: "Your essay must be at least %{count} words.",
- tokenizer: lambda {|str| str.scan(/\w+/) }
+ assert_deprecated do
+ Topic.validates_length_of(
+ :content,
+ minimum: 5,
+ too_short: "Your essay must be at least %{count} words.",
+ tokenizer: lambda {|str| str.scan(/\w+/) },
+ )
+ end
+ t = Topic.new(content: "this content should be long enough")
+ assert t.valid?
+
+ t.content = "not long enough"
+ assert t.invalid?
+ assert t.errors[:content].any?
+ assert_equal ["Your essay must be at least 5 words."], t.errors[:content]
+ end
+
+
+ def test_validates_length_of_with_symbol
+ assert_deprecated do
+ Topic.validates_length_of(
+ :content,
+ minimum: 5,
+ too_short: "Your essay must be at least %{count} words.",
+ tokenizer: :my_word_tokenizer,
+ )
+ end
t = Topic.new(content: "this content should be long enough")
assert t.valid?
diff --git a/activemodel/test/cases/validations/numericality_validation_test.rb b/activemodel/test/cases/validations/numericality_validation_test.rb
index 3834d327ea..05432abaff 100644
--- a/activemodel/test/cases/validations/numericality_validation_test.rb
+++ b/activemodel/test/cases/validations/numericality_validation_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'cases/helper'
require 'models/topic'
@@ -59,7 +58,7 @@ class NumericalityValidationTest < ActiveModel::TestCase
def test_validates_numericality_of_with_integer_only_and_proc_as_value
Topic.send(:define_method, :allow_only_integers?, lambda { false })
- Topic.validates_numericality_of :approved, only_integer: Proc.new {|topic| topic.allow_only_integers? }
+ Topic.validates_numericality_of :approved, only_integer: Proc.new(&:allow_only_integers?)
invalid!(NIL + BLANK + JUNK)
valid!(FLOATS + INTEGERS + BIGDECIMAL + INFINITY)
@@ -130,7 +129,7 @@ class NumericalityValidationTest < ActiveModel::TestCase
def test_validates_numericality_with_proc
Topic.send(:define_method, :min_approved, lambda { 5 })
- Topic.validates_numericality_of :approved, greater_than_or_equal_to: Proc.new {|topic| topic.min_approved }
+ Topic.validates_numericality_of :approved, greater_than_or_equal_to: Proc.new(&:min_approved)
invalid!([3, 4])
valid!([5, 6])
diff --git a/activemodel/test/cases/validations/presence_validation_test.rb b/activemodel/test/cases/validations/presence_validation_test.rb
index ecf16d1e16..59b9db0795 100644
--- a/activemodel/test/cases/validations/presence_validation_test.rb
+++ b/activemodel/test/cases/validations/presence_validation_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'cases/helper'
require 'models/topic'
diff --git a/activemodel/test/cases/validations/validates_test.rb b/activemodel/test/cases/validations/validates_test.rb
index 699a872e42..04101f3545 100644
--- a/activemodel/test/cases/validations/validates_test.rb
+++ b/activemodel/test/cases/validations/validates_test.rb
@@ -1,9 +1,7 @@
-# encoding: utf-8
require 'cases/helper'
require 'models/person'
require 'models/topic'
require 'models/person_with_validator'
-require 'validators/email_validator'
require 'validators/namespace/email_validator'
class ValidatesTest < ActiveModel::TestCase
diff --git a/activemodel/test/cases/validations/validations_context_test.rb b/activemodel/test/cases/validations/validations_context_test.rb
index 005bf118c6..150dce379f 100644
--- a/activemodel/test/cases/validations/validations_context_test.rb
+++ b/activemodel/test/cases/validations/validations_context_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'cases/helper'
require 'models/topic'
diff --git a/activemodel/test/cases/validations/with_validation_test.rb b/activemodel/test/cases/validations/with_validation_test.rb
index 736c2deea8..03c7943308 100644
--- a/activemodel/test/cases/validations/with_validation_test.rb
+++ b/activemodel/test/cases/validations/with_validation_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'cases/helper'
require 'models/topic'
@@ -98,12 +97,14 @@ class ValidatesWithTest < ActiveModel::TestCase
test "passes all configuration options to the validator class" do
topic = Topic.new
- validator = mock()
- validator.expects(:new).with(foo: :bar, if: "1 == 1", class: Topic).returns(validator)
- validator.expects(:validate).with(topic)
+ validator = Minitest::Mock.new
+ validator.expect(:new, validator, [{foo: :bar, if: "1 == 1", class: Topic}])
+ validator.expect(:validate, nil, [topic])
+ validator.expect(:is_a?, false, [Symbol])
Topic.validates_with(validator, if: "1 == 1", foo: :bar)
assert topic.valid?
+ validator.verify
end
test "validates_with with options" do
diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb
index de71bb6f42..f0317ad219 100644
--- a/activemodel/test/cases/validations_test.rb
+++ b/activemodel/test/cases/validations_test.rb
@@ -1,4 +1,3 @@
-# encoding: utf-8
require 'cases/helper'
require 'models/topic'
@@ -171,10 +170,45 @@ class ValidationsTest < ActiveModel::TestCase
# A common mistake -- we meant to call 'validates'
Topic.validate :title, presence: true
end
- message = 'Unknown key: :presence. Valid keys are: :on, :if, :unless. Perhaps you meant to call `validates` instead of `validate`?'
+ message = 'Unknown key: :presence. Valid keys are: :on, :if, :unless, :prepend. Perhaps you meant to call `validates` instead of `validate`?'
assert_equal message, error.message
end
+ def test_callback_options_to_validate
+ klass = Class.new(Topic) do
+ attr_reader :call_sequence
+
+ def initialize(*)
+ super
+ @call_sequence = []
+ end
+
+ private
+ def validator_a
+ @call_sequence << :a
+ end
+
+ def validator_b
+ @call_sequence << :b
+ end
+
+ def validator_c
+ @call_sequence << :c
+ end
+ end
+
+ assert_nothing_raised do
+ klass.validate :validator_a, if: ->{ true }
+ klass.validate :validator_b, prepend: true
+ klass.validate :validator_c, unless: ->{ true }
+ end
+
+ t = klass.new
+
+ assert_predicate t, :valid?
+ assert_equal [:b, :a], t.call_sequence
+ end
+
def test_errors_conversions
Topic.validates_presence_of %w(title content)
t = Topic.new
@@ -282,7 +316,7 @@ class ValidationsTest < ActiveModel::TestCase
ActiveModel::Validations::FormatValidator,
ActiveModel::Validations::LengthValidator,
ActiveModel::Validations::PresenceValidator
- ], validators.map { |v| v.class }.sort_by { |c| c.to_s }
+ ], validators.map(&:class).sort_by(&:to_s)
end
def test_list_of_validators_will_be_empty_when_empty
@@ -317,6 +351,25 @@ class ValidationsTest < ActiveModel::TestCase
assert_not_empty topic.errors
end
+ def test_validate_with_bang
+ Topic.validates :title, presence: true
+
+ assert_raise(ActiveModel::ValidationError) do
+ Topic.new.validate!
+ end
+ end
+
+ def test_validate_with_bang_and_context
+ Topic.validates :title, presence: true, on: :context
+
+ assert_raise(ActiveModel::ValidationError) do
+ Topic.new.validate!(:context)
+ end
+
+ t = Topic.new(title: "Valid title")
+ assert t.validate!(:context)
+ end
+
def test_strict_validation_in_validates
Topic.validates :title, strict: true, presence: true
assert_raises ActiveModel::StrictValidationFailed do
diff --git a/activemodel/test/models/contact.rb b/activemodel/test/models/contact.rb
index bcfd267a34..113ab0bc1f 100644
--- a/activemodel/test/models/contact.rb
+++ b/activemodel/test/models/contact.rb
@@ -4,7 +4,6 @@ class Contact
include ActiveModel::Validations
include ActiveModel::Serializers::JSON
- include ActiveModel::Serializers::Xml
attr_accessor :id, :name, :age, :created_at, :awesome, :preferences
attr_accessor :address, :friends, :contact
diff --git a/activemodel/test/models/topic.rb b/activemodel/test/models/topic.rb
index 1411a093e9..fed50bc361 100644
--- a/activemodel/test/models/topic.rb
+++ b/activemodel/test/models/topic.rb
@@ -37,4 +37,8 @@ class Topic
errors.add attr, "is missing" unless send(attr)
end
+ def my_word_tokenizer(str)
+ str.scan(/\w+/)
+ end
+
end