aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--actionview/lib/action_view/helpers/form_tag_helper.rb2
-rw-r--r--actionview/lib/action_view/template.rb2
-rw-r--r--activejob/lib/active_job/arguments.rb6
-rw-r--r--activejob/lib/active_job/base.rb43
-rw-r--r--activejob/lib/active_job/logging.rb2
-rw-r--r--activejob/lib/active_job/queue_adapter.rb7
-rw-r--r--activejob/lib/active_job/queue_adapters.rb6
-rw-r--r--activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb8
-rw-r--r--activejob/lib/active_job/queue_name.rb9
-rw-r--r--activemodel/lib/active_model/callbacks.rb3
-rw-r--r--activemodel/lib/active_model/validations.rb10
-rw-r--r--activemodel/lib/active_model/validations/numericality.rb2
-rw-r--r--activemodel/lib/active_model/validations/validates.rb8
-rw-r--r--activemodel/lib/active_model/validations/with.rb7
-rw-r--r--activerecord/CHANGELOG.md2
-rw-r--r--activerecord/lib/active_record/associations/collection_proxy.rb31
-rw-r--r--activerecord/lib/active_record/validations/associated.rb8
-rw-r--r--activerecord/lib/active_record/validations/presence.rb8
-rw-r--r--activesupport/CHANGELOG.md4
-rw-r--r--activesupport/lib/active_support/callbacks.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/module/aliasing.rb4
-rw-r--r--activesupport/lib/active_support/duration.rb4
-rw-r--r--activesupport/lib/active_support/inflector/methods.rb2
-rw-r--r--activesupport/test/core_ext/duration_test.rb4
-rw-r--r--activesupport/test/inflector_test.rb3
-rw-r--r--guides/source/4_2_release_notes.md4
-rw-r--r--guides/source/active_model_basics.md369
-rw-r--r--guides/source/active_record_validations.md10
-rw-r--r--guides/source/configuring.md30
-rw-r--r--guides/source/documents.yaml5
-rw-r--r--guides/source/testing.md1
31 files changed, 519 insertions, 88 deletions
diff --git a/actionview/lib/action_view/helpers/form_tag_helper.rb b/actionview/lib/action_view/helpers/form_tag_helper.rb
index 7d1cdc5a68..ff5d278b85 100644
--- a/actionview/lib/action_view/helpers/form_tag_helper.rb
+++ b/actionview/lib/action_view/helpers/form_tag_helper.rb
@@ -862,7 +862,7 @@ module ActionView
# see http://www.w3.org/TR/html4/types.html#type-name
def sanitize_to_id(name)
- name.to_s.delete(']').gsub(/[^-a-zA-Z0-9:.]/, "_")
+ name.to_s.delete(']').tr('^-a-zA-Z0-9:.', "_")
end
end
end
diff --git a/actionview/lib/action_view/template.rb b/actionview/lib/action_view/template.rb
index f398f9bfa3..379f31bdaf 100644
--- a/actionview/lib/action_view/template.rb
+++ b/actionview/lib/action_view/template.rb
@@ -321,7 +321,7 @@ module ActionView
end
def identifier_method_name #:nodoc:
- inspect.gsub(/[^a-z_]/, '_')
+ inspect.tr('^a-z_', '_')
end
def instrument(action, &block)
diff --git a/activejob/lib/active_job/arguments.rb b/activejob/lib/active_job/arguments.rb
index 86b85ebdba..e2c076eb3f 100644
--- a/activejob/lib/active_job/arguments.rb
+++ b/activejob/lib/active_job/arguments.rb
@@ -24,10 +24,16 @@ module ActiveJob
extend self
TYPE_WHITELIST = [ NilClass, Fixnum, Float, String, TrueClass, FalseClass, Bignum ]
+ # Serializes a set of arguments. Whitelisted types are returned
+ # as-is. Arrays/Hashes are serialized element by element.
+ # All other types are serialized using GlobalID.
def serialize(arguments)
arguments.map { |argument| serialize_argument(argument) }
end
+ # Deserializes a set of arguments. Whitelisted types are returned
+ # as-is. Arrays/Hashes are deserialized element by element.
+ # All other types are deserialized using GlobalID.
def deserialize(arguments)
arguments.map { |argument| deserialize_argument(argument) }
rescue => e
diff --git a/activejob/lib/active_job/base.rb b/activejob/lib/active_job/base.rb
index a3bec1f827..8f4b37222a 100644
--- a/activejob/lib/active_job/base.rb
+++ b/activejob/lib/active_job/base.rb
@@ -6,7 +6,48 @@ require 'active_job/execution'
require 'active_job/callbacks'
require 'active_job/logging'
-module ActiveJob
+module ActiveJob #:nodoc:
+ # = Active Job
+ #
+ # Active job objects can be configured to work with different backend
+ # queuing frameworks. To specify a queue adapter to use:
+ #
+ # ActiveJob::Base.queue_adapter = :inline
+ #
+ # A list of supported adapters can be found in QueueAdapters.
+ #
+ # Active job objects can be defined by creating a class that inherits
+ # from the ActiveJob::Base class. The only necessary method to
+ # implement is the "perform" method.
+ #
+ # To define an Active Job object:
+ #
+ # class ProcessPhotoJob < ActiveJob::Base
+ # def perform(photo)
+ # photo.watermark!('Rails')
+ # photo.rotate!(90.degrees)
+ # photo.resize_to_fit!(300, 300)
+ # photo.upload!
+ # end
+ # end
+ #
+ # Records that are passed in are serialized/deserialized using Global
+ # Id. More information can be found in Arguments.
+ #
+ # To queue a job to be processed asynchronously immediately:
+ #
+ # ProcessPhotoJob.perform_later(photo)
+ #
+ # To queue a job to be processed at some point in the future:
+ #
+ # ProcessPhotoJob.set(wait_until: Date.tomorrow.noon).perform_later(photo)
+ #
+ # More information can be found in ActiveJob::Core::ClassMethods#set
+ #
+ # == Exceptions
+ #
+ # * DeserializationError - Error class for deserialization errors.
+ # * SerializationError - Error class for serialization errors.
class Base
include Core
include QueueAdapter
diff --git a/activejob/lib/active_job/logging.rb b/activejob/lib/active_job/logging.rb
index bb96668cfb..6e703faaa7 100644
--- a/activejob/lib/active_job/logging.rb
+++ b/activejob/lib/active_job/logging.rb
@@ -3,7 +3,7 @@ require 'active_support/tagged_logging'
require 'active_support/logger'
module ActiveJob
- module Logging
+ module Logging #:nodoc:
extend ActiveSupport::Concern
included do
diff --git a/activejob/lib/active_job/queue_adapter.rb b/activejob/lib/active_job/queue_adapter.rb
index fb54aec75e..4bd28522ab 100644
--- a/activejob/lib/active_job/queue_adapter.rb
+++ b/activejob/lib/active_job/queue_adapter.rb
@@ -2,12 +2,15 @@ require 'active_job/queue_adapters/inline_adapter'
require 'active_support/core_ext/string/inflections'
module ActiveJob
- module QueueAdapter
+ module QueueAdapter #:nodoc:
extend ActiveSupport::Concern
module ClassMethods
mattr_reader(:queue_adapter) { ActiveJob::QueueAdapters::InlineAdapter }
+ # Specify the backend queue provider. The default queue adapter
+ # is the :inline queue. See QueueAdapters for more
+ # information.
def queue_adapter=(name_or_adapter)
@@queue_adapter = \
case name_or_adapter
@@ -26,4 +29,4 @@ module ActiveJob
end
end
end
-end \ No newline at end of file
+end
diff --git a/activejob/lib/active_job/queue_adapters.rb b/activejob/lib/active_job/queue_adapters.rb
index e865c901ce..efbcd3cb3a 100644
--- a/activejob/lib/active_job/queue_adapters.rb
+++ b/activejob/lib/active_job/queue_adapters.rb
@@ -7,7 +7,7 @@ module ActiveJob
# * {Delayed Job}[https://github.com/collectiveidea/delayed_job]
# * {Qu}[https://github.com/bkeepers/qu]
# * {Que}[https://github.com/chanks/que]
- # * {QueueClassic 2.x}[https://github.com/ryandotsmith/queue_classic/tree/v2.2.3]
+ # * {queue_classic}[https://github.com/QueueClassic/queue_classic]
# * {Resque 1.x}[https://github.com/resque/resque/tree/1-x-stable]
# * {Sidekiq}[http://sidekiq.org]
# * {Sneakers}[https://github.com/jondot/sneakers]
@@ -20,7 +20,7 @@ module ActiveJob
# | Backburner | Yes | Yes | Yes | Yes | Job | Global |
# | Delayed Job | Yes | Yes | Yes | Job | Global | Global |
# | Que | Yes | Yes | Yes | Job | No | Job |
- # | Queue Classic | Yes | Yes | No* | No | No | No |
+ # | queue_classic | Yes | Yes | No* | No | No | No |
# | Resque | Yes | Yes | Yes (Gem) | Queue | Global | Yes |
# | Sidekiq | Yes | Yes | Yes | Queue | No | Job |
# | Sneakers | Yes | Yes | No | Queue | Queue | No |
@@ -29,7 +29,7 @@ module ActiveJob
# | Active Job | Yes | Yes | Yes | No | No | No |
#
# NOTE:
- # Queue Classic does not support Job scheduling. However you can implement this
+ # queue_classic does not support Job scheduling. However you can implement this
# yourself or you can use the queue_classic-later gem. See the documentation for
# ActiveJob::QueueAdapters::QueueClassicAdapter.
#
diff --git a/activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb b/activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb
index f160932578..1a46f20420 100644
--- a/activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb
+++ b/activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb
@@ -2,7 +2,7 @@ require 'queue_classic'
module ActiveJob
module QueueAdapters
- # == Queue Classic adapter for Active Job
+ # == queue_classic adapter for Active Job
#
# queue_classic provides a simple interface to a PostgreSQL-backed message
# queue. queue_classic specializes in concurrent locking and minimizing
@@ -11,9 +11,9 @@ module ActiveJob
# production environment and that adding another dependency (e.g. redis,
# beanstalkd, 0mq) is undesirable.
#
- # Read more about Queue Classic {here}[https://github.com/ryandotsmith/queue_classic].
+ # Read more about queue_classic {here}[https://github.com/QueueClassic/queue_classic].
#
- # To use Queue Classic set the queue_adapter config to +:queue_classic+.
+ # To use queue_classic set the queue_adapter config to +:queue_classic+.
#
# Rails.application.config.active_job.queue_adapter = :queue_classic
class QueueClassicAdapter
@@ -25,7 +25,7 @@ module ActiveJob
def enqueue_at(job, timestamp) #:nodoc:
queue = build_queue(job.queue_name)
unless queue.respond_to?(:enqueue_at)
- raise NotImplementedError, 'To be able to schedule jobs with Queue Classic ' \
+ raise NotImplementedError, 'To be able to schedule jobs with queue_classic ' \
'the QC::Queue needs to respond to `enqueue_at(timestamp, method, *args)`. '
'You can implement this yourself or you can use the queue_classic-later gem.'
end
diff --git a/activejob/lib/active_job/queue_name.rb b/activejob/lib/active_job/queue_name.rb
index 45acb71605..d6ac01a921 100644
--- a/activejob/lib/active_job/queue_name.rb
+++ b/activejob/lib/active_job/queue_name.rb
@@ -6,6 +6,15 @@ module ActiveJob
mattr_accessor(:queue_name_prefix)
mattr_accessor(:default_queue_name) { "default" }
+ # Specifies the name of the queue to process the job on.
+ #
+ # class PublishToFeedJob < ActiveJob::Base
+ # queue_as :feeds
+ #
+ # def perform(post)
+ # post.to_feed!
+ # end
+ # end
def queue_as(part_name=nil, &block)
if block_given?
self.queue_name = block
diff --git a/activemodel/lib/active_model/callbacks.rb b/activemodel/lib/active_model/callbacks.rb
index b27a39b787..b3d70dc515 100644
--- a/activemodel/lib/active_model/callbacks.rb
+++ b/activemodel/lib/active_model/callbacks.rb
@@ -97,6 +97,9 @@ module ActiveModel
# # obj is the MyModel instance that the callback is being called on
# end
# end
+ #
+ # NOTE: +method_name+ passed to `define_model_callbacks` must not end with
+ # `!`, `?` or `=`.
def define_model_callbacks(*callbacks)
options = callbacks.extract_options!
options = {
diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb
index 718fc78605..1116f6b8ee 100644
--- a/activemodel/lib/active_model/validations.rb
+++ b/activemodel/lib/active_model/validations.rb
@@ -68,8 +68,9 @@ module ActiveModel
#
# Options:
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
- # You can pass a symbol or an array of symbols.
- # (e.g. <tt>on: :create</tt> or <tt>on: :custom_validation_context</tt> or
+ # Runs in all validation contexts by default (nil). You can pass a symbol
+ # or an array of symbols. (e.g. <tt>on: :create</tt> or
+ # <tt>on: :custom_validation_context</tt> or
# <tt>on: [:create, :custom_validation_context]</tt>)
# * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+.
# * <tt>:allow_blank</tt> - Skip validation if attribute is blank.
@@ -130,8 +131,9 @@ module ActiveModel
#
# Options:
# * <tt>:on</tt> - Specifies the contexts where this validation is active.
- # You can pass a symbol or an array of symbols.
- # (e.g. <tt>on: :create</tt> or <tt>on: :custom_validation_context</tt> or
+ # Runs in all validation contexts by default (nil). You can pass a symbol
+ # or an array of symbols. (e.g. <tt>on: :create</tt> or
+ # <tt>on: :custom_validation_context</tt> or
# <tt>on: [:create, :custom_validation_context]</tt>)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb
index 5bd162433d..13d6a966c0 100644
--- a/activemodel/lib/active_model/validations/numericality.rb
+++ b/activemodel/lib/active_model/validations/numericality.rb
@@ -67,7 +67,7 @@ module ActiveModel
end
def parse_raw_value_as_an_integer(raw_value)
- raw_value.to_i if raw_value.to_s =~ /\A[+-]?\d+\Z/
+ raw_value.to_i if raw_value.to_s =~ /\A[+-]?\d+\z/
end
def filtered_options(value)
diff --git a/activemodel/lib/active_model/validations/validates.rb b/activemodel/lib/active_model/validations/validates.rb
index ae8d377fdf..bda436d8d0 100644
--- a/activemodel/lib/active_model/validations/validates.rb
+++ b/activemodel/lib/active_model/validations/validates.rb
@@ -71,9 +71,11 @@ module ActiveModel
#
# There is also a list of options that could be used along with validators:
#
- # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
- # validation contexts by default (+nil+), other options are <tt>:create</tt>
- # and <tt>:update</tt>.
+ # * <tt>:on</tt> - Specifies the contexts where this validation is active.
+ # Runs in all validation contexts by default (nil). You can pass a symbol
+ # or an array of symbols. (e.g. <tt>on: :create</tt> or
+ # <tt>on: :custom_validation_context</tt> or
+ # <tt>on: [:create, :custom_validation_context]</tt>)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
diff --git a/activemodel/lib/active_model/validations/with.rb b/activemodel/lib/active_model/validations/with.rb
index ff41572105..a2531327bf 100644
--- a/activemodel/lib/active_model/validations/with.rb
+++ b/activemodel/lib/active_model/validations/with.rb
@@ -52,8 +52,11 @@ module ActiveModel
# end
#
# Configuration options:
- # * <tt>:on</tt> - Specifies when this validation is active
- # (<tt>:create</tt> or <tt>:update</tt>).
+ # * <tt>:on</tt> - Specifies the contexts where this validation is active.
+ # Runs in all validation contexts by default (nil). You can pass a symbol
+ # or an array of symbols. (e.g. <tt>on: :create</tt> or
+ # <tt>on: :custom_validation_context</tt> or
+ # <tt>on: [:create, :custom_validation_context]</tt>)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>).
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index 210151a2ad..6bdb53ac5a 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -213,7 +213,7 @@
*Kenn Ejima*
-* Add support for Postgresql JSONB.
+* Add support for PostgreSQL JSONB.
Example:
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb
index 8c7b0b4be9..060b2278d9 100644
--- a/activerecord/lib/active_record/associations/collection_proxy.rb
+++ b/activerecord/lib/active_record/associations/collection_proxy.rb
@@ -355,14 +355,15 @@ module ActiveRecord
@association.replace(other_array)
end
- # Deletes all the records from the collection. For +has_many+ associations,
- # the deletion is done according to the strategy specified by the <tt>:dependent</tt>
- # option.
+ # Deletes all the records from the collection according to the strategy
+ # specified by the +:dependent+ option. If no +:dependent+ option is given,
+ # then it will follow the default strategy.
#
- # If no <tt>:dependent</tt> option is given, then it will follow the
- # default strategy. The default strategy is <tt>:nullify</tt>. This
- # sets the foreign keys to <tt>NULL</tt>. For, +has_many+ <tt>:through</tt>,
- # the default strategy is +delete_all+.
+ # For +has_many :through+ associations, the default deletion strategy is
+ # +:delete_all+.
+ #
+ # For +has_many+ associations, the default deletion strategy is +:nullify+.
+ # This sets the foreign keys to +NULL+.
#
# class Person < ActiveRecord::Base
# has_many :pets # dependent: :nullify option by default
@@ -393,9 +394,9 @@ module ActiveRecord
# # #<Pet id: 3, name: "Choo-Choo", person_id: nil>
# # ]
#
- # If it is set to <tt>:destroy</tt> all the objects from the collection
- # are removed by calling their +destroy+ method. See +destroy+ for more
- # information.
+ # Both +has_many+ and +has_many :through+ dependencies default to the
+ # +:delete_all+ strategy if the +:dependent+ option is set to +:destroy+.
+ # Records are not instantiated and callbacks will not be fired.
#
# class Person < ActiveRecord::Base
# has_many :pets, dependent: :destroy
@@ -410,11 +411,6 @@ module ActiveRecord
# # ]
#
# person.pets.delete_all
- # # => [
- # # #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
- # # #<Pet id: 2, name: "Spook", person_id: 1>,
- # # #<Pet id: 3, name: "Choo-Choo", person_id: 1>
- # # ]
#
# Pet.find(1, 2, 3)
# # => ActiveRecord::RecordNotFound
@@ -443,8 +439,9 @@ module ActiveRecord
end
# Deletes the records of the collection directly from the database
- # ignoring the +:dependent+ option. It invokes +before_remove+,
- # +after_remove+ , +before_destroy+ and +after_destroy+ callbacks.
+ # ignoring the +:dependent+ option. Records are instantiated and it
+ # invokes +before_remove+, +after_remove+ , +before_destroy+ and
+ # +after_destroy+ callbacks.
#
# class Person < ActiveRecord::Base
# has_many :pets
diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb
index b4785d3ba4..47ccef31a5 100644
--- a/activerecord/lib/active_record/validations/associated.rb
+++ b/activerecord/lib/active_record/validations/associated.rb
@@ -29,9 +29,11 @@ module ActiveRecord
# Configuration options:
#
# * <tt>:message</tt> - A custom error message (default is: "is invalid").
- # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
- # validation contexts by default (+nil+), other options are <tt>:create</tt>
- # and <tt>:update</tt>.
+ # * <tt>:on</tt> - Specifies the contexts where this validation is active.
+ # Runs in all validation contexts by default (nil). You can pass a symbol
+ # or an array of symbols. (e.g. <tt>on: :create</tt> or
+ # <tt>on: :custom_validation_context</tt> or
+ # <tt>on: [:create, :custom_validation_context]</tt>)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine
# if the validation should occur (e.g. <tt>if: :allow_validation</tt>,
# or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method,
diff --git a/activerecord/lib/active_record/validations/presence.rb b/activerecord/lib/active_record/validations/presence.rb
index e586744818..c7aa814ba8 100644
--- a/activerecord/lib/active_record/validations/presence.rb
+++ b/activerecord/lib/active_record/validations/presence.rb
@@ -44,9 +44,11 @@ module ActiveRecord
#
# Configuration options:
# * <tt>:message</tt> - A custom error message (default is: "can't be blank").
- # * <tt>:on</tt> - Specifies when this validation is active. Runs in all
- # validation contexts by default (+nil+), other options are <tt>:create</tt>
- # and <tt>:update</tt>.
+ # * <tt>:on</tt> - Specifies the contexts where this validation is active.
+ # Runs in all validation contexts by default (nil). You can pass a symbol
+ # or an array of symbols. (e.g. <tt>on: :create</tt> or
+ # <tt>on: :custom_validation_context</tt> or
+ # <tt>on: [:create, :custom_validation_context]</tt>)
# * <tt>:if</tt> - Specifies a method, proc or string to call to determine if
# the validation should occur (e.g. <tt>if: :allow_validation</tt>, or
# <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index a5fe6d65d9..74d57180fe 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,3 +1,7 @@
+* Corrected Inflector#underscore handling of multiple successive acroynms.
+
+ *James Le Cuirot*
+
* Delegation now works with ruby reserved words passed to `:to` option.
Fixes #16956.
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 0c8c1d7dfb..4bc13f20ca 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -719,6 +719,9 @@ module ActiveSupport
# define_callbacks :save, scope: [:name]
#
# would call <tt>Audit#save</tt>.
+ #
+ # NOTE: +method_name+ passed to `define_model_callbacks` must not end with
+ # `!`, `?` or `=`.
def define_callbacks(*names)
options = names.extract_options!
diff --git a/activesupport/lib/active_support/core_ext/module/aliasing.rb b/activesupport/lib/active_support/core_ext/module/aliasing.rb
index 580cb80413..0a6fadf928 100644
--- a/activesupport/lib/active_support/core_ext/module/aliasing.rb
+++ b/activesupport/lib/active_support/core_ext/module/aliasing.rb
@@ -19,9 +19,9 @@ class Module
# alias_method :foo_without_feature?, :foo?
# alias_method :foo?, :foo_with_feature?
#
- # so you can safely chain foo, foo?, and foo! with the same feature.
+ # so you can safely chain foo, foo?, foo! and/or foo= with the same feature.
def alias_method_chain(target, feature)
- # Strip out punctuation on predicates or bang methods since
+ # Strip out punctuation on predicates, bang or writer methods since
# e.g. target?_without_feature is not a valid method name.
aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
yield(aliased_target, punctuation) if block_given?
diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb
index e861a17426..584fc1e1c5 100644
--- a/activesupport/lib/active_support/duration.rb
+++ b/activesupport/lib/active_support/duration.rb
@@ -63,6 +63,10 @@ module ActiveSupport
Duration === other && other.value.eql?(value)
end
+ def hash
+ @value.hash
+ end
+
def self.===(other) #:nodoc:
other.is_a?(Duration)
rescue ::NoMethodError
diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb
index f35e71ce81..0e3c8517d1 100644
--- a/activesupport/lib/active_support/inflector/methods.rb
+++ b/activesupport/lib/active_support/inflector/methods.rb
@@ -91,7 +91,7 @@ module ActiveSupport
def underscore(camel_cased_word)
return camel_cased_word unless camel_cased_word =~ /[A-Z-]|::/
word = camel_cased_word.to_s.gsub('::', '/')
- word.gsub!(/(?:([A-Za-z\d])|\b)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1}#{$1 && '_'}#{$2.downcase}" }
+ word.gsub!(/(?:(?<=([A-Za-z\d]))|\b)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1 && '_'}#{$2.downcase}" }
word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2')
word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
word.tr!("-", "_")
diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb
index f4d504914e..5a2af7f943 100644
--- a/activesupport/test/core_ext/duration_test.rb
+++ b/activesupport/test/core_ext/duration_test.rb
@@ -196,4 +196,8 @@ class DurationTest < ActiveSupport::TestCase
assert_respond_to 1.day, :since
assert_respond_to 1.day, :zero?
end
+
+ def test_hash
+ assert_equal 1.minute.hash, 60.seconds.hash
+ end
end
diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb
index b37f31bc5f..5446c5ec3c 100644
--- a/activesupport/test/inflector_test.rb
+++ b/activesupport/test/inflector_test.rb
@@ -125,6 +125,9 @@ class InflectorTest < ActiveSupport::TestCase
["PhDRequired", "phd_required", "PhD required", "PhD Required"],
["IRoRU", "i_ror_u", "I RoR u", "I RoR U"],
["RESTfulHTTPAPI", "restful_http_api", "RESTful HTTP API", "RESTful HTTP API"],
+ ["HTTP::RESTful", "http/restful", "HTTP/RESTful", "HTTP/RESTful"],
+ ["HTTP::RESTfulAPI", "http/restful_api", "HTTP/RESTful API", "HTTP/RESTful API"],
+ ["APIRESTful", "api_restful", "API RESTful", "API RESTful"],
# misdirection
["Capistrano", "capistrano", "Capistrano", "Capistrano"],
diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md
index 2b8a6eb622..a598c7c319 100644
--- a/guides/source/4_2_release_notes.md
+++ b/guides/source/4_2_release_notes.md
@@ -79,7 +79,7 @@ post.comments(true) # uses cached pattern
The caching is not used in the following scenarios:
- The model has a default scope
-- The model uses single table inheritence to inherit from another model
+- The model uses single table inheritance to inherit from another model
- `find` with a list of ids. eg:
```ruby
@@ -753,7 +753,7 @@ Please refer to the [Changelog][active-support] for detailed changes.
* Introduced new configuration option `active_support.test_order` for
specifying the order test cases are executed. This option currently defaults
to `:sorted` but will be changed to `:random` in Rails 5.0.
- ([Commit](TODO: fill me in))
+ ([Commit](https://github.com/rails/rails/commit/53e877f7d9291b2bf0b8c425f9e32ef35829f35b))
* The `travel_to` test helper now truncates the `usec` component to 0.
([Commit](https://github.com/rails/rails/commit/9f6e82ee4783e491c20f5244a613fdeb4024beb5))
diff --git a/guides/source/active_model_basics.md b/guides/source/active_model_basics.md
index 3eaeeff389..a520b91a4d 100644
--- a/guides/source/active_model_basics.md
+++ b/guides/source/active_model_basics.md
@@ -1,20 +1,32 @@
Active Model Basics
===================
-This guide should provide you with all you need to get started using model classes. Active Model allows for Action Pack helpers to interact with non-Active Record models. Active Model also helps building custom ORMs for use outside of the Rails framework.
+This guide should provide you with all you need to get started using model
+classes. Active Model allows for Action Pack helpers to interact with
+plain Ruby objects. Active Model also helps build custom ORMs for use
+outside of the Rails framework.
-After reading this guide, you will know:
+After reading this guide, you will be able to add to plain Ruby objects:
+
+* The ability to behave like an Active Record model.
+* Callbacks and validations like Active Record.
+* Serializers.
+* Integration with the Rails internationalization (i18n) framework.
--------------------------------------------------------------------------------
Introduction
------------
-Active Model is a library containing various modules used in developing frameworks that need to interact with the Rails Action Pack library. Active Model provides a known set of interfaces for usage in classes. Some of modules are explained below.
+Active Model is a library containing various modules used in developing
+classes that need some features present on Active Record.
+Some of these modules are explained below.
-### AttributeMethods
+### Attribute Methods
-The AttributeMethods module can add custom prefixes and suffixes on methods of a class. It is used by defining the prefixes and suffixes and which methods on the object will use them.
+The `ActiveModel::AttributeMethods` module can add custom prefixes and suffixes
+on methods of a class. It is used by defining the prefixes and suffixes and
+which methods on the object will use them.
```ruby
class Person
@@ -38,14 +50,17 @@ end
person = Person.new
person.age = 110
-person.age_highest? # true
-person.reset_age # 0
-person.age_highest? # false
+person.age_highest? # => true
+person.reset_age # => 0
+person.age_highest? # => false
```
### Callbacks
-Callbacks gives Active Record style callbacks. This provides an ability to define callbacks which run at appropriate times. After defining callbacks, you can wrap them with before, after and around custom methods.
+`ActiveModel::Callbacks` gives Active Record style callbacks. This provides an
+ability to define callbacks which run at appropriate times.
+After defining callbacks, you can wrap them with before, after and around
+custom methods.
```ruby
class Person
@@ -69,7 +84,9 @@ end
### Conversion
-If a class defines `persisted?` and `id` methods, then you can include the `Conversion` module in that class and call the Rails conversion methods on objects of that class.
+If a class defines `persisted?` and `id` methods, then you can include the
+`ActiveModel::Conversion` module in that class and call the Rails conversion
+methods on objects of that class.
```ruby
class Person
@@ -92,11 +109,13 @@ person.to_param # => nil
### Dirty
-An object becomes dirty when it has gone through one or more changes to its attributes and has not been saved. This gives the ability to check whether an object has been changed or not. It also has attribute based accessor methods. Let's consider a Person class with attributes `first_name` and `last_name`:
+An object becomes dirty when it has gone through one or more changes to its
+attributes and has not been saved. `ActiveModel::Dirty` gives the ability to
+check whether an object has been changed or not. It also has attribute based
+accessor methods. Let's consider a Person class with attributes `first_name`
+and `last_name`:
```ruby
-require 'active_model'
-
class Person
include ActiveModel::Dirty
define_attribute_methods :first_name, :last_name
@@ -162,10 +181,11 @@ Track what was the previous value of the attribute.
```ruby
# attr_name_was accessor
-person.first_name_was # => "First Name"
+person.first_name_was # => nil
```
-Track both previous and current value of the changed attribute. Returns an array if changed, else returns nil.
+Track both previous and current value of the changed attribute. Returns an array
+if changed, else returns nil.
```ruby
# attr_name_change
@@ -175,7 +195,8 @@ person.last_name_change # => nil
### Validations
-Validations module adds the ability to class objects to validate them in Active Record style.
+`ActiveModel::Validations` module adds the ability to validate class objects
+like in Active Record.
```ruby
class Person
@@ -188,7 +209,8 @@ class Person
validates! :token, presence: true
end
-person = Person.new(token: "2b1f325")
+person = Person.new
+person.token = "2b1f325"
person.valid? # => false
person.name = 'vishnu'
person.email = 'me'
@@ -199,9 +221,9 @@ person.token = nil
person.valid? # => raises ActiveModel::StrictValidationFailed
```
-### ActiveModel::Naming
+### Naming
-Naming adds a number of class methods which make the naming and routing
+`ActiveModel::Naming` adds a number of class methods which make the naming and routing
easier to manage. The module defines the `model_name` class method which
will define a number of accessors using some `ActiveSupport::Inflector` methods.
@@ -221,3 +243,312 @@ Person.model_name.i18n_key # => :person
Person.model_name.route_key # => "people"
Person.model_name.singular_route_key # => "person"
```
+
+### Model
+
+`ActiveModel::Model` adds the ability to a class to work with Action Pack and
+Action View right out of the box.
+
+```ruby
+class EmailContact
+ include ActiveModel::Model
+
+ attr_accessor :name, :email, :message
+ validates :name, :email, :message, presence: true
+
+ def deliver
+ if valid?
+ # deliver email
+ end
+ end
+end
+```
+
+When including `ActiveModel::Model` you get some features like:
+
+- model name introspection
+- conversions
+- translations
+- validations
+
+It also gives you the ability to initialize an object with a hash of attributes,
+much like any Active Record object.
+
+```ruby
+email_contact = EmailContact.new(name: 'David',
+ email: 'david@example.com',
+ message: 'Hello World')
+email_contact.name # => 'David'
+email_contact.email # => 'david@example.com'
+email_contact.valid? # => true
+email_contact.persisted? # => false
+```
+
+Any class that includes `ActiveModel::Model` can be used with `form_for`,
+`render` and any other Action View helper methods, just like Active Record
+objects.
+
+### Serialization
+
+`ActiveModel::Serialization` provides a basic serialization for your object.
+You need to declare an attributes hash which contains the attributes you want to
+serialize. Attributes must be strings, not symbols.
+
+```ruby
+class Person
+ include ActiveModel::Serialization
+
+ attr_accessor :name
+
+ def attributes
+ {'name' => nil}
+ end
+end
+```
+
+Now you can access a serialized hash of your object using the `serializable_hash`.
+
+```ruby
+person = Person.new
+person.serializable_hash # => {"name"=>nil}
+person.name = "Bob"
+person.serializable_hash # => {"name"=>"Bob"}
+```
+
+#### ActiveModel::Serializers
+
+Rails provides two serializers `ActiveModel::Serializers::JSON` and
+`ActiveModel::Serializers::Xml`. Both of these modules automatically include
+the `ActiveModel::Serialization`.
+
+##### ActiveModel::Serializers::JSON
+
+To use the `ActiveModel::Serializers::JSON` you only need to change from
+`ActiveModel::Serialization` to `ActiveModel::Serializers::JSON`.
+
+```ruby
+class Person
+ include ActiveModel::Serializers::JSON
+
+ attr_accessor :name
+
+ def attributes
+ {'name' => nil}
+ end
+end
+```
+
+With the `as_json` you have a hash representing the model.
+
+```ruby
+person = Person.new
+person.as_json # => {"name"=>nil}
+person.name = "Bob"
+person.as_json # => {"name"=>"Bob"}
+```
+
+From a JSON string you define the attributes of the model.
+You need to have the `attributes=` method defined on your class:
+
+```ruby
+class Person
+ include ActiveModel::Serializers::JSON
+
+ attr_accessor :name
+
+ def attributes=(hash)
+ hash.each do |key, value|
+ send("#{key}=", value)
+ end
+ end
+
+ def attributes
+ {'name' => nil}
+ end
+end
+```
+
+Now it is possible to create an instance of person and set the attributes using `from_json`.
+
+```ruby
+json = { name: 'Bob' }.to_json
+person = Person.new
+person.from_json(json) # => #<Person:0x00000100c773f0 @name="Bob">
+person.name # => "Bob"
+```
+
+##### ActiveModel::Serializers::Xml
+
+To use the `ActiveModel::Serializers::Xml` you only need to change from
+`ActiveModel::Serialization` to `ActiveModel::Serializers::Xml`.
+
+```ruby
+class Person
+ include ActiveModel::Serializers::Xml
+
+ attr_accessor :name
+
+ def attributes
+ {'name' => nil}
+ end
+end
+```
+
+With the `to_xml` you have a XML representing the model.
+
+```ruby
+person = Person.new
+person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<person>\n <name nil=\"true\"/>\n</person>\n"
+person.name = "Bob"
+person.to_xml # => "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<person>\n <name>Bob</name>\n</person>\n"
+```
+
+From a XML string you define the attributes of the model.
+You need to have the `attributes=` method defined on your class:
+
+```ruby
+class Person
+ include ActiveModel::Serializers::Xml
+
+ attr_accessor :name
+
+ def attributes=(hash)
+ hash.each do |key, value|
+ send("#{key}=", value)
+ end
+ end
+
+ def attributes
+ {'name' => nil}
+ end
+end
+```
+
+Now it is possible to create an instance of person and set the attributes using `from_xml`.
+
+```ruby
+xml = { name: 'Bob' }.to_xml
+person = Person.new
+person.from_xml(xml) # => #<Person:0x00000100c773f0 @name="Bob">
+person.name # => "Bob"
+```
+
+### Translation
+
+`ActiveModel::Translation` provides integration between your object and the Rails
+internationalization (i18n) framework.
+
+```ruby
+class Person
+ extend ActiveModel::Translation
+end
+```
+
+With the `human_attribute_name` you can transform attribute names into a more
+human format. The human format is defined in your locale file.
+
+* config/locales/app.pt-BR.yml
+
+ ```yml
+ pt-BR:
+ activemodel:
+ attributes:
+ person:
+ name: 'Nome'
+ ```
+
+```ruby
+Person.human_attribute_name('name') # => "Nome"
+```
+
+### Lint Tests
+
+`ActiveModel::Lint::Tests` allow you to test whether an object is compliant with
+the Active Model API.
+
+* app/models/person.rb
+
+ ```ruby
+ class Person
+ include ActiveModel::Model
+
+ end
+ ```
+
+* test/models/person_test.rb
+
+ ```ruby
+ require 'test_helper'
+
+ class PersonTest < ActiveSupport::TestCase
+ include ActiveModel::Lint::Tests
+
+ def setup
+ @model = Person.new
+ end
+ end
+ ```
+
+```bash
+$ rake test
+
+Run options: --seed 14596
+
+# Running:
+
+......
+
+Finished in 0.024899s, 240.9735 runs/s, 1204.8677 assertions/s.
+
+6 runs, 30 assertions, 0 failures, 0 errors, 0 skips
+```
+
+An object is not required to implement all APIs in order to work with
+Action Pack. This module only intends to provide guidance in case you want all
+features out of the box.
+
+### SecurePassword
+
+`ActiveModel::SecurePassword` provides a way to securely store any
+password in an encrypted form. On including this module, a
+`has_secure_password` class method is provided which defines
+an accessor named `password` with certain validations on it.
+
+#### Requirements
+
+`ActiveModel::SecurePassword` depends on the [`bcrypt`](https://github.com/codahale/bcrypt-ruby 'BCrypt'),
+so include this gem in your Gemfile to use `ActiveModel::SecurePassword` correctly.
+In order to make this work, the model must have an accessor named `password_digest`.
+The `has_secure_password` will add the following validations on the `password` accessor:
+
+1. Password should be present.
+2. Password should be equal to its confirmation.
+3. This maximum length of a password is 72 (required by `bcrypt` on which ActiveModel::SecurePassword depends)
+
+#### Examples
+
+```ruby
+class Person
+ include ActiveModel::SecurePassword
+ has_secure_password
+ attr_accessor :password_digest
+end
+
+person = Person.new
+
+# When password is blank.
+person.valid? # => false
+
+# When the confirmation doesn't match the password.
+person.password = 'aditya'
+person.password_confirmation = 'nomatch'
+person.valid? # => false
+
+# When the length of password, exceeds 72.
+person.password = person.password_confirmation = 'a' * 100
+person.valid? # => false
+
+# When all validations are passed.
+person.password = person.password_confirmation = 'aditya'
+person.valid? # => true
+```
diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md
index 582bb240dd..4dc7203ba3 100644
--- a/guides/source/active_record_validations.md
+++ b/guides/source/active_record_validations.md
@@ -524,9 +524,15 @@ If you validate the presence of an object associated via a `has_one` or
`marked_for_destruction?`.
Since `false.blank?` is true, if you want to validate the presence of a boolean
-field you should use `validates :field_name, inclusion: { in: [true, false] }`.
+field you should use one of the following validations:
-The default error message is _"can't be blank"_.
+```ruby
+validates :boolean_field_name, presence: true
+validates :boolean_field_name, inclusion: { in: [true, false] }
+validates :boolean_field_name, exclusion: { in: [nil] }
+```
+By using one of these validations, you will ensure the value will NOT be `nil`
+which would result in a `NULL` value in most cases.
### `absence`
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index 7b9710bcd8..be0478653b 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -368,24 +368,24 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
```ruby
config.action_dispatch.rescue_responses = {
- 'ActionController::RoutingError' => :not_found,
- 'AbstractController::ActionNotFound' => :not_found,
- 'ActionController::MethodNotAllowed' => :method_not_allowed,
- 'ActionController::UnknownHttpMethod' => :method_not_allowed,
- 'ActionController::NotImplemented' => :not_implemented,
- 'ActionController::UnknownFormat' => :not_acceptable,
- 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,
- 'ActionDispatch::ParamsParser::ParseError' => :bad_request,
- 'ActionController::BadRequest' => :bad_request,
- 'ActionController::ParameterMissing' => :bad_request,
- 'ActiveRecord::RecordNotFound' => :not_found,
- 'ActiveRecord::StaleObjectError' => :conflict,
- 'ActiveRecord::RecordInvalid' => :unprocessable_entity,
- 'ActiveRecord::RecordNotSaved' => :unprocessable_entity
+ 'ActionController::RoutingError' => :not_found,
+ 'AbstractController::ActionNotFound' => :not_found,
+ 'ActionController::MethodNotAllowed' => :method_not_allowed,
+ 'ActionController::UnknownHttpMethod' => :method_not_allowed,
+ 'ActionController::NotImplemented' => :not_implemented,
+ 'ActionController::UnknownFormat' => :not_acceptable,
+ 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity,
+ 'ActionDispatch::ParamsParser::ParseError' => :bad_request,
+ 'ActionController::BadRequest' => :bad_request,
+ 'ActionController::ParameterMissing' => :bad_request,
+ 'ActiveRecord::RecordNotFound' => :not_found,
+ 'ActiveRecord::StaleObjectError' => :conflict,
+ 'ActiveRecord::RecordInvalid' => :unprocessable_entity,
+ 'ActiveRecord::RecordNotSaved' => :unprocessable_entity
}
```
- Any execptions that are not configured will be assigned to 500 Internal server error.
+ Any exceptions that are not configured will be mapped to 500 Internal Server Error.
* `ActionDispatch::Callbacks.before` takes a block of code to run before the request.
diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml
index 5c37837a1c..4c98d3e1d5 100644
--- a/guides/source/documents.yaml
+++ b/guides/source/documents.yaml
@@ -32,6 +32,11 @@
name: Active Record Query Interface
url: active_record_querying.html
description: This guide covers the database query interface provided by Active Record.
+ -
+ name: Active Model basics
+ url: active_model_basics.html
+ description: This guide covers the use of model classes without Active Record.
+ work_in_progress: true
-
name: Views
documents:
diff --git a/guides/source/testing.md b/guides/source/testing.md
index 29724ae011..b784098fbb 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -797,6 +797,7 @@ when you initiate a Rails project.
| `rake test:functionals` | Runs all the functional tests from `test/controllers`, `test/mailers`, and `test/functional` |
| `rake test:helpers` | Runs all the helper tests from `test/helpers` |
| `rake test:integration` | Runs all the integration tests from `test/integration` |
+| `rake test:jobs` | Runs all the job tests from `test/jobs` |
| `rake test:mailers` | Runs all the mailer tests from `test/mailers` |
| `rake test:models` | Runs all the model tests from `test/models` |
| `rake test:units` | Runs all the unit tests from `test/models`, `test/helpers`, and `test/unit` |