[DRE-commits] [rails] 28/44: New upstream version 4.0.2+dfsg

Ondrej Sury ondrej at moszumanska.debian.org
Wed Jul 16 15:04:01 UTC 2014


This is an automated email from the git hooks/post-receive script.

ondrej pushed a commit to branch master
in repository rails.

commit 81dc9dae6770051b10123089fc114639d279150f
Author: Ondřej Surý <ondrej at sury.org>
Date:   Wed Dec 4 10:33:18 2013 +0100

    New upstream version 4.0.2+dfsg
---
 .gitignore                                         |   2 +-
 .travis.yml                                        |   6 +
 Gemfile                                            |   9 +-
 RAILS_VERSION                                      |   2 +-
 Rakefile                                           |  18 +-
 actionmailer/CHANGELOG.md                          |  11 +
 actionmailer/README.rdoc                           |   2 +-
 actionmailer/actionmailer.gemspec                  |   2 +-
 actionmailer/lib/action_mailer/base.rb             |   2 +-
 actionmailer/lib/action_mailer/delivery_methods.rb |   2 +-
 actionmailer/lib/action_mailer/version.rb          |   2 +-
 actionmailer/test/base_test.rb                     |   4 +
 actionmailer/test/delivery_methods_test.rb         |   3 +
 actionmailer/test/fixtures/raw_email10             |  20 --
 actionmailer/test/fixtures/raw_email12             |  32 --
 actionmailer/test/fixtures/raw_email13             |  29 --
 actionmailer/test/fixtures/raw_email2              | 114 -------
 actionmailer/test/fixtures/raw_email3              |  70 -----
 actionmailer/test/fixtures/raw_email4              |  59 ----
 actionmailer/test/fixtures/raw_email5              |  19 --
 actionmailer/test/fixtures/raw_email6              |  20 --
 actionmailer/test/fixtures/raw_email7              |  66 -----
 actionmailer/test/fixtures/raw_email8              |  47 ---
 actionmailer/test/fixtures/raw_email9              |  28 --
 .../test/fixtures/raw_email_quoted_with_0d0a       |  14 -
 ...w_email_with_invalid_characters_in_content_type | 104 -------
 .../test/fixtures/raw_email_with_nested_attachment | 100 -------
 .../raw_email_with_partially_quoted_subject        |  14 -
 actionmailer/test/mailers/proc_mailer.rb           |   3 +-
 actionpack/CHANGELOG.md                            | 232 +++++++++++++++
 actionpack/README.rdoc                             |   2 +-
 actionpack/Rakefile                                |  14 +-
 actionpack/lib/abstract_controller/callbacks.rb    |   2 +-
 actionpack/lib/abstract_controller/helpers.rb      |   7 +-
 actionpack/lib/action_controller/base.rb           |   2 +-
 actionpack/lib/action_controller/metal/flash.rb    |   2 +-
 .../action_controller/metal/strong_parameters.rb   |   9 +-
 actionpack/lib/action_controller/test_case.rb      |   2 +-
 actionpack/lib/action_dispatch/http/mime_type.rb   |   2 +-
 actionpack/lib/action_dispatch/http/request.rb     |   4 +-
 actionpack/lib/action_dispatch/http/response.rb    |   4 +-
 .../lib/action_dispatch/journey/formatter.rb       |   6 +-
 .../journey/gtg/transition_table.rb                |  35 ++-
 actionpack/lib/action_dispatch/journey/route.rb    |  12 +
 .../lib/action_dispatch/journey/router/utils.rb    |   3 +
 actionpack/lib/action_dispatch/journey/routes.rb   |   1 +
 actionpack/lib/action_dispatch/journey/visitors.rb |   7 +-
 .../lib/action_dispatch/middleware/cookies.rb      |   2 +-
 .../action_dispatch/middleware/params_parser.rb    |   2 +-
 .../lib/action_dispatch/middleware/remote_ip.rb    |   2 +-
 actionpack/lib/action_dispatch/middleware/ssl.rb   |   5 +-
 actionpack/lib/action_dispatch/routing/mapper.rb   |   5 +
 .../lib/action_dispatch/routing/redirection.rb     |  18 ++
 .../lib/action_dispatch/routing/route_set.rb       |  27 +-
 .../lib/action_dispatch/testing/assertions/dom.rb  |   8 +-
 .../lib/action_dispatch/testing/test_request.rb    |  10 +-
 actionpack/lib/action_pack/version.rb              |   2 +-
 actionpack/lib/action_view/dependency_tracker.rb   |   2 +-
 actionpack/lib/action_view/digestor.rb             |  40 ++-
 actionpack/lib/action_view/helpers/date_helper.rb  |   4 +-
 actionpack/lib/action_view/helpers/form_helper.rb  |   2 +-
 .../lib/action_view/helpers/form_options_helper.rb |  17 +-
 .../lib/action_view/helpers/number_helper.rb       |   1 +
 actionpack/lib/action_view/helpers/tags/base.rb    |   3 +-
 .../helpers/tags/collection_check_boxes.rb         |   3 +-
 .../action_view/helpers/tags/collection_helpers.rb |   3 +-
 .../lib/action_view/helpers/tags/color_field.rb    |   2 +-
 .../lib/action_view/helpers/tags/datetime_field.rb |   2 +-
 actionpack/lib/action_view/helpers/tags/label.rb   |   1 +
 .../lib/action_view/helpers/tags/text_area.rb      |   2 +-
 .../lib/action_view/helpers/tags/text_field.rb     |   4 +-
 actionpack/lib/action_view/helpers/text_helper.rb  |   7 +-
 .../lib/action_view/helpers/translation_helper.rb  |  22 +-
 actionpack/lib/action_view/helpers/url_helper.rb   |   7 +-
 actionpack/lib/action_view/lookup_context.rb       |   7 +
 actionpack/lib/action_view/railtie.rb              |   4 +
 .../lib/action_view/renderer/template_renderer.rb  |   2 +-
 actionpack/lib/action_view/tasks/dependencies.rake |  17 ++
 actionpack/test/abstract/.helper_test.rb.swp       | Bin 0 -> 12288 bytes
 actionpack/test/abstract/helper_test.rb            |  20 ++
 actionpack/test/controller/filters_test.rb         |   9 +
 actionpack/test/controller/flash_test.rb           |  12 +
 actionpack/test/controller/integration_test.rb     |   6 +-
 .../parameters/nested_parameters_test.rb           |  15 +
 .../parameters/parameters_permit_test.rb           |   9 +
 actionpack/test/controller/render_test.rb          |  27 +-
 actionpack/test/controller/routing_test.rb         |   4 +
 actionpack/test/dispatch/prefix_generation_test.rb | 100 +++++++
 .../dispatch/request/json_params_parsing_test.rb   |   7 +
 .../dispatch/request/query_string_parsing_test.rb  |  15 +
 actionpack/test/dispatch/routing_test.rb           |  66 +++++
 actionpack/test/dispatch/ssl_test.rb               |  19 ++
 actionpack/test/dispatch/test_request_test.rb      |  30 ++
 .../fixtures/digestor/level/_recursion.html.erb    |   1 +
 .../fixtures/digestor/level/recursion.html.erb     |   1 +
 .../helpers_missing/invalid_require_helper.rb      |   5 +
 actionpack/test/journey/router/utils_test.rb       |   8 +
 actionpack/test/journey/router_test.rb             |  22 +-
 actionpack/test/routing/helper_test.rb             |   2 +-
 actionpack/test/template/date_helper_test.rb       |  12 +-
 .../test/template/dependency_tracker_test.rb       |  54 +++-
 actionpack/test/template/digestor_test.rb          |  63 +++-
 .../test/template/form_collections_helper_test.rb  |  11 +-
 actionpack/test/template/form_helper_test.rb       |  60 ++++
 .../test/template/form_options_helper_test.rb      |  16 +
 actionpack/test/template/number_helper_test.rb     |   3 +-
 actionpack/test/template/render_test.rb            |   5 +
 actionpack/test/template/resolver_patterns_test.rb |   2 +-
 actionpack/test/template/text_helper_test.rb       |   3 +
 .../test/template/translation_helper_test.rb       |   2 +-
 actionpack/test/template/url_helper_test.rb        |  33 +++
 actionpack/test/ts_isolated.rb                     |  15 -
 activemodel/CHANGELOG.md                           |  17 ++
 activemodel/README.rdoc                            |   2 +-
 activemodel/lib/active_model/attribute_methods.rb  |   5 +-
 activemodel/lib/active_model/errors.rb             |  10 +-
 activemodel/lib/active_model/secure_password.rb    |   8 +-
 .../lib/active_model/validations/clusivity.rb      |  15 +-
 .../lib/active_model/validations/inclusion.rb      |   2 +-
 activemodel/lib/active_model/version.rb            |   2 +-
 activemodel/test/cases/railtie_test.rb             |   5 +-
 activemodel/test/cases/secure_password_test.rb     |   8 +
 .../cases/serializers/json_serialization_test.rb   |   2 +-
 .../cases/serializers/xml_serialization_test.rb    |   3 +-
 .../cases/validations/inclusion_validation_test.rb |  23 ++
 activemodel/test/models/topic.rb                   |   2 +-
 activerecord/CHANGELOG.md                          | 329 ++++++++++++++++++++-
 activerecord/README.rdoc                           |   2 +-
 activerecord/Rakefile                              |   2 -
 activerecord/lib/active_record.rb                  |   1 +
 .../lib/active_record/association_relation.rb      |  18 ++
 .../lib/active_record/associations/association.rb  |  14 +-
 .../associations/builder/belongs_to.rb             |   6 +-
 .../associations/collection_association.rb         |  16 +-
 .../active_record/associations/collection_proxy.rb |   6 +-
 .../associations/has_many_association.rb           |   4 +-
 .../associations/has_one_association.rb            |   4 +-
 .../join_dependency/join_association.rb            |   2 +
 .../associations/join_dependency/join_part.rb      |  15 +-
 .../lib/active_record/associations/preloader.rb    |   5 +-
 .../lib/active_record/attribute_methods.rb         |  28 +-
 .../lib/active_record/attribute_methods/read.rb    |  24 +-
 .../attribute_methods/time_zone_conversion.rb      |   2 +-
 .../lib/active_record/attribute_methods/write.rb   |   2 +
 .../lib/active_record/autosave_association.rb      |  16 +-
 activerecord/lib/active_record/callbacks.rb        |   5 +-
 .../abstract/database_statements.rb                |  14 +-
 .../abstract/schema_statements.rb                  |  15 +-
 .../connection_adapters/abstract_adapter.rb        |  18 +-
 .../connection_adapters/abstract_mysql_adapter.rb  |   4 +-
 .../active_record/connection_adapters/column.rb    |  23 +-
 .../connection_adapters/mysql2_adapter.rb          |  12 +-
 .../connection_adapters/mysql_adapter.rb           |  28 +-
 .../connection_adapters/postgresql/cast.rb         |   2 +-
 .../postgresql/database_statements.rb              |  13 +-
 .../connection_adapters/postgresql/oid.rb          |   5 +
 .../connection_adapters/postgresql/quoting.rb      |   2 +
 .../postgresql/schema_statements.rb                |  17 +-
 .../connection_adapters/postgresql_adapter.rb      |  32 +-
 .../connection_adapters/sqlite3_adapter.rb         |  13 +-
 activerecord/lib/active_record/core.rb             |  36 +--
 activerecord/lib/active_record/dynamic_matchers.rb |   2 +-
 activerecord/lib/active_record/fixtures.rb         |   4 +-
 .../lib/active_record/locking/optimistic.rb        |   2 +-
 activerecord/lib/active_record/migration.rb        |   2 +-
 .../active_record/migration/command_recorder.rb    |   5 +-
 activerecord/lib/active_record/model_schema.rb     |  44 +--
 activerecord/lib/active_record/null_relation.rb    |   6 +-
 activerecord/lib/active_record/persistence.rb      |  21 +-
 activerecord/lib/active_record/railtie.rb          |   1 +
 .../lib/active_record/railties/databases.rake      |   5 +-
 activerecord/lib/active_record/reflection.rb       |   2 +-
 activerecord/lib/active_record/relation.rb         |   2 +-
 activerecord/lib/active_record/relation/batches.rb |   4 +-
 .../lib/active_record/relation/calculations.rb     |   1 +
 .../lib/active_record/relation/finder_methods.rb   |  20 +-
 activerecord/lib/active_record/relation/merger.rb  |  59 ++--
 .../lib/active_record/relation/query_methods.rb    |  31 +-
 activerecord/lib/active_record/result.rb           |  16 +-
 activerecord/lib/active_record/sanitization.rb     |  16 +-
 activerecord/lib/active_record/schema_dumper.rb    |   6 +-
 .../lib/active_record/tasks/database_tasks.rb      |   3 +-
 .../active_record/tasks/sqlite_database_tasks.rb   |   2 +-
 activerecord/lib/active_record/transactions.rb     |  10 +-
 .../lib/active_record/validations/uniqueness.rb    |   4 +-
 activerecord/lib/active_record/version.rb          |   2 +-
 .../cases/adapters/mysql/mysql_adapter_test.rb     |  31 +-
 .../test/cases/adapters/postgresql/array_test.rb   |  12 +
 .../cases/adapters/postgresql/datatype_test.rb     |  10 +-
 .../test/cases/adapters/postgresql/json_test.rb    |  13 +
 .../adapters/postgresql/postgresql_adapter_test.rb |  70 ++++-
 .../test/cases/adapters/postgresql/uuid_test.rb    |  52 +++-
 .../test/cases/adapters/postgresql/xml_test.rb     |  38 +++
 .../cases/adapters/sqlite3/sqlite3_adapter_test.rb |  12 +
 .../adapters/sqlite3/sqlite3_create_folder_test.rb |  21 ++
 .../associations/belongs_to_associations_test.rb   |  63 +++-
 .../has_and_belongs_to_many_associations_test.rb   |   4 +-
 .../associations/has_many_associations_test.rb     |  76 ++++-
 .../has_many_through_associations_test.rb          |   6 +
 .../associations/has_one_associations_test.rb      |   2 +
 .../associations/inner_join_association_test.rb    |  13 +
 .../associations/inverse_associations_test.rb      |  39 ++-
 activerecord/test/cases/associations_test.rb       |  13 +
 .../test/cases/attribute_methods/read_test.rb      |   7 -
 .../test/cases/autosave_association_test.rb        |  29 +-
 activerecord/test/cases/base_test.rb               |  39 +++
 activerecord/test/cases/batches_test.rb            |  10 +
 activerecord/test/cases/disconnected_test.rb       |  27 ++
 activerecord/test/cases/finder_respond_to_test.rb  |   5 +
 activerecord/test/cases/finder_test.rb             |  58 ++--
 activerecord/test/cases/fixtures_test.rb           |   4 +-
 activerecord/test/cases/inheritance_test.rb        |   6 +-
 activerecord/test/cases/invalid_connection_test.rb |  22 ++
 .../test/cases/invertible_migration_test.rb        |  28 ++
 activerecord/test/cases/locking_test.rb            |  12 +
 activerecord/test/cases/reflection_test.rb         |  16 +
 activerecord/test/cases/relation_test.rb           |  25 +-
 activerecord/test/cases/relations_test.rb          |  79 ++++-
 activerecord/test/cases/sanitize_test.rb           |  24 ++
 activerecord/test/cases/schema_dumper_test.rb      |   7 +-
 .../test/cases/scoping/default_scoping_test.rb     |   8 +-
 .../test/cases/serialized_attribute_test.rb        |   2 +-
 activerecord/test/fixtures/all/admin               |   1 +
 activerecord/test/fixtures/tasks.yml               |   2 +-
 .../test/fixtures/to_be_linked/accounts.yml        |   2 +
 activerecord/test/fixtures/to_be_linked/users.yml  |  10 +
 activerecord/test/models/author.rb                 |  13 +-
 activerecord/test/models/cake_designer.rb          |   3 +
 activerecord/test/models/chef.rb                   |   3 +
 activerecord/test/models/company.rb                |  11 +-
 activerecord/test/models/department.rb             |   4 +
 activerecord/test/models/drink_designer.rb         |   3 +
 activerecord/test/models/hotel.rb                  |   6 +
 activerecord/test/models/person.rb                 |   1 +
 activerecord/test/schema/schema.rb                 |  19 ++
 activesupport/CHANGELOG.md                         |  73 +++++
 activesupport/README.rdoc                          |   2 +-
 activesupport/Rakefile                             |   9 +-
 .../lib/active_support/backtrace_cleaner.rb        |   6 +-
 activesupport/lib/active_support/cache.rb          |   2 +-
 .../lib/active_support/cache/file_store.rb         |   3 +-
 .../lib/active_support/cache/memory_store.rb       |  16 +-
 activesupport/lib/active_support/callbacks.rb      |   2 +-
 .../active_support/core_ext/date_time/acts_like.rb |   1 +
 .../core_ext/date_time/conversions.rb              |  10 +
 .../active_support/core_ext/module/delegation.rb   |  21 +-
 activesupport/lib/active_support/core_ext/range.rb |   1 +
 .../lib/active_support/core_ext/range/each.rb      |  24 ++
 .../lib/active_support/core_ext/thread.rb          |  21 +-
 .../active_support/core_ext/time/calculations.rb   |  11 +-
 activesupport/lib/active_support/dependencies.rb   |   5 +-
 .../lib/active_support/deprecation/behaviors.rb    |  23 +-
 .../lib/active_support/multibyte/unicode.rb        |   6 +-
 activesupport/lib/active_support/number_helper.rb  |  18 +-
 activesupport/lib/active_support/rescuable.rb      |   1 -
 activesupport/lib/active_support/time_with_zone.rb |   6 +-
 activesupport/lib/active_support/version.rb        |   2 +-
 .../test/autoloading_fixtures/html/some_class.rb   |   4 +
 activesupport/test/caching_test.rb                 |  40 ++-
 activesupport/test/clean_backtrace_test.rb         |  21 ++
 activesupport/test/core_ext/date_time_ext_test.rb  |  10 +
 activesupport/test/core_ext/module_test.rb         |  27 ++
 activesupport/test/core_ext/numeric_ext_test.rb    |   2 +-
 activesupport/test/core_ext/range_ext_test.rb      |  24 +-
 activesupport/test/core_ext/thread_test.rb         |   9 +
 activesupport/test/core_ext/time_ext_test.rb       |  54 ++++
 activesupport/test/core_ext/time_with_zone_test.rb |  10 +
 .../raises_exception_without_blame_file.rb         |   5 +
 activesupport/test/dependencies_test.rb            |  16 +
 activesupport/test/deprecation_test.rb             |  16 +
 activesupport/test/json/encoding_test.rb           |   2 +-
 activesupport/test/rescuable_test.rb               |   2 +-
 activesupport/test/ts_isolated.rb                  |  16 -
 activesupport/test/xml_mini/jdom_engine_test.rb    |   2 +-
 activesupport/test/xml_mini/libxml_engine_test.rb  |   3 +-
 .../test/xml_mini/libxmlsax_engine_test.rb         |   3 +-
 .../test/xml_mini/nokogiri_engine_test.rb          |   3 +-
 .../test/xml_mini/nokogirisax_engine_test.rb       |   3 +-
 activesupport/test/xml_mini/rexml_engine_test.rb   |   3 +-
 railties/CHANGELOG.md                              |  28 ++
 railties/RDOC_MAIN.rdoc                            |   6 +-
 railties/README.rdoc                               |   2 +-
 railties/lib/rails/api/task.rb                     |   8 +
 railties/lib/rails/application.rb                  |   7 +-
 railties/lib/rails/application/bootstrap.rb        |   3 +-
 railties/lib/rails/commands.rb                     |  18 +-
 railties/lib/rails/engine.rb                       |   2 +-
 .../erb/scaffold/templates/_form.html.erb          |   5 +
 .../rails/generators/rails/app/app_generator.rb    |   2 +-
 .../rails/generators/rails/app/templates/Gemfile   |   2 +-
 .../app/views/layouts/application.html.erb.tt      |   5 +
 .../rails/app/templates/config/routes.rb           |   2 +-
 .../rails/generators/rails/app/templates/gitignore |   2 +-
 .../rails/scaffold/scaffold_generator.rb           |   2 +
 .../test_unit/model/templates/fixtures.yml         |   2 +-
 railties/lib/rails/rack/logger.rb                  |   7 +-
 railties/lib/rails/tasks.rb                        |   2 +-
 railties/lib/rails/tasks/documentation.rake        |   4 +-
 .../rails/templates/rails/welcome/index.html.erb   |   4 +-
 railties/lib/rails/version.rb                      |   2 +-
 railties/test/application/assets_test.rb           |   2 +-
 railties/test/application/configuration_test.rb    |   8 +
 .../test/application/middleware/remote_ip_test.rb  |  10 +
 railties/test/application/middleware_test.rb       |  16 +-
 railties/test/application/rake_test.rb             |  36 +--
 railties/test/application/routing_test.rb          |  45 +++
 railties/test/generators/app_generator_test.rb     |  11 +-
 .../test/generators/scaffold_generator_test.rb     |  40 ++-
 railties/test/rack_logger_test.rb                  |   2 +-
 tools/profile                                      |   1 -
 version.rb                                         |   2 +-
 311 files changed, 3501 insertions(+), 1435 deletions(-)

diff --git a/.gitignore b/.gitignore
index 7236e39..bc96284 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,5 +1,5 @@
 # Don't put *.swp, *.bak, etc here; those belong in a global ~/.gitignore.
-# Check out http://help.github.com/ignore-files/ for how to set that up.
+# Check out https://help.github.com/articles/ignoring-files for how to set that up.
 
 debug.log
 .Gemfile
diff --git a/.travis.yml b/.travis.yml
index 5214b98..17851c4 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -4,6 +4,8 @@ before_install:
 rvm:
   - 1.9.3
   - 2.0.0
+  - jruby-19mode
+  - rbx-19mode
 env:
   - "GEM=railties"
   - "GEM=ap,am,amo,as"
@@ -11,6 +13,10 @@ env:
   - "GEM=ar:mysql2"
   - "GEM=ar:sqlite3"
   - "GEM=ar:postgresql"
+matrix:
+  allow_failures:
+    - rvm: jruby-19mode
+    - rvm: rbx-19mode
 notifications:
   email: false
   irc:
diff --git a/Gemfile b/Gemfile
index 04562fe..4aae46f 100644
--- a/Gemfile
+++ b/Gemfile
@@ -4,10 +4,9 @@ gemspec
 
 gem 'mocha', '~> 0.13.0', require: false
 gem 'rack-cache', '~> 1.2'
-gem 'bcrypt-ruby', '~> 3.0.0'
+gem 'bcrypt-ruby', '~> 3.1.2'
 gem 'jquery-rails', '~> 2.2.0'
 gem 'turbolinks'
-gem 'coffee-rails', '~> 4.0.0'
 
 # This needs to be with require false to avoid
 # it being automatically loaded by sprockets
@@ -58,11 +57,11 @@ end
 
 platforms :jruby do
   gem 'json'
-  gem 'activerecord-jdbcsqlite3-adapter', '>= 1.2.7'
+  gem 'activerecord-jdbcsqlite3-adapter', '>= 1.3.0'
 
   group :db do
-    gem 'activerecord-jdbcmysql-adapter', '>= 1.2.7'
-    gem 'activerecord-jdbcpostgresql-adapter', '>= 1.2.7'
+    gem 'activerecord-jdbcmysql-adapter', '>= 1.3.0'
+    gem 'activerecord-jdbcpostgresql-adapter', '>= 1.3.0'
   end
 end
 
diff --git a/RAILS_VERSION b/RAILS_VERSION
index fcdb2e1..4d54dad 100644
--- a/RAILS_VERSION
+++ b/RAILS_VERSION
@@ -1 +1 @@
-4.0.0
+4.0.2
diff --git a/Rakefile b/Rakefile
index 177765f..a87e1a7 100644
--- a/Rakefile
+++ b/Rakefile
@@ -36,18 +36,14 @@ task :smoke do
 end
 
 desc "Install gems for all projects."
-task :install => :gem do
-  version = File.read("RAILS_VERSION").strip
-  (PROJECTS - ["railties"]).each do |project|
-    puts "INSTALLING #{project}"
-    system("gem install #{project}/pkg/#{project}-#{version}.gem --local --no-ri --no-rdoc")
-  end
-  system("gem install railties/pkg/railties-#{version}.gem --local --no-ri --no-rdoc")
-  system("gem install pkg/rails-#{version}.gem --local --no-ri --no-rdoc")
-end
+task :install => "all:install"
 
 desc "Generate documentation for the Rails framework"
-Rails::API::RepoTask.new('rdoc')
+if ENV['EDGE']
+  Rails::API::EdgeTask.new('rdoc')
+else
+  Rails::API::StableTask.new('rdoc')
+end
 
 desc 'Bump all versions to match version.rb'
 task :update_versions do
@@ -78,7 +74,7 @@ task :update_versions do
 end
 
 #
-# We have a webhook configured in Github that gets invoked after pushes.
+# We have a webhook configured in GitHub that gets invoked after pushes.
 # This hook triggers the following tasks:
 #
 #   * updates the local checkout
diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md
index 495a87a..fef8aac 100644
--- a/actionmailer/CHANGELOG.md
+++ b/actionmailer/CHANGELOG.md
@@ -1,3 +1,14 @@
+## Rails 4.0.1 (November 01, 2013) ##
+
+*   Invoke mailer defaults as procs only if they are procs, do not convert
+    with `to_proc`. That an object is convertible to a proc does not mean it's
+    meant to be always used as a proc.
+
+    Fixes #11533.
+
+    *Alex Tsukernik*
+
+
 ## Rails 4.0.0 (June 25, 2013) ##
 
 *   Allow passing interpolations to `#default_i18n_subject`, e.g.:
diff --git a/actionmailer/README.rdoc b/actionmailer/README.rdoc
index a14a6ba..a02ea86 100644
--- a/actionmailer/README.rdoc
+++ b/actionmailer/README.rdoc
@@ -142,7 +142,7 @@ The latest version of Action Mailer can be installed with RubyGems:
 
 Source code can be downloaded as part of the Rails project on GitHub
 
-* https://github.com/rails/rails/tree/master/actionmailer
+* https://github.com/rails/rails/tree/4-0-stable/actionmailer
 
 
 == License
diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec
index 67ec0d1..c56b697 100644
--- a/actionmailer/actionmailer.gemspec
+++ b/actionmailer/actionmailer.gemspec
@@ -21,5 +21,5 @@ Gem::Specification.new do |s|
 
   s.add_dependency 'actionpack', version
 
-  s.add_dependency 'mail', '~> 2.5.3'
+  s.add_dependency 'mail', '~> 2.5.4'
 end
diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb
index 1fff958..9d612db 100644
--- a/actionmailer/lib/action_mailer/base.rb
+++ b/actionmailer/lib/action_mailer/base.rb
@@ -670,7 +670,7 @@ module ActionMailer
       # Call all the procs (if any)
       class_default = self.class.default
       default_values = class_default.merge(class_default) do |k,v|
-        v.respond_to?(:to_proc) ? instance_eval(&v) : v
+        v.is_a?(Proc) ? instance_eval(&v) : v
       end
 
       # Handle defaults
diff --git a/actionmailer/lib/action_mailer/delivery_methods.rb b/actionmailer/lib/action_mailer/delivery_methods.rb
index caea3d7..b1ef0a7 100644
--- a/actionmailer/lib/action_mailer/delivery_methods.rb
+++ b/actionmailer/lib/action_mailer/delivery_methods.rb
@@ -63,7 +63,7 @@ module ActionMailer
           raise "Delivery method cannot be nil"
         when Symbol
           if klass = delivery_methods[method]
-            mail.delivery_method(klass,(send(:"#{method}_settings") || {}).merge!(options || {}))
+            mail.delivery_method(klass, (send(:"#{method}_settings") || {}).merge(options || {}))
           else
             raise "Invalid delivery method #{method.inspect}"
           end
diff --git a/actionmailer/lib/action_mailer/version.rb b/actionmailer/lib/action_mailer/version.rb
index caf0534..7faa489 100644
--- a/actionmailer/lib/action_mailer/version.rb
+++ b/actionmailer/lib/action_mailer/version.rb
@@ -1,7 +1,7 @@
 module ActionMailer
   # Returns the version of the currently loaded ActionMailer as a Gem::Version
   def self.version
-    Gem::Version.new "4.0.0"
+    Gem::Version.new "4.0.2"
   end
 
   module VERSION #:nodoc:
diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb
index b9c56c5..b74728a 100644
--- a/actionmailer/test/base_test.rb
+++ b/actionmailer/test/base_test.rb
@@ -578,6 +578,10 @@ class BaseTest < ActiveSupport::TestCase
     assert(mail1.to_s.to_i > mail2.to_s.to_i)
   end
 
+  test 'default values which have to_proc (e.g. symbols) should not be considered procs' do
+    assert(ProcMailer.welcome['x-has-to-proc'].to_s == 'symbol')
+  end
+
   test "we can call other defined methods on the class as needed" do
     mail = ProcMailer.welcome
     assert_equal("Thanks for signing up this afternoon", mail.subject)
diff --git a/actionmailer/test/delivery_methods_test.rb b/actionmailer/test/delivery_methods_test.rb
index 61a037e..20412c7 100644
--- a/actionmailer/test/delivery_methods_test.rb
+++ b/actionmailer/test/delivery_methods_test.rb
@@ -152,6 +152,9 @@ class MailDeliveryTest < ActiveSupport::TestCase
     assert_equal "overridden", delivery_method_instance.settings[:user_name]
     assert_equal "somethingobtuse", delivery_method_instance.settings[:password]
     assert_equal delivery_method_instance.settings.merge(overridden_options), delivery_method_instance.settings
+
+    # make sure that overriding delivery method options per mail instance doesn't affect the Base setting
+    assert_equal settings, ActionMailer::Base.smtp_settings
   end
 
   test "non registered delivery methods raises errors" do
diff --git a/actionmailer/test/fixtures/raw_email10 b/actionmailer/test/fixtures/raw_email10
deleted file mode 100644
index edad5cc..0000000
--- a/actionmailer/test/fixtures/raw_email10
+++ /dev/null
@@ -1,20 +0,0 @@
-Return-Path: <xxx at xxxx.xxx>
-Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id C1B953B4CB6 for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:05 -0500
-Received: from SMS-GTYxxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id ca for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:04 -0500
-Received: from xxx.xxxx.xxx by SMS-GTYxxx.xxxx.xxx with ESMTP id j4AKR3r23323 for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:03 -0500
-Date: Tue, 10 May 2005 15:27:03 -0500
-From: xxx at xxxx.xxx
-Sender: xxx at xxxx.xxx
-To: xxxxxxxxxxx at xxxx.xxxx.xxx
-Message-Id: <xxx at xxxx.xxx>
-X-Original-To: xxxxxxxxxxx at xxxx.xxxx.xxx
-Delivered-To: xxx at xxxx.xxx
-Importance: normal
-Content-Type: text/plain; charset=X-UNKNOWN
-
-Test test. Hi. Waving. m
-
-----------------------------------------------------------------
-Sent via Bell Mobility's Text Messaging service.
-Envoyé par le service de messagerie texte de Bell Mobilité.
-----------------------------------------------------------------
diff --git a/actionmailer/test/fixtures/raw_email12 b/actionmailer/test/fixtures/raw_email12
deleted file mode 100644
index 2cd3172..0000000
--- a/actionmailer/test/fixtures/raw_email12
+++ /dev/null
@@ -1,32 +0,0 @@
-Mime-Version: 1.0 (Apple Message framework v730)
-Content-Type: multipart/mixed; boundary=Apple-Mail-13-196941151
-Message-Id: <9169D984-4E0B-45EF-82D4-8F5E53AD7012 at example.com>
-From: foo at example.com
-Subject: testing
-Date: Mon, 6 Jun 2005 22:21:22 +0200
-To: blah at example.com
-
-
---Apple-Mail-13-196941151
-Content-Transfer-Encoding: quoted-printable
-Content-Type: text/plain;
-	charset=ISO-8859-1;
-	delsp=yes;
-	format=flowed
-
-This is the first part.
-
---Apple-Mail-13-196941151
-Content-Type: image/jpeg
-Content-Transfer-Encoding: base64
-Content-Location: Photo25.jpg
-Content-ID: <qbFGyPQAS8>
-Content-Disposition: inline
-
-jamisSqGSIb3DQEHAqCAMIjamisxCzAJBgUrDgMCGgUAMIAGCSqGSjamisEHAQAAoIIFSjCCBUYw
-ggQujamisQICBD++ukQwDQYJKojamisNAQEFBQAwMTELMAkGA1UEBhMCRjamisAKBgNVBAoTA1RE
-QzEUMBIGjamisxMLVERDIE9DRVMgQ0jamisNMDQwMjI5MTE1OTAxWhcNMDYwMjamisIyOTAxWjCB
-gDELMAkGA1UEjamisEsxKTAnBgNVBAoTIEjamisuIG9yZ2FuaXNhdG9yaXNrIHRpbjamisRuaW5=
-
---Apple-Mail-13-196941151--
-
diff --git a/actionmailer/test/fixtures/raw_email13 b/actionmailer/test/fixtures/raw_email13
deleted file mode 100644
index 7d9314e..0000000
--- a/actionmailer/test/fixtures/raw_email13
+++ /dev/null
@@ -1,29 +0,0 @@
-Mime-Version: 1.0 (Apple Message framework v730)
-Content-Type: multipart/mixed; boundary=Apple-Mail-13-196941151
-Message-Id: <9169D984-4E0B-45EF-82D4-8F5E53AD7012 at example.com>
-From: foo at example.com
-Subject: testing
-Date: Mon, 6 Jun 2005 22:21:22 +0200
-To: blah at example.com
-
-
---Apple-Mail-13-196941151
-Content-Transfer-Encoding: quoted-printable
-Content-Type: text/plain;
-	charset=ISO-8859-1;
-	delsp=yes;
-	format=flowed
-
-This is the first part.
-
---Apple-Mail-13-196941151
-Content-Type: text/x-ruby-script; name="hello.rb"
-Content-Transfer-Encoding: 7bit
-Content-Disposition: attachment;
-	filename="api.rb"
-
-puts "Hello, world!"
-gets
-
---Apple-Mail-13-196941151--
-
diff --git a/actionmailer/test/fixtures/raw_email2 b/actionmailer/test/fixtures/raw_email2
deleted file mode 100644
index 9f87bb2..0000000
--- a/actionmailer/test/fixtures/raw_email2
+++ /dev/null
@@ -1,114 +0,0 @@
-From xxxxxxxxx.xxxxxxx at gmail.com Sun May  8 19:07:09 2005
-Return-Path: <xxxxxxxxx.xxxxxxx at gmail.com>
-X-Original-To: xxxxx at xxxxx.xxxxxxxxx.com
-Delivered-To: xxxxx at xxxxx.xxxxxxxxx.com
-Received: from localhost (localhost [127.0.0.1])
-	by xxxxx.xxxxxxxxx.com (Postfix) with ESMTP id 06C9DA98D
-	for <xxxxx at xxxxx.xxxxxxxxx.com>; Sun,  8 May 2005 19:09:13 +0000 (GMT)
-Received: from xxxxx.xxxxxxxxx.com ([127.0.0.1])
- by localhost (xxxxx.xxxxxxxxx.com [127.0.0.1]) (amavisd-new, port 10024)
- with LMTP id 88783-08 for <xxxxx at xxxxx.xxxxxxxxx.com>;
- Sun,  8 May 2005 19:09:12 +0000 (GMT)
-Received: from xxxxxxx.xxxxxxxxx.com (xxxxxxx.xxxxxxxxx.com [69.36.39.150])
-	by xxxxx.xxxxxxxxx.com (Postfix) with ESMTP id 10D8BA960
-	for <xxxxx at xxxxxxxxx.org>; Sun,  8 May 2005 19:09:12 +0000 (GMT)
-Received: from zproxy.gmail.com (zproxy.gmail.com [64.233.162.199])
-	by xxxxxxx.xxxxxxxxx.com (Postfix) with ESMTP id 9EBC4148EAB
-	for <xxxxx at xxxxxxxxx.com>; Sun,  8 May 2005 14:09:11 -0500 (CDT)
-Received: by zproxy.gmail.com with SMTP id 13so1233405nzp
-        for <xxxxx at xxxxxxxxx.com>; Sun, 08 May 2005 12:09:11 -0700 (PDT)
-DomainKey-Signature: a=rsa-sha1; q=dns; c=nofws;
-        s=beta; d=gmail.com;
-        h=received:message-id:date:from:reply-to:to:subject:in-reply-to:mime-version:content-type:references;
-        b=cid1mzGEFa3gtRa06oSrrEYfKca2CTKu9sLMkWxjbvCsWMtp9RGEILjUz0L5RySdH5iO661LyNUoHRFQIa57bylAbXM3g2DTEIIKmuASDG3x3rIQ4sHAKpNxP7Pul+mgTaOKBv+spcH7af++QEJ36gHFXD2O/kx9RePs3JNf/K8=
-Received: by 10.36.10.16 with SMTP id 16mr1012493nzj;
-        Sun, 08 May 2005 12:09:11 -0700 (PDT)
-Received: by 10.36.5.10 with HTTP; Sun, 8 May 2005 12:09:11 -0700 (PDT)
-Message-ID: <e85734b90505081209eaaa17b at mail.gmail.com>
-Date: Sun, 8 May 2005 14:09:11 -0500
-From: xxxxxxxxx xxxxxxx <xxxxxxxxx.xxxxxxx at gmail.com>
-Reply-To: xxxxxxxxx xxxxxxx <xxxxxxxxx.xxxxxxx at gmail.com>
-To: xxxxx xxxx <xxxxx at xxxxxxxxx.com>
-Subject: Fwd: Signed email causes file attachments
-In-Reply-To: <F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13 at mac.com>
-Mime-Version: 1.0
-Content-Type: multipart/mixed;
-	boundary="----=_Part_5028_7368284.1115579351471"
-References: <F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13 at mac.com>
-
-------=_Part_5028_7368284.1115579351471
-Content-Type: text/plain; charset=ISO-8859-1
-Content-Transfer-Encoding: quoted-printable
-Content-Disposition: inline
-
-We should not include these files or vcards as attachments.
-
----------- Forwarded message ----------
-From: xxxxx xxxxxx <xxxxxxxx at xxx.com>
-Date: May 8, 2005 1:17 PM
-Subject: Signed email causes file attachments
-To: xxxxxxx at xxxxxxxxxx.com
-
-
-Hi,
-
-Just started to use my xxxxxxxx account (to set-up a GTD system,
-natch) and noticed that when I send content via email the signature/
-certificate from my email account gets added as a file (e.g.
-"smime.p7s").
-
-Obviously I can uncheck the signature option in the Mail compose
-window but how often will I remember to do that?
-
-Is there any way these kind of files could be ignored, e.g. via some
-sort of exclusions list?
-
-------=_Part_5028_7368284.1115579351471
-Content-Type: application/pkcs7-signature; name=smime.p7s
-Content-Transfer-Encoding: base64
-Content-Disposition: attachment; filename="smime.p7s"
-
-MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIGFDCCAs0w
-ggI2oAMCAQICAw5c+TANBgkqhkiG9w0BAQQFADBiMQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhh
-d3RlIENvbnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNvbmFsIEZyZWVt
-YWlsIElzc3VpbmcgQ0EwHhcNMDUwMzI5MDkzOTEwWhcNMDYwMzI5MDkzOTEwWjBCMR8wHQYDVQQD
-ExZUaGF3dGUgRnJlZW1haWwgTWVtYmVyMR8wHQYJKoZIhvcNAQkBFhBzbWhhdW5jaEBtYWMuY29t
-MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn90dPsYS3LjfMY211OSYrDQLzwNYPlAL
-7+/0XA+kdy8/rRnyEHFGwhNCDmg0B6pxC7z3xxJD/8GfCd+IYUUNUQV5m9MkxfP9pTVXZVIYLaBw
-o8xS3A0a1LXealcmlEbJibmKkEaoXci3MhryLgpaa+Kk/sH02SNatDO1vS28bPsibZpcc6deFrla
-hSYnL+PW54mDTGHIcCN2fbx/Y6qspzqmtKaXrv75NBtuy9cB6KzU4j2xXbTkAwz3pRSghJJaAwdp
-+yIivAD3vr0kJE3p+Ez34HMh33EXEpFoWcN+MCEQZD9WnmFViMrvfvMXLGVFQfAAcC060eGFSRJ1
-ZQ9UVQIDAQABoy0wKzAbBgNVHREEFDASgRBzbWhhdW5jaEBtYWMuY29tMAwGA1UdEwEB/wQCMAAw
-DQYJKoZIhvcNAQEEBQADgYEAQMrg1n2pXVWteP7BBj+Pk3UfYtbuHb42uHcLJjfjnRlH7AxnSwrd
-L3HED205w3Cq8T7tzVxIjRRLO/ljq0GedSCFBky7eYo1PrXhztGHCTSBhsiWdiyLWxKlOxGAwJc/
-lMMnwqLOdrQcoF/YgbjeaUFOQbUh94w9VDNpWZYCZwcwggM/MIICqKADAgECAgENMA0GCSqGSIb3
-DQEBBQUAMIHRMQswCQYDVQQGEwJaQTEVMBMGA1UECBMMV2VzdGVybiBDYXBlMRIwEAYDVQQHEwlD
-YXBlIFRvd24xGjAYBgNVBAoTEVRoYXd0ZSBDb25zdWx0aW5nMSgwJgYDVQQLEx9DZXJ0aWZpY2F0
-aW9uIFNlcnZpY2VzIERpdmlzaW9uMSQwIgYDVQQDExtUaGF3dGUgUGVyc29uYWwgRnJlZW1haWwg
-Q0ExKzApBgkqhkiG9w0BCQEWHHBlcnNvbmFsLWZyZWVtYWlsQHRoYXd0ZS5jb20wHhcNMDMwNzE3
-MDAwMDAwWhcNMTMwNzE2MjM1OTU5WjBiMQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhhd3RlIENv
-bnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNvbmFsIEZyZWVtYWlsIElz
-c3VpbmcgQ0EwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMSmPFVzVftOucqZWh5owHUEcJ3f
-6f+jHuy9zfVb8hp2vX8MOmHyv1HOAdTlUAow1wJjWiyJFXCO3cnwK4Vaqj9xVsuvPAsH5/EfkTYk
-KhPPK9Xzgnc9A74r/rsYPge/QIACZNenprufZdHFKlSFD0gEf6e20TxhBEAeZBlyYLf7AgMBAAGj
-gZQwgZEwEgYDVR0TAQH/BAgwBgEB/wIBADBDBgNVHR8EPDA6MDigNqA0hjJodHRwOi8vY3JsLnRo
-YXd0ZS5jb20vVGhhd3RlUGVyc29uYWxGcmVlbWFpbENBLmNybDALBgNVHQ8EBAMCAQYwKQYDVR0R
-BCIwIKQeMBwxGjAYBgNVBAMTEVByaXZhdGVMYWJlbDItMTM4MA0GCSqGSIb3DQEBBQUAA4GBAEiM
-0VCD6gsuzA2jZqxnD3+vrL7CF6FDlpSdf0whuPg2H6otnzYvwPQcUCCTcDz9reFhYsPZOhl+hLGZ
-GwDFGguCdJ4lUJRix9sncVcljd2pnDmOjCBPZV+V2vf3h9bGCE6u9uo05RAaWzVNd+NWIXiC3CEZ
-Nd4ksdMdRv9dX2VPMYIC5zCCAuMCAQEwaTBiMQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhhd3Rl
-IENvbnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNvbmFsIEZyZWVtYWls
-IElzc3VpbmcgQ0ECAw5c+TAJBgUrDgMCGgUAoIIBUzAYBgkqhkiG9w0BCQMxCwYJKoZIhvcNAQcB
-MBwGCSqGSIb3DQEJBTEPFw0wNTA1MDgxODE3NDZaMCMGCSqGSIb3DQEJBDEWBBQSkG9j6+hB0pKp
-fV9tCi/iP59sNTB4BgkrBgEEAYI3EAQxazBpMGIxCzAJBgNVBAYTAlpBMSUwIwYDVQQKExxUaGF3
-dGUgQ29uc3VsdGluZyAoUHR5KSBMdGQuMSwwKgYDVQQDEyNUaGF3dGUgUGVyc29uYWwgRnJlZW1h
-aWwgSXNzdWluZyBDQQIDDlz5MHoGCyqGSIb3DQEJEAILMWugaTBiMQswCQYDVQQGEwJaQTElMCMG
-A1UEChMcVGhhd3RlIENvbnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNv
-bmFsIEZyZWVtYWlsIElzc3VpbmcgQ0ECAw5c+TANBgkqhkiG9w0BAQEFAASCAQAm1GeF7dWfMvrW
-8yMPjkhE+R8D1DsiCoWSCp+5gAQm7lcK7V3KrZh5howfpI3TmCZUbbaMxOH+7aKRKpFemxoBY5Q8
-rnCkbpg/++/+MI01T69hF/rgMmrGcrv2fIYy8EaARLG0xUVFSZHSP+NQSYz0TTmh4cAESHMzY3JA
-nHOoUkuPyl8RXrimY1zn0lceMXlweZRouiPGuPNl1hQKw8P+GhOC5oLlM71UtStnrlk3P9gqX5v7
-Tj7Hx057oVfY8FMevjxGwU3EK5TczHezHbWWgTyum9l2ZQbUQsDJxSniD3BM46C1VcbDLPaotAZ0
-fTYLZizQfm5hcWEbfYVzkSzLAAAAAAAA
-------=_Part_5028_7368284.1115579351471--
-
diff --git a/actionmailer/test/fixtures/raw_email3 b/actionmailer/test/fixtures/raw_email3
deleted file mode 100644
index 3a09274..0000000
--- a/actionmailer/test/fixtures/raw_email3
+++ /dev/null
@@ -1,70 +0,0 @@
-From xxxx at xxxx.com Tue May 10 11:28:07 2005
-Return-Path: <xxxx at xxxx.com>
-X-Original-To: xxxx at xxxx.com
-Delivered-To: xxxx at xxxx.com
-Received: from localhost (localhost [127.0.0.1])
-	by xxx.xxxxx.com (Postfix) with ESMTP id 50FD3A96F
-	for <xxxx at xxxx.com>; Tue, 10 May 2005 17:26:50 +0000 (GMT)
-Received: from xxx.xxxxx.com ([127.0.0.1])
- by localhost (xxx.xxxxx.com [127.0.0.1]) (amavisd-new, port 10024)
- with LMTP id 70060-03 for <xxxx at xxxx.com>;
- Tue, 10 May 2005 17:26:49 +0000 (GMT)
-Received: from xxx.xxxxx.com (xxx.xxxxx.com [69.36.39.150])
-	by xxx.xxxxx.com (Postfix) with ESMTP id 8B957A94B
-	for <xxxx at xxxx.com>; Tue, 10 May 2005 17:26:48 +0000 (GMT)
-Received: from xxx.xxxxx.com (xxx.xxxxx.com [64.233.184.203])
-	by xxx.xxxxx.com (Postfix) with ESMTP id 9972514824C
-	for <xxxx at xxxx.com>; Tue, 10 May 2005 12:26:40 -0500 (CDT)
-Received: by xxx.xxxxx.com with SMTP id 68so1694448wri
-        for <xxxx at xxxx.com>; Tue, 10 May 2005 10:26:40 -0700 (PDT)
-DomainKey-Signature: a=rsa-sha1; q=dns; c=nofws;
-        s=beta; d=xxxxx.com;
-        h=received:message-id:date:from:reply-to:to:subject:mime-version:content-type;
-        b=g8ZO5ttS6GPEMAz9WxrRk9+9IXBUfQIYsZLL6T88+ECbsXqGIgfGtzJJFn6o9CE3/HMrrIGkN5AisxVFTGXWxWci5YA/7PTVWwPOhJff5BRYQDVNgRKqMl/SMttNrrRElsGJjnD1UyQ/5kQmcBxq2PuZI5Zc47u6CILcuoBcM+A=
-Received: by 10.54.96.19 with SMTP id t19mr621017wrb;
-        Tue, 10 May 2005 10:26:39 -0700 (PDT)
-Received: by 10.54.110.5 with HTTP; Tue, 10 May 2005 10:26:39 -0700 (PDT)
-Message-ID: <xxxx at xxxx.com>
-Date: Tue, 10 May 2005 11:26:39 -0600
-From: Test Tester <xxxx at xxxx.com>
-Reply-To: Test Tester <xxxx at xxxx.com>
-To: xxxx at xxxx.com, xxxx at xxxx.com
-Subject: Another PDF
-Mime-Version: 1.0
-Content-Type: multipart/mixed;
-	boundary="----=_Part_2192_32400445.1115745999735"
-X-Virus-Scanned: amavisd-new at textdrive.com
-
-------=_Part_2192_32400445.1115745999735
-Content-Type: text/plain; charset=ISO-8859-1
-Content-Transfer-Encoding: quoted-printable
-Content-Disposition: inline
-
-Just attaching another PDF, here, to see what the message looks like,
-and to see if I can figure out what is going wrong here.
-
-------=_Part_2192_32400445.1115745999735
-Content-Type: application/pdf; name="broken.pdf"
-Content-Transfer-Encoding: base64
-Content-Disposition: attachment; filename="broken.pdf"
-
-JVBERi0xLjQNCiXk9tzfDQoxIDAgb2JqDQo8PCAvTGVuZ3RoIDIgMCBSDQogICAvRmlsdGVyIC9G
-bGF0ZURlY29kZQ0KPj4NCnN0cmVhbQ0KeJy9Wt2KJbkNvm/od6jrhZxYln9hWEh2p+8HBvICySaE
-ycLuTV4/1ifJ9qnq09NpSBimu76yLUuy/qzqcPz7+em3Ixx/CDc6CsXxs3b5+fvfjr/8cPz6/BRu
-rbfAx/n3739/fuJylJ5u5fjX81OuDr4deK4Bz3z/aDP+8fz0yw8g0Ofq7ktr1Mn+u28rvhy/jVeD
-QSa+9YNKHP/pxjvDNfVAx/m3MFz54FhvTbaseaxiDoN2LeMVMw+yA7RbHSCDzxZuaYB2E1Yay7QU
-x89vz0+tyFDKMlAHK5yqLmnjF+c4RjEiQIUeKwblXMe+AsZjN1J5yGQL5DHpDHksurM81rF6PKab
-gK6zAarIDzIiUY23rJsN9iorAE816aIu6lsgAdQFsuhhkHOUFgVjp2GjMqSewITXNQ27jrMeamkg
-1rPI3iLWG2CIaSBB+V1245YVRICGbbpYKHc2USFDl6M09acQVQYhlwIrkBNLISvXhGlF1wi5FHCw
-wxZkoGNJlVeJCEsqKA+3YAV5AMb6KkeaqEJQmFKKQU8T1pRi2ihE1Y4CDrqoYFFXYjJJOatsyzuI
-8SIlykuxKTMibWK8H1PgEvqYgs4GmQSrEjJAalgGirIhik+p4ZQN9E3ETFPAHE1b8pp1l/0Rc1gl
-fQs0ABWvyoZZzU8VnPXwVVcO9BEsyjEJaO6eBoZRyKGlrKoYoOygA8BGIzgwN3RQ15ouigG5idZQ
-fx2U4Db2CqiLO0WHAZoylGiCAqhniNQjFjQPSkmjwfNTgQ6M1Ih+eWo36wFmjIxDJZiGUBiWsAyR
-xX3EekGOizkGI96Ol9zVZTAivikURhRsHh2E3JhWMpSTZCnnonrLhMCodgrNcgo4uyJUJc6qnVss
-nrGd1Ptr0YwisCOYyIbUwVjV4xBUNLbguSO2YHujonAMJkMdSI7bIw91Akq2AUlMUWGFTMAOamjU
-OvZQCxIkY2pCpMFo/IwLdVLHs6nddwTRrgoVbvLU9eB0G4EMndV0TNoxHbt3JBWwK6hhv3iHfDtF
-yokB302IpEBTnWICde4uYc/1khDbSIkQopO6lcqamGBu1OSE3N5IPSsZX00CkSHRiiyx6HQIShsS
-HSVNswdVsaOUSAWq9aYhDtGDaoG5a3lBGkYt/lFlBFt1UqrYnzVtUpUQnLiZeouKgf1KhRBViRRk
-ExepJCzTwEmFDalIRbLEGtw0gfpESOpIAF/NnpPzcVCG86s0g2DuSyd41uhNGbEgaSrWEXORErbw
-------=_Part_2192_32400445.1115745999735--
-
diff --git a/actionmailer/test/fixtures/raw_email4 b/actionmailer/test/fixtures/raw_email4
deleted file mode 100644
index 639ad40..0000000
--- a/actionmailer/test/fixtures/raw_email4
+++ /dev/null
@@ -1,59 +0,0 @@
-Return-Path: <xxx at xxxx.xxx>
-Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id 6AAEE3B4D23 for <xxx at xxxx.xxx>; Sun, 8 May 2005 12:30:23 -0500
-Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id j48HUC213279 for <xxx at xxxx.xxx>; Sun, 8 May 2005 12:30:13 -0500
-Received: from conversion-xxx.xxxx.xxx.net by xxx.xxxx.xxx id <0IG600901LQ64I at xxx.xxxx.xxx> for <xxx at xxxx.xxx>; Sun, 8 May 2005 12:30:12 -0500
-Received: from agw1 by xxx.xxxx.xxx with ESMTP id <0IG600JFYLYCAxxx at xxxx.xxx> for <xxx at xxxx.xxx>; Sun, 8 May 2005 12:30:12 -0500
-Date: Sun, 8 May 2005 12:30:08 -0500
-From: xxx at xxxx.xxx
-To: xxx at xxxx.xxx
-Message-Id: <7864245.1115573412626.JavaMxxx at xxxx.xxx>
-Subject: Filth
-Mime-Version: 1.0
-Content-Type: multipart/mixed; boundary=mimepart_427e4cb4ca329_133ae40413c81ef
-X-Mms-Priority: 1
-X-Mms-Transaction-Id: 3198421808-0
-X-Mms-Message-Type: 0
-X-Mms-Sender-Visibility: 1
-X-Mms-Read-Reply: 1
-X-Original-To: xxx at xxxx.xxx
-X-Mms-Message-Class: 0
-X-Mms-Delivery-Report: 0
-X-Mms-Mms-Version: 16
-Delivered-To: xxx at xxxx.xxx
-X-Nokia-Ag-Version: 2.0
-
-This is a multi-part message in MIME format.
-
---mimepart_427e4cb4ca329_133ae40413c81ef
-Content-Type: multipart/mixed; boundary=mimepart_427e4cb4cbd97_133ae40413c8217
-
-
-
---mimepart_427e4cb4cbd97_133ae40413c8217
-Content-Type: text/plain; charset=utf-8
-Content-Transfer-Encoding: 7bit
-Content-Disposition: inline
-Content-Location: text.txt
-
-Some text
-
---mimepart_427e4cb4cbd97_133ae40413c8217--
-
---mimepart_427e4cb4ca329_133ae40413c81ef
-Content-Type: text/plain; charset=us-ascii
-Content-Transfer-Encoding: 7bit
-
-
---
-This Orange Multi Media Message was sent wirefree from an Orange
-MMS phone. If you would like to reply, please text or phone the
-sender directly by using the phone number listed in the sender's
-address. To learn more about Orange's Multi Media Messaging
-Service, find us on the Web at xxx.xxxx.xxx.uk/mms
-
-
---mimepart_427e4cb4ca329_133ae40413c81ef
-
-
---mimepart_427e4cb4ca329_133ae40413c81ef-
-
diff --git a/actionmailer/test/fixtures/raw_email5 b/actionmailer/test/fixtures/raw_email5
deleted file mode 100644
index bbe31bc..0000000
--- a/actionmailer/test/fixtures/raw_email5
+++ /dev/null
@@ -1,19 +0,0 @@
-Return-Path: <xxx at xxxx.xxx>
-Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id C1B953B4CB6 for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:05 -0500
-Received: from SMS-GTYxxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id ca for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:04 -0500
-Received: from xxx.xxxx.xxx by SMS-GTYxxx.xxxx.xxx with ESMTP id j4AKR3r23323 for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:03 -0500
-Date: Tue, 10 May 2005 15:27:03 -0500
-From: xxx at xxxx.xxx
-Sender: xxx at xxxx.xxx
-To: xxxxxxxxxxx at xxxx.xxxx.xxx
-Message-Id: <xxx at xxxx.xxx>
-X-Original-To: xxxxxxxxxxx at xxxx.xxxx.xxx
-Delivered-To: xxx at xxxx.xxx
-Importance: normal
-
-Test test. Hi. Waving. m
-
-----------------------------------------------------------------
-Sent via Bell Mobility's Text Messaging service.
-Envoyé par le service de messagerie texte de Bell Mobilité.
-----------------------------------------------------------------
diff --git a/actionmailer/test/fixtures/raw_email6 b/actionmailer/test/fixtures/raw_email6
deleted file mode 100644
index 8e37bd7..0000000
--- a/actionmailer/test/fixtures/raw_email6
+++ /dev/null
@@ -1,20 +0,0 @@
-Return-Path: <xxx at xxxx.xxx>
-Received: from xxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id C1B953B4CB6 for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:05 -0500
-Received: from SMS-GTYxxx.xxxx.xxx by xxx.xxxx.xxx with ESMTP id ca for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:04 -0500
-Received: from xxx.xxxx.xxx by SMS-GTYxxx.xxxx.xxx with ESMTP id j4AKR3r23323 for <xxxxx at Exxx.xxxx.xxx>; Tue, 10 May 2005 15:27:03 -0500
-Date: Tue, 10 May 2005 15:27:03 -0500
-From: xxx at xxxx.xxx
-Sender: xxx at xxxx.xxx
-To: xxxxxxxxxxx at xxxx.xxxx.xxx
-Message-Id: <xxx at xxxx.xxx>
-X-Original-To: xxxxxxxxxxx at xxxx.xxxx.xxx
-Delivered-To: xxx at xxxx.xxx
-Importance: normal
-Content-Type: text/plain; charset=us-ascii
-
-Test test. Hi. Waving. m
-
-----------------------------------------------------------------
-Sent via Bell Mobility's Text Messaging service.
-Envoyé par le service de messagerie texte de Bell Mobilité.
-----------------------------------------------------------------
diff --git a/actionmailer/test/fixtures/raw_email7 b/actionmailer/test/fixtures/raw_email7
deleted file mode 100644
index da64ada..0000000
--- a/actionmailer/test/fixtures/raw_email7
+++ /dev/null
@@ -1,66 +0,0 @@
-Mime-Version: 1.0 (Apple Message framework v730)
-Content-Type: multipart/mixed; boundary=Apple-Mail-13-196941151
-Message-Id: <9169D984-4E0B-45EF-82D4-8F5E53AD7012 at example.com>
-From: foo at example.com
-Subject: testing
-Date: Mon, 6 Jun 2005 22:21:22 +0200
-To: blah at example.com
-
-
---Apple-Mail-13-196941151
-Content-Type: multipart/mixed;
-	boundary=Apple-Mail-12-196940926
-
-
---Apple-Mail-12-196940926
-Content-Transfer-Encoding: quoted-printable
-Content-Type: text/plain;
-	charset=ISO-8859-1;
-	delsp=yes;
-	format=flowed
-
-This is the first part.
-
---Apple-Mail-12-196940926
-Content-Transfer-Encoding: 7bit
-Content-Type: text/x-ruby-script;
-	x-unix-mode=0666;
-	name="test.rb"
-Content-Disposition: attachment;
-	filename=test.rb
-
-puts "testing, testing"
-
---Apple-Mail-12-196940926
-Content-Transfer-Encoding: base64
-Content-Type: application/pdf;
-	x-unix-mode=0666;
-	name="test.pdf"
-Content-Disposition: inline;
-	filename=test.pdf
-
-YmxhaCBibGFoIGJsYWg=
-
---Apple-Mail-12-196940926
-Content-Transfer-Encoding: 7bit
-Content-Type: text/plain;
-	charset=US-ASCII;
-	format=flowed
-
-
-
---Apple-Mail-12-196940926--
-
---Apple-Mail-13-196941151
-Content-Transfer-Encoding: base64
-Content-Type: application/pkcs7-signature;
-	name=smime.p7s
-Content-Disposition: attachment;
-	filename=smime.p7s
-
-jamisSqGSIb3DQEHAqCAMIjamisxCzAJBgUrDgMCGgUAMIAGCSqGSjamisEHAQAAoIIFSjCCBUYw
-ggQujamisQICBD++ukQwDQYJKojamisNAQEFBQAwMTELMAkGA1UEBhMCRjamisAKBgNVBAoTA1RE
-QzEUMBIGjamisxMLVERDIE9DRVMgQ0jamisNMDQwMjI5MTE1OTAxWhcNMDYwMjamisIyOTAxWjCB
-gDELMAkGA1UEjamisEsxKTAnBgNVBAoTIEjamisuIG9yZ2FuaXNhdG9yaXNrIHRpbjamisRuaW5=
-
---Apple-Mail-13-196941151--
diff --git a/actionmailer/test/fixtures/raw_email8 b/actionmailer/test/fixtures/raw_email8
deleted file mode 100644
index 7999636..0000000
--- a/actionmailer/test/fixtures/raw_email8
+++ /dev/null
@@ -1,47 +0,0 @@
-From xxxxxxxxx.xxxxxxx at gmail.com Sun May  8 19:07:09 2005
-Return-Path: <xxxxxxxxx.xxxxxxx at gmail.com>
-Message-ID: <e85734b90505081209eaaa17b at mail.gmail.com>
-Date: Sun, 8 May 2005 14:09:11 -0500
-From: xxxxxxxxx xxxxxxx <xxxxxxxxx.xxxxxxx at gmail.com>
-Reply-To: xxxxxxxxx xxxxxxx <xxxxxxxxx.xxxxxxx at gmail.com>
-To: xxxxx xxxx <xxxxx at xxxxxxxxx.com>
-Subject: Fwd: Signed email causes file attachments
-In-Reply-To: <F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13 at mac.com>
-Mime-Version: 1.0
-Content-Type: multipart/mixed;
-	boundary="----=_Part_5028_7368284.1115579351471"
-References: <F6E2D0B4-CC35-4A91-BA4C-C7C712B10C13 at mac.com>
-
-------=_Part_5028_7368284.1115579351471
-Content-Type: text/plain; charset=ISO-8859-1
-Content-Transfer-Encoding: quoted-printable
-Content-Disposition: inline
-
-We should not include these files or vcards as attachments.
-
----------- Forwarded message ----------
-From: xxxxx xxxxxx <xxxxxxxx at xxx.com>
-Date: May 8, 2005 1:17 PM
-Subject: Signed email causes file attachments
-To: xxxxxxx at xxxxxxxxxx.com
-
-
-Hi,
-
-Test attachments oddly encoded with japanese charset.
-
-
-------=_Part_5028_7368284.1115579351471
-Content-Type: application/octet-stream; name*=iso-2022-jp'ja'01%20Quien%20Te%20Dij%8aat.%20Pitbull.mp3
-Content-Transfer-Encoding: base64
-Content-Disposition: attachment
-
-MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIGFDCCAs0w
-ggI2oAMCAQICAw5c+TANBgkqhkiG9w0BAQQFADBiMQswCQYDVQQGEwJaQTElMCMGA1UEChMcVGhh
-d3RlIENvbnN1bHRpbmcgKFB0eSkgTHRkLjEsMCoGA1UEAxMjVGhhd3RlIFBlcnNvbmFsIEZyZWVt
-YWlsIElzc3VpbmcgQ0EwHhcNMDUwMzI5MDkzOTEwWhcNMDYwMzI5MDkzOTEwWjBCMR8wHQYDVQQD
-ExZUaGF3dGUgRnJlZW1haWwgTWVtYmVyMR8wHQYJKoZIhvcNAQkBFhBzbWhhdW5jaEBtYWMuY29t
-MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn90dPsYS3LjfMY211OSYrDQLzwNYPlAL
-7+/0XA+kdy8/rRnyEHFGwhNCDmg0B6pxC7z3xxJD/8GfCd+IYUUNUQV5m9MkxfP9pTVXZVIYLaBw
-------=_Part_5028_7368284.1115579351471--
-
diff --git a/actionmailer/test/fixtures/raw_email9 b/actionmailer/test/fixtures/raw_email9
deleted file mode 100644
index 02ea0b0..0000000
--- a/actionmailer/test/fixtures/raw_email9
+++ /dev/null
@@ -1,28 +0,0 @@
-Received: from xxx.xxx.xxx ([xxx.xxx.xxx.xxx] verified)
-  by xxx.com (CommuniGate Pro SMTP 4.2.8)
-  with SMTP id 2532598 for xxx at xxx.com; Wed, 23 Feb 2005 17:51:49 -0500
-Received-SPF: softfail
- receiver=xxx.com; client-ip=xxx.xxx.xxx.xxx; envelope-from=xxx at xxx.xxx
-quite Delivered-To: xxx at xxx.xxx
-Received: by xxx.xxx.xxx (Wostfix, from userid xxx)
-	  id 0F87F333; Wed, 23 Feb 2005 16:16:17 -0600
-Date: Wed, 23 Feb 2005 18:20:17 -0400
-From: "xxx xxx" <xxx at xxx.xxx>
-Message-ID: <4D6AA7EB.6490534 at xxx.xxx>
-To: xxx at xxx.com
-Subject: Stop adware/spyware once and for all.
-X-Scanned-By: MIMEDefang 2.11 (www dot roaringpenguin dot com slash mimedefang)
-
-You are infected with:
-Ad Ware and Spy Ware
-
-Get your free scan and removal download now,
-before it gets any worse.
-
-http://xxx.xxx.info?aid=3D13&?stat=3D4327kdzt
-
-
-
-
-no more? (you will still be infected)
-http://xxx.xxx.info/discon/?xxx@xxx.com
diff --git a/actionmailer/test/fixtures/raw_email_quoted_with_0d0a b/actionmailer/test/fixtures/raw_email_quoted_with_0d0a
deleted file mode 100644
index 8a2c25a..0000000
--- a/actionmailer/test/fixtures/raw_email_quoted_with_0d0a
+++ /dev/null
@@ -1,14 +0,0 @@
-Mime-Version: 1.0 (Apple Message framework v730)
-Message-Id: <9169D984-4E0B-45EF-82D4-8F5E53AD7012 at example.com>
-From: foo at example.com
-Subject: testing
-Date: Mon, 6 Jun 2005 22:21:22 +0200
-To: blah at example.com
-Content-Transfer-Encoding: quoted-printable
-Content-Type: text/plain
-
-A fax has arrived from remote ID ''.=0D=0A-----------------------=
--------------------------------------=0D=0ATime: 3/9/2006 3:50:52=
- PM=0D=0AReceived from remote ID: =0D=0AInbound user ID XXXXXXXXXX, r=
-outing code XXXXXXXXX=0D=0AResult: (0/352;0/0) Successful Send=0D=0AP=
-age record: 1 - 1=0D=0AElapsed time: 00:58 on channel 11=0D=0A
diff --git a/actionmailer/test/fixtures/raw_email_with_invalid_characters_in_content_type b/actionmailer/test/fixtures/raw_email_with_invalid_characters_in_content_type
deleted file mode 100644
index a8ff7ed..0000000
--- a/actionmailer/test/fixtures/raw_email_with_invalid_characters_in_content_type
+++ /dev/null
@@ -1,104 +0,0 @@
-Return-Path: <mikel.other at baci>
-Received: from some.isp.com by baci with ESMTP id 632BD5758 for <mikel.lindsaar at baci>; Sun, 21 Oct 2007 19:38:21 +1000
-Date: Sun, 21 Oct 2007 19:38:13 +1000
-From: Mikel Lindsaar <mikel.other at baci>
-Reply-To: Mikel Lindsaar <mikel.other at baci>
-To: mikel.lindsaar at baci
-Message-Id: <009601c813c6$19df3510$0437d30a at mikel091a>
-Subject: Testing outlook
-Mime-Version: 1.0
-Content-Type: multipart/alternative; boundary=----=_NextPart_000_0093_01C81419.EB75E850
-Delivered-To: mikel.lindsaar at baci
-X-Mimeole: Produced By Microsoft MimeOLE V6.00.2900.3138
-X-Msmail-Priority: Normal
-
-This is a multi-part message in MIME format.
-
-
-------=_NextPart_000_0093_01C81419.EB75E850
-Content-Type: text/plain; charset=iso-8859-1
-Content-Transfer-Encoding: Quoted-printable
-
-Hello
-This is an outlook test
-
-So there.
-
-Me.
-
-------=_NextPart_000_0093_01C81419.EB75E850
-Content-Type: text/html; charset=iso-8859-1
-Content-Transfer-Encoding: Quoted-printable
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-<HTML><HEAD>
-<META http-equiv=3DContent-Type content=3D"text/html; =
-charset=3Diso-8859-1">
-<META content=3D"MSHTML 6.00.6000.16525" name=3DGENERATOR>
-<STYLE></STYLE>
-</HEAD>
-<BODY bgColor=3D#ffffff>
-<DIV><FONT face=3DArial size=3D2>Hello</FONT></DIV>
-<DIV><FONT face=3DArial size=3D2><STRONG>This is an outlook=20
-test</STRONG></FONT></DIV>
-<DIV><FONT face=3DArial size=3D2><STRONG></STRONG></FONT> </DIV>
-<DIV><FONT face=3DArial size=3D2><STRONG>So there.</STRONG></FONT></DIV>
-<DIV><FONT face=3DArial size=3D2></FONT> </DIV>
-<DIV><FONT face=3DArial size=3D2>Me.</FONT></DIV></BODY></HTML>
-
-
-------=_NextPart_000_0093_01C81419.EB75E850--
-
-
-Return-Path: <mikel.other at baci>
-Received: from some.isp.com by baci with ESMTP id 632BD5758 for <mikel.lindsaar at baci>; Sun, 21 Oct 2007 19:38:21 +1000
-Date: Sun, 21 Oct 2007 19:38:13 +1000
-From: Mikel Lindsaar <mikel.other at baci>
-Reply-To: Mikel Lindsaar <mikel.other at baci>
-To: mikel.lindsaar at baci
-Message-Id: <009601c813c6$19df3510$0437d30a at mikel091a>
-Subject: Testing outlook
-Mime-Version: 1.0
-Content-Type: multipart/alternative; boundary=----=_NextPart_000_0093_01C81419.EB75E850
-Delivered-To: mikel.lindsaar at baci
-X-Mimeole: Produced By Microsoft MimeOLE V6.00.2900.3138
-X-Msmail-Priority: Normal
-
-This is a multi-part message in MIME format.
-
-
-------=_NextPart_000_0093_01C81419.EB75E850
-Content-Type: text/plain; charset=iso-8859-1
-Content-Transfer-Encoding: Quoted-printable
-
-Hello
-This is an outlook test
-
-So there.
-
-Me.
-
-------=_NextPart_000_0093_01C81419.EB75E850
-Content-Type: text/html; charset=iso-8859-1
-Content-Transfer-Encoding: Quoted-printable
-
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-<HTML><HEAD>
-<META http-equiv=3DContent-Type content=3D"text/html; =
-charset=3Diso-8859-1">
-<META content=3D"MSHTML 6.00.6000.16525" name=3DGENERATOR>
-<STYLE></STYLE>
-</HEAD>
-<BODY bgColor=3D#ffffff>
-<DIV><FONT face=3DArial size=3D2>Hello</FONT></DIV>
-<DIV><FONT face=3DArial size=3D2><STRONG>This is an outlook=20
-test</STRONG></FONT></DIV>
-<DIV><FONT face=3DArial size=3D2><STRONG></STRONG></FONT> </DIV>
-<DIV><FONT face=3DArial size=3D2><STRONG>So there.</STRONG></FONT></DIV>
-<DIV><FONT face=3DArial size=3D2></FONT> </DIV>
-<DIV><FONT face=3DArial size=3D2>Me.</FONT></DIV></BODY></HTML>
-
-
-------=_NextPart_000_0093_01C81419.EB75E850--
-
-
diff --git a/actionmailer/test/fixtures/raw_email_with_nested_attachment b/actionmailer/test/fixtures/raw_email_with_nested_attachment
deleted file mode 100644
index 429c408..0000000
--- a/actionmailer/test/fixtures/raw_email_with_nested_attachment
+++ /dev/null
@@ -1,100 +0,0 @@
-From jamis at 37signals.com Thu Feb 22 11:20:31 2007
-Mime-Version: 1.0 (Apple Message framework v752.3)
-Message-Id: <2CCE0408-10C7-4045-9B16-A1C11C31469B at 37signals.com>
-Content-Type: multipart/signed;
-	micalg=sha1;
-	boundary=Apple-Mail-42-587703407;
-	protocol="application/pkcs7-signature"
-To: Jamis Buck <jamis at jamisbuck.org>
-Subject: Testing attachments
-From: Jamis Buck <jamis at 37signals.com>
-Date: Thu, 22 Feb 2007 11:20:31 -0700
-
-
---Apple-Mail-42-587703407
-Content-Type: multipart/mixed;
-	boundary=Apple-Mail-41-587703287
-
-
---Apple-Mail-41-587703287
-Content-Transfer-Encoding: 7bit
-Content-Type: text/plain;
-	charset=US-ASCII;
-	format=flowed
-
-Here is a test of an attachment via email.
-
-- Jamis
-
-
---Apple-Mail-41-587703287
-Content-Transfer-Encoding: base64
-Content-Type: image/png;
-	x-unix-mode=0644;
-	name=byo-ror-cover.png
-Content-Disposition: inline;
-	filename=truncated.png
-
-iVBORw0KGgoAAAANSUhEUgAAAKUAAADXCAYAAAB7wZEQAAAABHNCSVQICAgIfAhkiAAAAAlwSFlz
-AAALEgAACxIB0t1+/AAAABd0RVh0Q3JlYXRpb24gVGltZQAxLzI1LzIwMDeD9CJVAAAAGHRFWHRT
-b2Z0d2FyZQBBZG9iZSBGaXJld29ya3NPsx9OAAAyBWlUWHRYTUw6Y29tLmFkb2JlLnhtcDw/eHBh
-Y2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+Cjx4OnhtcG1l
-dGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDQuMS1j
-MDIwIDEuMjU1NzE2LCBUdWUgT2N0IDEwIDIwMDYgMjM6MTY6MzQiPgogICA8cmRmOlJERiB4bWxu
-czpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAg
-ICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczp4YXA9Imh0
-dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iPgogICAgICAgICA8eGFwOkNyZWF0b3JUb29sPkFk
-b2JlIEZpcmV3b3JrcyBDUzM8L3hhcDpDcmVhdG9yVG9vbD4KICAgICAgICAgPHhhcDpDcmVhdGVE
-YXRlPjIwMDctMDEtMjVUMDU6Mjg6MjFaPC94YXA6Q3JlYXRlRGF0ZT4KICAgICAgICAgPHhhcDpN
-b2RpZnlEYXRlPjIwMDctMDEtMjVUMDU6Mjg6MjFaPC94YXA6TW9kaWZ5RGF0ZT4KICAgICAgPC9y
-ZGY6RGVzY3JpcHRpb24+CiAgICAgIDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiCiAgICAg
-ICAgICAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyI+CiAgICAg
-ICAgIDxkYzpmb3JtYXQ+aW1hZ2UvcG5nPC9kYzpmb3JtYXQ+CiAgICAgIDwvcmRmOkRlc2NyaXB0
-hhojpmnJMfaYFmSkXWg5PGCmHXVj/c9At0hSK2xGdd8F3muk0VFjb4f5Ue0ksQ8qAcq0delaXhdb
-DjKNnF+3B3t9kObZYmk7AZgWYqO9anpR3wpM9sQ5XslB9a+kWyTtNb0fOmudzGHfPFBQDKesyycm
-DBL7Cw5bXjIEuci+SSOm/LYnXDZu6iuPEj8lYBb+OU8xx1f9m+e5rhJiYKqjo5vHfiZp+VUkW9xc
-Ufd6JHNWc47PkQqb9ie3SLEZB/ZqyAssiqURY+G35iOMZUrHbasHnb80QAPv9FHtAbJIyro7bi5b
-ai2TEAKen5+LJNWrglZjm3UbZvt7KryA2J5b5J1jZF8kL6GzvG1Zqx54Y1y7J7n20wMOt9frG2sW
-uwGP07kNz3732vf6bfvAvLldfS+9fts2euXY37D+R29FGZdlnhzV4TTFmPJduBP2RbNNua4rTqcT
-Qt7Xy1KUB0AHSdP5AZQYvHZg7WD1XvYeMO1A9HhZPqMX5KXbMBrn2efxns/ee21674efxz4Tp/fq
-2HZ648dgYaC1i3Vq1IbNPq3PvDTPezY9FaRISjvnzWqdgcWN8EJgjnNq+Z7ktOm9l2Nfth28EZi4
-bG/we5JwxM+Tql47/D/X6b38I8/RyxvxPJrX6zvQbo3h9jyJx+C0ALX327QETHl5eYlaYCT5rPTb
-+5/rAq26t3lKIxV/p88hq6ptngdgCzoPjJqndiLfc/6y5A14WeDFGNPct4iUsJBV2bYzLEV7m83s
-6Rp63VPhHKC/g/LzaU9qexJRr56043JWinqAtfZqsSm1sjoznthl54dtCqv+uL4nIY+oYWuc3+nH
-kGfn8b0HQpvOYLQAZUDanbJs3jQhITZEgdarZK+cO6ySlL13rut5nFaN23s7u3Snz6eRPTkCoc2/
-Vp1zHfZVFpZ87FiMVLV1iqyK5rlzfji2GzjfDsodlD+Weo5UD4h6PwKqzQMqID0tq2VjjFVSMpis
-ZLRAs7sePZBZAHI+gIanB8I7MD+femAceeUe2Kxa5jS950kZ1p5eNEdeX1+jFmSpZ+1EdWCsDcne
-NPNgUHNw3aYpnzv9PGTX0uo94EtN9qq1rOdxe3kc79T8ukeHJJ8Fnxej6qlylbLLsjQLOy6Xy2a1
-kefs/N+nM7+S7IG5/E5Yc7F003pWErLjbH0O5cGadiMptSB/DZ5U5DI9yeg5MFYyMj8lC/Y7/Xjq
-OZlWcnpg9aQfXz2HRq+Wn5xOp6gN8tWq8R44e2pfyzLYemEgprst+XXk2Zj2nXlbsG05BprndTMv
-C3QRaXczshhVsHnMgfYn80Y2g5JureA6wBasPeP7LkE/jvZMJAaf/g/U2RelHsisvan5FqweIAHg
-Pwc7L68GxvVDAAAAAElFTkSuQmCC
-
---Apple-Mail-41-587703287--
-
---Apple-Mail-42-587703407
-Content-Transfer-Encoding: base64
-Content-Type: application/pkcs7-signature;
-	name=smime.p7s
-Content-Disposition: attachment;
-	filename=smime.p7s
-
-MIAGCSqGSIb3DQEHAqCAMIACAQExCzAJBgUrDgMCGgUAMIAGCSqGSIb3DQEHAQAAoIIGJzCCAuAw
-ggJJoAMCAQICEFjnFNYXwDEZRWY5EkfzopUwDQYJKoZIhvcNAQEFBQAwYjELMAkGA1UEBhMCWkEx
-JTAjBgNVBAoTHFRoYXd0ZSBDb25zdWx0aW5nIChQdHkpIEx0ZC4xLDAqBgNVBAMTI1RoYXd0ZSBQ
-ZXJzb25hbCBGcmVlbWFpbCBJc3N1aW5nIENBMB4XDTA2MDkxMjE3MDExMloXDTA3MDkxMjE3MDEx
-MlowRTEfMB0GA1UEAxMWVGhhd3RlIEZyZWVtYWlsIE1lbWJlcjEiMCAGCSqGSIb3DQEJARYTamFt
-aXNAMzdzaWduYWxzLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAO2A9JeOFIFJ
-G6z8pTcAldrZ2nMe+Xb1tNrbHgoVzN/QhHXM4qst2Ml93cmFLjMmwG7P9RJeU4oNx+jTqVoBB7NV
-Ne1/o56Do0KhfMZ9iUDQdPLbkZMq4EEpFMdm6PyM3muRKwPhj66iAWe/osCb8DowUK2f66vaRx0Z
-Y0MQHIIrXE02Ta4IfAhIfPqBLkZ4WgTYBHN9vMdYea1jF0GO4gqGk1wqwb3yxv2QMYMbwJ6SI+k/
-ZjkSR/OilTCBhwYLKoZIhvcNAQkQAgsxeKB2MGIxCzAJBgNVBAYTAlpBMSUwIwYDVQQKExxUaGF3
-dGUgQ29uc3VsdGluZyAoUHR5KSBMdGQuMSwwKgYDVQQDEyNUaGF3dGUgUGVyc29uYWwgRnJlZW1h
-aWwgSXNzdWluZyBDQQIQWOcU1hfAMRlFZjkSR/OilTANBgkqhkiG9w0BAQEFAASCAQCfwQiC3v6/
-yleRDGv3bJ4nQYQ+c3mz3+mn3Xi6uU35n3piwxZZaWRdmLyiXPvU+QReHpSf3l2qsEZM3sdE0XF9
-eRul/+QTFJcDNXOEAxG1zC2Gpz+6c6RrX4Ou12Pwkp+pNrZWTSY/mZgdqcArupOBcZi7qBjoWcy5
-wb54dfvSSjrjmqLbkH/E8ww/6gGQuU/xXpAUZgUrTmQHrNKeIdSh5oDkOxFaFWvnmb8Z/2ixKqW/
-Ux6WqamyvBtTs/5YBEtnpZOk+uVoscYEUBhU+DVJ2OSvTdXSivMtBdXmGTsG22k+P1NGUHi/A7ev
-xPaO0uk4V8xyjNlN4HPuGpkrlXwPAAAAAAAA
-
---Apple-Mail-42-587703407--
diff --git a/actionmailer/test/fixtures/raw_email_with_partially_quoted_subject b/actionmailer/test/fixtures/raw_email_with_partially_quoted_subject
deleted file mode 100644
index e86108d..0000000
--- a/actionmailer/test/fixtures/raw_email_with_partially_quoted_subject
+++ /dev/null
@@ -1,14 +0,0 @@
-From jamis at 37signals.com Mon May  2 16:07:05 2005
-Mime-Version: 1.0 (Apple Message framework v622)
-Content-Transfer-Encoding: base64
-Message-Id: <d3b8cf8e49f04480850c28713a1f473e at 37signals.com>
-Content-Type: text/plain;
-  charset=EUC-KR;
-  format=flowed
-To: jamis at 37signals.com
-From: Jamis Buck <jamis at 37signals.com>
-Subject: Re: Test: =?UTF-8?B?Iua8ouWtlyI=?= mid =?UTF-8?B?Iua8ouWtlyI=?= tail
-Date: Mon, 2 May 2005 16:07:05 -0600
-
-tOu6zrrQwMcguLbC+bChwfa3ziwgv+y4rrTCIMfPs6q01MC7ILnPvcC0z7TZLg0KDQrBpiDAzLin
-wLogSmFtaXPA1LTPtNku
diff --git a/actionmailer/test/mailers/proc_mailer.rb b/actionmailer/test/mailers/proc_mailer.rb
index 733633b..7e189d8 100644
--- a/actionmailer/test/mailers/proc_mailer.rb
+++ b/actionmailer/test/mailers/proc_mailer.rb
@@ -1,7 +1,8 @@
 class ProcMailer < ActionMailer::Base
   default to: 'system at test.lindsaar.net',
           'X-Proc-Method' => Proc.new { Time.now.to_i.to_s },
-          subject: Proc.new { give_a_greeting }
+          subject: Proc.new { give_a_greeting },
+          'x-has-to-proc' => :symbol
 
   def welcome
     mail
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 3c72f4a..0f0c2d5 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,3 +1,231 @@
+*   Ensure simple_format escapes its html attributes. This fixes CVE-2013-6416
+
+*   Deep Munge the parameters for GET and POST Fixes CVE-2013-6417
+
+*   Stop using i18n's built in HTML error handling.  Fixes: CVE-2013-4491
+
+*   Escape the unit value provided to number_to_currency Fixes CVE-2013-6415
+
+*   Only use valid mime type symbols as cache keys CVE-2013-6414
+
+
+## Rails 4.0.1 (November 01, 2013) ##
+
+*   Respect `SCRIPT_NAME` when using `redirect` with a relative path
+
+    Example:
+        # application routes.rb
+        mount BlogEngine => '/blog'
+
+        # engine routes.rb
+        get '/admin' => redirect('admin/dashboard')
+
+    This now redirects to the path `/blog/admin/dashboard`, whereas before it would've
+    generated an invalid url because there would be no slash between the host name and
+    the path. It also allows redirects to work where the application is deployed to a
+    subdirectory of a website.
+
+    Fixes #7977.
+
+    *Andrew White*
+
+*   Fix `ActionDispatch::RemoteIp::GetIp#calculate_ip` to only check for spoofing
+    attacks if both `HTTP_CLIENT_IP` and `HTTP_X_FORWARDED_FOR` are set.
+
+    Fixes #10844.
+
+    *Tamir Duberstein*
+
+*   Strong parameters should permit nested number as key.
+
+    Fixes #12293.
+
+    *kennyj*
+
+*   Fix `collection_check_boxes` generated hidden input to use the name attribute provided
+    in the options hash.
+
+    *Angel N. Sciortino*
+
+*   Fix some edge cases for AV `select` helper with `:selected` option
+
+    *Bogdan Gusiev*
+
+*   Handle `:namespace` form option in collection labels
+
+    *Vasiliy Ermolovich*
+
+*   Fix an issue where router can't recognize downcased url encoding path.
+
+    Fixes #12269.
+
+    *kennyj*
+
+*   Fix custom flash type definition. Misusage of the `_flash_types` class variable
+    caused an error when reloading controllers with custom flash types.
+
+    Fixes #12057.
+
+    *Ricardo de Cillo*
+
+*   Do not break params filtering on `nil` values.
+
+    Fixes #12149.
+
+    *Vasiliy Ermolovich*
+
+*   Fix `excerpt` when `:separator` is `nil`.
+
+    *Paul Nikitochkin*
+
+*   Make Live Streaming work with basic authentication or builder.
+
+    Fixes #10984.
+
+    *Aaron Patterson*
+
+*   Always use `Rack::Sendfile` to make possible to it be automatically
+    configured by the webserver.
+
+    Fixes #11440.
+
+    *Martin Schürrer*
+
+*   Flag cookies as secure with ignore case in `ActionDispatch::SSL`.
+
+    *Yamagishi Kazutoshi*
+
+*   Don't include STS header in non-HTTPS responses.
+
+    *Geoff Buesing*
+
+*   Fix an issue where rails raise exception about missing helper where it
+    should throw `LoadError`. When helper file exists and only loaded file from
+    this helper does not exist rails should throw LoadError instead of
+    `MissingHelperError`.
+
+    *Piotr Niełacny*
+
+*   Only cache template digests if `config.cache_template_loading` is true.
+
+    *Josh Lauer*, *Justin Ridgewell*
+
+*   Fix an issue where `:if` and `:unless` controller action procs were being run
+    before checking for the correct action in the `:only` and `:unless` options.
+
+    Fixes #11799.
+
+    *Nicholas Jakobsen*
+
+*   Fix an issue where `assert_dom_equal` and `assert_dom_not_equal` were
+    ignoring the passed failure message argument.
+
+    Fixes #11751.
+
+    *Ryan McGeary*
+
+*   Fix `current_page?` when the URL contains escaped characters and the
+    original URL is using the hexadecimal lowercased.
+
+    *Rafael Mendonça França*
+
+*   Allow `REMOTE_ADDR`, `HTTP_HOST` and `HTTP_USER_AGENT` to be overridden from
+    the environment passed into `ActionDispatch::TestRequest.new`.
+
+    Fixes #11590.
+
+    *Andrew White*
+
+*   Fix `text_area` to behave like `text_field` when `nil` is given as
+    value.
+
+    Before:
+
+        f.text_field :field, value: nil #=> <input value="">
+        f.text_area :field, value: nil  #=> <textarea>value of field</textarea>
+
+    After:
+
+        f.text_area :field, value: nil  #=> <textarea></textarea>
+
+    *Joel Cogen*
+
+*   Fix an issue where Journey was failing to clear the named routes hash when the
+    routes were reloaded and since it doesn't overwrite existing routes then if a
+    route changed but wasn't renamed it kept the old definition. This was being
+    masked by the optimised url helpers so it only became apparent when passing an
+    options hash to the url helper.
+
+    *Andrew White*
+
+*   Skip routes pointing to a redirect or mounted application when generating urls
+    using an options hash as they aren't relevant and generate incorrect urls.
+
+    Fixes #8018.
+
+    *Andrew White*
+
+*   Fix default rendered format problem when calling `render` without `:content_type` option.
+    It should return `:html`.
+
+    Fixes #11393.
+
+    *Gleb Mazovetskiy*, *Oleg*, *kennyj*
+
+*   Fix `ActionDispatch::ParamsParser#parse_formatted_parameters` to rewind body input stream on
+    parsing json params.
+
+    Fixes #11345.
+
+    *Yuri Bol*, *Paul Nikitochkin*
+
+*   Fix `link_to` with block and url hashes.
+
+    Before:
+
+        link_to(action: 'bar', controller: 'foo') { content_tag(:span, 'Example site') }
+        # => "<a action=\"bar\" controller=\"foo\"><span>Example site</span></a>"
+
+    After:
+
+        link_to(action: 'bar', controller: 'foo') { content_tag(:span, 'Example site') }
+        # => "<a href=\"/foo/bar\"><span>Example site</span></a>"
+
+    *Murahashi Sanemat Kenichi*
+
+*   Fix "Stack Level Too Deep" error when redering recursive partials.
+
+    Fixes #11340.
+
+    *Rafael Mendonça França*
+
+*   Pick `DateField` `DateTimeField` and `ColorField` values from stringified options allowing use of symbol keys with helpers.
+
+    *Jon Rowe*
+
+*   Fix `Mime::Type.parse` when bad accepts header is looked up. Previously it
+    was setting `request.formats` with an array containing a `nil` value, which
+    raised an error when setting the controller formats.
+
+    Fixes #10965.
+
+    *Becker*
+
+*   Always escape the result of `link_to_unless` method.
+
+    Before:
+
+        link_to_unless(true, '<b>Showing</b>', 'github.com')
+        # => "<b>Showing</b>"
+
+    After:
+
+        link_to_unless(true, '<b>Showing</b>', 'github.com')
+        # => "<b>Showing</b>"
+
+    *dtaniwaki*
+
+
 ## Rails 4.0.0 (June 25, 2013) ##
 
 *   Merge `:action` from routing scope and assign endpoint if both `:controller`
@@ -30,6 +258,10 @@
 
     *David Celis*
 
+*   Add `has_named_route?(route_name)` to the mapper API.
+
+    *José Valim*
+
 *   Fix an issue where partials with a number in the filename weren't being digested for cache dependencies.
 
     *Bryan Ricker*
diff --git a/actionpack/README.rdoc b/actionpack/README.rdoc
index 29a7fcf..f730a87 100644
--- a/actionpack/README.rdoc
+++ b/actionpack/README.rdoc
@@ -37,7 +37,7 @@ The latest version of Action Pack can be installed with RubyGems:
 
 Source code can be downloaded as part of the Rails project on GitHub
 
-* https://github.com/rails/rails/tree/master/actionpack
+* https://github.com/rails/rails/tree/4-0-stable/actionpack
 
 
 == License
diff --git a/actionpack/Rakefile b/actionpack/Rakefile
index ba7956c..7254d78 100644
--- a/actionpack/Rakefile
+++ b/actionpack/Rakefile
@@ -2,6 +2,8 @@ require 'rake/testtask'
 require 'rake/packagetask'
 require 'rubygems/package_task'
 
+test_files = Dir.glob('test/{abstract,controller,dispatch,template,assertions,journey,routing}/**/*_test.rb')
+
 desc "Default Task"
 task :default => :test
 
@@ -15,18 +17,22 @@ Rake::TestTask.new(:test_action_pack) do |t|
 
   # make sure we include the tests in alphabetical order as on some systems
   # this will not happen automatically and the tests (as a whole) will error
-  t.test_files = Dir.glob('test/{abstract,controller,dispatch,template,assertions,journey}/**/*_test.rb').sort
+  t.test_files = test_files.sort
 
   t.warning = true
   t.verbose = true
 end
 
 namespace :test do
-  Rake::TestTask.new(:isolated) do |t|
-    t.libs << 'test'
-    t.pattern = 'test/ts_isolated.rb'
+  task :isolated do
+    ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
+    test_files.all? do |file|
+      sh(ruby, '-w', '-Ilib:test', file)
+    end or raise "Failures"
   end
+end
 
+namespace :test do
   Rake::TestTask.new(:template) do |t|
     t.libs << 'test'
     t.pattern = 'test/template/**/*.rb'
diff --git a/actionpack/lib/abstract_controller/callbacks.rb b/actionpack/lib/abstract_controller/callbacks.rb
index 599fff8..491185b 100644
--- a/actionpack/lib/abstract_controller/callbacks.rb
+++ b/actionpack/lib/abstract_controller/callbacks.rb
@@ -36,7 +36,7 @@ module AbstractController
       def _normalize_callback_option(options, from, to) # :nodoc:
         if from = options[from]
           from = Array(from).map {|o| "action_name == '#{o}'"}.join(" || ")
-          options[to] = Array(options[to]) << from
+          options[to] = Array(options[to]).unshift(from)
         end
       end
 
diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb
index 5ae8c6c..a928205 100644
--- a/actionpack/lib/abstract_controller/helpers.rb
+++ b/actionpack/lib/abstract_controller/helpers.rb
@@ -150,7 +150,12 @@ module AbstractController
           @error = error
           @path  = "helpers/#{path}.rb"
           set_backtrace error.backtrace
-          super("Missing helper file helpers/%s.rb" % path)
+
+          if error.path =~ /^#{path}(\.rb)?$/
+            super("Missing helper file helpers/%s.rb" % path)
+          else
+            raise error
+          end
         end
       end
 
diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb
index 971c418..c623d7e 100644
--- a/actionpack/lib/action_controller/base.rb
+++ b/actionpack/lib/action_controller/base.rb
@@ -59,7 +59,7 @@ module ActionController
   #   <input type="text" name="post[address]" value="hyacintvej">
   #
   # A request stemming from a form holding these inputs will include <tt>{ "post" => { "name" => "david", "address" => "hyacintvej" } }</tt>.
-  # If the address input had been named "post[address][street]", the params would have included
+  # If the address input had been named <tt>post[address][street]</tt>, the params would have included
   # <tt>{ "post" => { "address" => { "street" => "hyacintvej" } } }</tt>. There's no limit to the depth of the nesting.
   #
   # == Sessions
diff --git a/actionpack/lib/action_controller/metal/flash.rb b/actionpack/lib/action_controller/metal/flash.rb
index b078beb..875315e 100644
--- a/actionpack/lib/action_controller/metal/flash.rb
+++ b/actionpack/lib/action_controller/metal/flash.rb
@@ -20,7 +20,7 @@ module ActionController #:nodoc:
           end
           helper_method type
 
-          _flash_types << type
+          self._flash_types += [type]
         end
       end
     end
diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb
index 4470322..a189357 100644
--- a/actionpack/lib/action_controller/metal/strong_parameters.rb
+++ b/actionpack/lib/action_controller/metal/strong_parameters.rb
@@ -201,6 +201,7 @@ module ActionController
     # You may declare that the parameter should be an array of permitted scalars
     # by mapping it to an empty array:
     #
+    #   params = ActionController::Parameters.new(tags: ['rails', 'parameters'])
     #   params.permit(tags: [])
     #
     # You can also use +permit+ on nested parameters, like:
@@ -328,7 +329,7 @@ module ActionController
       def each_element(object)
         if object.is_a?(Array)
           object.map { |el| yield el }.compact
-        elsif object.is_a?(Hash) && object.keys.all? { |k| k =~ /\A-?\d+\z/ }
+        elsif fields_for_style?(object)
           hash = object.class.new
           object.each { |k,v| hash[k] = yield v }
           hash
@@ -337,6 +338,10 @@ module ActionController
         end
       end
 
+      def fields_for_style?(object)
+        object.is_a?(Hash) && object.all? { |k, v| k =~ /\A-?\d+\z/ && v.is_a?(Hash) }
+      end
+
       def unpermitted_parameters!(params)
         unpermitted_keys = unpermitted_keys(params)
         if unpermitted_keys.any?
@@ -415,7 +420,7 @@ module ActionController
 
         # Slicing filters out non-declared keys.
         slice(*filter.keys).each do |key, value|
-          return unless value
+          next unless value
 
           if filter[key] == EMPTY_ARRAY
             # Declaration { comment_ids: [] }.
diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb
index 186be38..0cbbbbe 100644
--- a/actionpack/lib/action_controller/test_case.rb
+++ b/actionpack/lib/action_controller/test_case.rb
@@ -552,7 +552,7 @@ module ActionController
         parameters ||= {}
         controller_class_name = @controller.class.anonymous? ?
           "anonymous" :
-          @controller.class.name.underscore.sub(/_controller$/, '')
+          @controller.class.controller_path
 
         @request.assign_parameters(@routes, controller_class_name, action.to_s, parameters)
 
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index f29ad35..43cd91d 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -179,7 +179,7 @@ module Mime
       def parse(accept_header)
         if accept_header !~ /,/
           accept_header = accept_header.split(PARAMETER_SEPARATOR_REGEXP).first
-          parse_trailing_star(accept_header) || [Mime::Type.lookup(accept_header)]
+          parse_trailing_star(accept_header) || [Mime::Type.lookup(accept_header)].compact
         else
           list, index = AcceptList.new, 0
           accept_header.split(',').each do |header|
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index ebd87c4..ba04000 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -271,7 +271,7 @@ module ActionDispatch
 
     # Override Rack's GET method to support indifferent access
     def GET
-      @env["action_dispatch.request.query_parameters"] ||= (normalize_encode_params(super) || {})
+      @env["action_dispatch.request.query_parameters"] ||= deep_munge((normalize_encode_params(super) || {}))
     rescue TypeError => e
       raise ActionController::BadRequest.new(:query, e)
     end
@@ -279,7 +279,7 @@ module ActionDispatch
 
     # Override Rack's POST method to support indifferent access
     def POST
-      @env["action_dispatch.request.request_parameters"] ||= (normalize_encode_params(super) || {})
+      @env["action_dispatch.request.request_parameters"] ||= deep_munge((normalize_encode_params(super) || {}))
     rescue TypeError => e
       raise ActionController::BadRequest.new(:request, e)
     end
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index 60a2ccc..ab49300 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -198,7 +198,9 @@ module ActionDispatch # :nodoc:
       if body.respond_to?(:to_path)
         @stream = body
       else
-        @stream = build_buffer self, munge_body_object(body)
+        synchronize do
+          @stream = build_buffer self, munge_body_object(body)
+        end
       end
     end
 
diff --git a/actionpack/lib/action_dispatch/journey/formatter.rb b/actionpack/lib/action_dispatch/journey/formatter.rb
index a732e57..66f82d3 100644
--- a/actionpack/lib/action_dispatch/journey/formatter.rb
+++ b/actionpack/lib/action_dispatch/journey/formatter.rb
@@ -18,7 +18,11 @@ module ActionDispatch
 
         match_route(name, constraints) do |route|
           parameterized_parts = extract_parameterized_parts(route, options, recall, parameterize)
-          next if !name && route.requirements.empty? && route.parts.empty?
+
+          # Skip this route unless a name has been provided or it is a
+          # standard Rails route since we can't determine whether an options
+          # hash passed to url_for matches a Rack application or a redirect.
+          next unless name || route.dispatcher?
 
           missing_keys = missing_keys(route, parameterized_parts)
           next unless missing_keys.empty?
diff --git a/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb b/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb
index da0cddd..971cb34 100644
--- a/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb
+++ b/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb
@@ -9,8 +9,8 @@ module ActionDispatch
         attr_reader :memos
 
         def initialize
-          @regexp_states = Hash.new { |h,k| h[k] = {} }
-          @string_states = Hash.new { |h,k| h[k] = {} }
+          @regexp_states = {}
+          @string_states = {}
           @accepting     = {}
           @memos         = Hash.new { |h,k| h[k] = [] }
         end
@@ -111,14 +111,8 @@ module ActionDispatch
         end
 
         def []=(from, to, sym)
-          case sym
-          when String
-            @string_states[from][sym] = to
-          when Regexp
-            @regexp_states[from][sym] = to
-          else
-            raise ArgumentError, 'unknown symbol: %s' % sym.class
-          end
+          to_mappings = states_hash_for(sym)[from] ||= {}
+          to_mappings[sym] = to
         end
 
         def states
@@ -137,18 +131,35 @@ module ActionDispatch
 
         private
 
+          def states_hash_for(sym)
+            case sym
+            when String
+              @string_states
+            when Regexp
+              @regexp_states
+            else
+              raise ArgumentError, 'unknown symbol: %s' % sym.class
+            end
+          end
+
           def move_regexp(t, a)
             return [] if t.empty?
 
             t.map { |s|
-              @regexp_states[s].map { |re, v| re === a ? v : nil }
+              if states = @regexp_states[s]
+                states.map { |re, v| re === a ? v : nil }
+              end
             }.flatten.compact.uniq
           end
 
           def move_string(t, a)
             return [] if t.empty?
 
-            t.map { |s| @string_states[s][a] }.compact
+            t.map do |s|
+              if states = @string_states[s]
+                states[a]
+              end
+            end.compact
           end
       end
     end
diff --git a/actionpack/lib/action_dispatch/journey/route.rb b/actionpack/lib/action_dispatch/journey/route.rb
index 50e1853..c8eb0f6 100644
--- a/actionpack/lib/action_dispatch/journey/route.rb
+++ b/actionpack/lib/action_dispatch/journey/route.rb
@@ -16,6 +16,14 @@ module ActionDispatch
         @app         = app
         @path        = path
 
+        # Unwrap any constraints so we can see what's inside for route generation.
+        # This allows the formatter to skip over any mounted applications or redirects
+        # that shouldn't be matched when using a url_for without a route name.
+        while app.is_a?(Routing::Mapper::Constraints) do
+          app = app.app
+        end
+        @dispatcher  = app.is_a?(Routing::RouteSet::Dispatcher)
+
         @constraints = constraints
         @defaults    = defaults
         @required_defaults = nil
@@ -93,6 +101,10 @@ module ActionDispatch
         end
       end
 
+      def dispatcher?
+        @dispatcher
+      end
+
       def matches?(request)
         constraints.all? do |method, value|
           next true unless request.respond_to?(method)
diff --git a/actionpack/lib/action_dispatch/journey/router/utils.rb b/actionpack/lib/action_dispatch/journey/router/utils.rb
index 462f1a1..4b03cbb 100644
--- a/actionpack/lib/action_dispatch/journey/router/utils.rb
+++ b/actionpack/lib/action_dispatch/journey/router/utils.rb
@@ -7,15 +7,18 @@ module ActionDispatch
         # Normalizes URI path.
         #
         # Strips off trailing slash and ensures there is a leading slash.
+        # Also converts downcase url encoded string to uppercase.
         #
         #   normalize_path("/foo")  # => "/foo"
         #   normalize_path("/foo/") # => "/foo"
         #   normalize_path("foo")   # => "/foo"
         #   normalize_path("")      # => "/"
+        #   normalize_path("/%ab")  # => "/%AB"
         def self.normalize_path(path)
           path = "/#{path}"
           path.squeeze!('/')
           path.sub!(%r{/+\Z}, '')
+          path.gsub!(/(%[a-f0-9]{2})/) { $1.upcase }
           path = '/' if path == ''
           path
         end
diff --git a/actionpack/lib/action_dispatch/journey/routes.rb b/actionpack/lib/action_dispatch/journey/routes.rb
index a99d6d0..80e3818 100644
--- a/actionpack/lib/action_dispatch/journey/routes.rb
+++ b/actionpack/lib/action_dispatch/journey/routes.rb
@@ -30,6 +30,7 @@ module ActionDispatch
 
       def clear
         routes.clear
+        named_routes.clear
       end
 
       def partitioned_routes
diff --git a/actionpack/lib/action_dispatch/journey/visitors.rb b/actionpack/lib/action_dispatch/journey/visitors.rb
index 2964d80..c0be167 100644
--- a/actionpack/lib/action_dispatch/journey/visitors.rb
+++ b/actionpack/lib/action_dispatch/journey/visitors.rb
@@ -1,10 +1,13 @@
 # encoding: utf-8
+
+require 'thread_safe'
+
 module ActionDispatch
   module Journey # :nodoc:
     module Visitors # :nodoc:
       class Visitor # :nodoc:
-        DISPATCH_CACHE = Hash.new { |h,k|
-          h[k] = "visit_#{k}"
+        DISPATCH_CACHE = ThreadSafe::Cache.new { |h,k|
+          h[k] = :"visit_#{k}"
         }
 
         def accept(node)
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index d055acb..3ccd0c9 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -160,7 +160,7 @@ module ActionDispatch
           end
       end
 
-      # Returns the +signed+ or +encrypted jar, preferring +encrypted+ if +secret_key_base+ is set.
+      # Returns the +signed+ or +encrypted+ jar, preferring +encrypted+ if +secret_key_base+ is set.
       # Used by ActionDispatch::Session::CookieStore to avoid the need to introduce new cookie stores.
       def signed_or_encrypted
         @signed_or_encrypted ||=
diff --git a/actionpack/lib/action_dispatch/middleware/params_parser.rb b/actionpack/lib/action_dispatch/middleware/params_parser.rb
index 0fa1e9b..4d5b79f 100644
--- a/actionpack/lib/action_dispatch/middleware/params_parser.rb
+++ b/actionpack/lib/action_dispatch/middleware/params_parser.rb
@@ -41,7 +41,7 @@ module ActionDispatch
         when Proc
           strategy.call(request.raw_post)
         when :json
-          data = ActiveSupport::JSON.decode(request.body)
+          data = ActiveSupport::JSON.decode(request.raw_post)
           data = {:_json => data} unless data.is_a?(Hash)
           request.deep_munge(data).with_indifferent_access
         else
diff --git a/actionpack/lib/action_dispatch/middleware/remote_ip.rb b/actionpack/lib/action_dispatch/middleware/remote_ip.rb
index 8879291..57bc6d5 100644
--- a/actionpack/lib/action_dispatch/middleware/remote_ip.rb
+++ b/actionpack/lib/action_dispatch/middleware/remote_ip.rb
@@ -143,7 +143,7 @@ module ActionDispatch
         # proxies with incompatible IP header conventions, and there is no way
         # for us to determine which header is the right one after the fact.
         # Since we have no idea, we give up and explode.
-        should_check_ip = @check_ip && client_ips.last
+        should_check_ip = @check_ip && client_ips.last && forwarded_ips.last
         if should_check_ip && !forwarded_ips.include?(client_ips.last)
           # We don't know which came from the proxy, and which from the user
           raise IpSpoofAttackError, "IP spoofing attack?! " +
diff --git a/actionpack/lib/action_dispatch/middleware/ssl.rb b/actionpack/lib/action_dispatch/middleware/ssl.rb
index 9e03cbf..8d5ab19 100644
--- a/actionpack/lib/action_dispatch/middleware/ssl.rb
+++ b/actionpack/lib/action_dispatch/middleware/ssl.rb
@@ -36,8 +36,7 @@ module ActionDispatch
         url.scheme = "https"
         url.host   = @host if @host
         url.port   = @port if @port
-        headers    = hsts_headers.merge('Content-Type' => 'text/html',
-                                        'Location'     => url.to_s)
+        headers    = { 'Content-Type' => 'text/html', 'Location' => url.to_s }
 
         [301, headers, []]
       end
@@ -58,7 +57,7 @@ module ActionDispatch
           cookies = cookies.split("\n")
 
           headers['Set-Cookie'] = cookies.map { |cookie|
-            if cookie !~ /;\s+secure(;|$)/
+            if cookie !~ /;\s+secure(;|$)/i
               "#{cookie}; secure"
             else
               cookie
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index df2818b..288ce3e 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -515,6 +515,11 @@ module ActionDispatch
           end
         end
 
+        # Query if the following named route was already defined.
+        def has_named_route?(name)
+          @set.named_routes.routes[name.to_sym]
+        end
+
         private
           def app_name(app)
             return unless app.respond_to?(:routes)
diff --git a/actionpack/lib/action_dispatch/routing/redirection.rb b/actionpack/lib/action_dispatch/routing/redirection.rb
index d751e04..2ec8abd 100644
--- a/actionpack/lib/action_dispatch/routing/redirection.rb
+++ b/actionpack/lib/action_dispatch/routing/redirection.rb
@@ -30,6 +30,10 @@ module ActionDispatch
         uri.host   ||= req.host
         uri.port   ||= req.port unless req.standard_port?
 
+        if relative_path?(uri.path)
+          uri.path = "#{req.script_name}/#{uri.path}"
+        end
+
         body = %(<html><body>You are being <a href="#{ERB::Util.h(uri.to_s)}">redirected</a>.</body></html>)
 
         headers = {
@@ -48,6 +52,11 @@ module ActionDispatch
       def inspect
         "redirect(#{status})"
       end
+
+      private
+        def relative_path?(path)
+          path && !path.empty? && path[0] != '/'
+        end
     end
 
     class PathRedirect < Redirect
@@ -81,6 +90,11 @@ module ActionDispatch
           url_options[:path] = (url_options[:path] % escape_path(params))
         end
 
+        if relative_path?(url_options[:path])
+          url_options[:path] = "/#{url_options[:path]}"
+          url_options[:script_name] = request.script_name
+        end
+
         ActionDispatch::Http::URL.url_for url_options
       end
 
@@ -104,6 +118,10 @@ module ActionDispatch
       #
       #   get 'docs/:article', to: redirect('/wiki/%{article}')
       #
+      # Note that if you return a path without a leading slash then the url is prefixed with the
+      # current SCRIPT_NAME environment variable. This is typically '/' but may be different in
+      # a mounted engine or where the application is deployed to a subdirectory of a website.
+      #
       # Alternatively you can use one of the other syntaxes:
       #
       # The block version of redirect allows for the easy encapsulation of any logic associated with
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index 3ae9f92..0e5dc1f 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -186,10 +186,16 @@ module ActionDispatch
               klass = Journey::Router::Utils
 
               @path_parts.zip(args) do |part, arg|
+                parameterized_arg = arg.to_param
+
+                if parameterized_arg.nil? || parameterized_arg.empty?
+                  raise_generation_error(args)
+                end
+
                 # Replace each route parameter
                 # e.g. :id for regular parameter or *path for globbing
                 # with ruby string interpolation code
-                path.gsub!(/(\*|:)#{part}/, klass.escape_fragment(arg.to_param))
+                path.gsub!(/(\*|:)#{part}/, klass.escape_fragment(parameterized_arg))
               end
               path
             end
@@ -197,6 +203,25 @@ module ActionDispatch
             def optimize_routes_generation?(t)
               t.send(:optimize_routes_generation?)
             end
+
+            def raise_generation_error(args)
+              parts, missing_keys = [], []
+
+              @path_parts.zip(args) do |part, arg|
+                parameterized_arg = arg.to_param
+
+                if parameterized_arg.nil? || parameterized_arg.empty?
+                  missing_keys << part
+                end
+
+                parts << [part, arg]
+              end
+
+              message = "No route matches #{Hash[parts].inspect}"
+              message << " missing required keys: #{missing_keys.inspect}"
+
+              raise ActionController::UrlGenerationError, message
+            end
           end
 
           def initialize(route, options)
diff --git a/actionpack/lib/action_dispatch/testing/assertions/dom.rb b/actionpack/lib/action_dispatch/testing/assertions/dom.rb
index 8f90a12..241a393 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/dom.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/dom.rb
@@ -7,20 +7,20 @@ module ActionDispatch
       #
       #   # assert that the referenced method generates the appropriate HTML string
       #   assert_dom_equal '<a href="http://www.example.com">Apples</a>', link_to("Apples", "http://www.example.com")
-      def assert_dom_equal(expected, actual, message = "")
+      def assert_dom_equal(expected, actual, message = nil)
         expected_dom = HTML::Document.new(expected).root
         actual_dom   = HTML::Document.new(actual).root
-        assert_equal expected_dom, actual_dom
+        assert_equal expected_dom, actual_dom, message
       end
 
       # The negated form of +assert_dom_equivalent+.
       #
       #   # assert that the referenced method does not generate the specified HTML string
       #   assert_dom_not_equal '<a href="http://www.example.com">Apples</a>', link_to("Oranges", "http://www.example.com")
-      def assert_dom_not_equal(expected, actual, message = "")
+      def assert_dom_not_equal(expected, actual, message = nil)
         expected_dom = HTML::Document.new(expected).root
         actual_dom   = HTML::Document.new(actual).root
-        assert_not_equal expected_dom, actual_dom
+        assert_not_equal expected_dom, actual_dom, message
       end
     end
   end
diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb
index c63778f..57c6788 100644
--- a/actionpack/lib/action_dispatch/testing/test_request.rb
+++ b/actionpack/lib/action_dispatch/testing/test_request.rb
@@ -3,7 +3,11 @@ require 'rack/utils'
 
 module ActionDispatch
   class TestRequest < Request
-    DEFAULT_ENV = Rack::MockRequest.env_for('/')
+    DEFAULT_ENV = Rack::MockRequest.env_for('/',
+      'HTTP_HOST'       => 'test.host',
+      'REMOTE_ADDR'     => '0.0.0.0',
+      'HTTP_USER_AGENT' => 'Rails Testing'
+    )
 
     def self.new(env = {})
       super
@@ -12,10 +16,6 @@ module ActionDispatch
     def initialize(env = {})
       env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
       super(default_env.merge(env))
-
-      self.host        = 'test.host'
-      self.remote_addr = '0.0.0.0'
-      self.user_agent  = 'Rails Testing'
     end
 
     def request_method=(method)
diff --git a/actionpack/lib/action_pack/version.rb b/actionpack/lib/action_pack/version.rb
index c48b12b..d7d5288 100644
--- a/actionpack/lib/action_pack/version.rb
+++ b/actionpack/lib/action_pack/version.rb
@@ -1,7 +1,7 @@
 module ActionPack
   # Returns the version of the currently loaded ActionPack as a Gem::Version
   def self.version
-    Gem::Version.new "4.0.0"
+    Gem::Version.new "4.0.2"
   end
 
   module VERSION #:nodoc:
diff --git a/actionpack/lib/action_view/dependency_tracker.rb b/actionpack/lib/action_view/dependency_tracker.rb
index 45d17be..b2e8334 100644
--- a/actionpack/lib/action_view/dependency_tracker.rb
+++ b/actionpack/lib/action_view/dependency_tracker.rb
@@ -74,7 +74,7 @@ module ActionView
             # render(@topic)         => render("topics/topic")
             # render(topics)         => render("topics/topic")
             # render(message.topics) => render("topics/topic")
-            collect { |name| name.sub(/\A@?([a-z]+\.)*([a-z_]+)\z/) { "#{$2.pluralize}/#{$2.singularize}" } }.
+            collect { |name| name.sub(/\A@?([a-z_]+\.)*([a-z_]+)\z/) { "#{$2.pluralize}/#{$2.singularize}" } }.
 
             # render("headline") => render("message/headline")
             collect { |name| name.include?("/") ? name : "#{directory}/#{name}" }.
diff --git a/actionpack/lib/action_view/digestor.rb b/actionpack/lib/action_view/digestor.rb
index 9324a1a..377563e 100644
--- a/actionpack/lib/action_view/digestor.rb
+++ b/actionpack/lib/action_view/digestor.rb
@@ -1,16 +1,44 @@
 require 'thread_safe'
 require 'action_view/dependency_tracker'
+require 'monitor'
 
 module ActionView
   class Digestor
     cattr_reader(:cache)
-    @@cache = ThreadSafe::Cache.new
+    @@cache          = ThreadSafe::Cache.new
+    @@digest_monitor = Monitor.new
+
+    class << self
+      def digest(name, format, finder, options = {})
+        cache_key = ([name, format] + Array.wrap(options[:dependencies])).join('.')
+        # this is a correctly done double-checked locking idiom
+        # (ThreadSafe::Cache's lookups have volatile semantics)
+        @@cache[cache_key] || @@digest_monitor.synchronize do
+          @@cache.fetch(cache_key) do # re-check under lock
+            compute_and_store_digest(cache_key, name, format, finder, options)
+          end
+        end
+      end
+
+      private
+      def compute_and_store_digest(cache_key, name, format, finder, options) # called under @@digest_monitor lock
+        klass = if options[:partial] || name.include?("/_")
+          # Prevent re-entry or else recursive templates will blow the stack.
+          # There is no need to worry about other threads seeing the +false+ value,
+          # as they will then have to wait for this thread to let go of the @@digest_monitor lock.
+          pre_stored = @@cache.put_if_absent(cache_key, false).nil? # put_if_absent returns nil on insertion
+          PartialDigestor
+        else
+          Digestor
+        end
 
-    def self.digest(name, format, finder, options = {})
-      cache_key = [name, format] + Array.wrap(options[:dependencies])
-      @@cache[cache_key.join('.')] ||= begin
-        klass = options[:partial] || name.include?("/_") ? PartialDigestor : Digestor
-        klass.new(name, format, finder, options).digest
+        digest = klass.new(name, format, finder, options).digest
+        # Store the actual digest if config.cache_template_loading is true
+        @@cache[cache_key] = stored_digest = digest if ActionView::Resolver.caching?
+        digest
+      ensure
+        # something went wrong or ActionView::Resolver.caching? is false, make sure not to corrupt the @@cache
+        @@cache.delete_pair(cache_key, false) if pre_stored && !stored_digest 
       end
     end
 
diff --git a/actionpack/lib/action_view/helpers/date_helper.rb b/actionpack/lib/action_view/helpers/date_helper.rb
index 8fb5eb1..7216f72 100644
--- a/actionpack/lib/action_view/helpers/date_helper.rb
+++ b/actionpack/lib/action_view/helpers/date_helper.rb
@@ -539,7 +539,7 @@ module ActionView
       #   my_date = Time.now + 2.days
       #
       #   # Generates a select field for days that defaults to the day for the date in my_date.
-      #   select_day(my_time)
+      #   select_day(my_date)
       #
       #   # Generates a select field for days that defaults to the number given.
       #   select_day(5)
@@ -549,7 +549,7 @@ module ActionView
       #
       #   # Generates a select field for days that defaults to the day for the date in my_date
       #   # that is named 'due' rather than 'day'.
-      #   select_day(my_time, field_name: 'due')
+      #   select_day(my_date, field_name: 'due')
       #
       #   # Generates a select field for days with a custom prompt. Use <tt>prompt: true</tt> for a
       #   # generic prompt.
diff --git a/actionpack/lib/action_view/helpers/form_helper.rb b/actionpack/lib/action_view/helpers/form_helper.rb
index 36dedf0..002c2ae 100644
--- a/actionpack/lib/action_view/helpers/form_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_helper.rb
@@ -1172,7 +1172,7 @@ module ActionView
     # methods in the +FormHelper+ module. This class, however, allows you to
     # call methods with the model object you are building the form for.
     #
-    # You can create your own custom FormBuilder templates by subclasses this
+    # You can create your own custom FormBuilder templates by subclassing this
     # class. For example:
     #
     #   class MyFormBuilder < ActionView::Helpers::FormBuilder
diff --git a/actionpack/lib/action_view/helpers/form_options_helper.rb b/actionpack/lib/action_view/helpers/form_options_helper.rb
index 719c9c0..82781e7 100644
--- a/actionpack/lib/action_view/helpers/form_options_helper.rb
+++ b/actionpack/lib/action_view/helpers/form_options_helper.rb
@@ -97,14 +97,17 @@ module ActionView
       # Create a select tag and a series of contained option tags for the provided object and method.
       # The option currently held by the object will be selected, provided that the object is available.
       #
-      # There are two possible formats for the choices parameter, corresponding to other helpers' output:
-      #   * A flat collection: see options_for_select
-      #   * A nested collection: see grouped_options_for_select
+      # There are two possible formats for the +choices+ parameter, corresponding to other helpers' output:
+      #
+      # * A flat collection (see +options_for_select+).
+      #
+      # * A nested collection (see +grouped_options_for_select+).
+      #
+      # For example:
       #
-      # Example with @post.person_id => 1:
       #   select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { include_blank: true })
       #
-      # could become:
+      # would become:
       #
       #   <select name="post[person_id]">
       #     <option value=""></option>
@@ -113,6 +116,8 @@ module ActionView
       #     <option value="3">Tobias</option>
       #   </select>
       #
+      # assuming the associated person has ID 1.
+      #
       # This can be used to provide a default set of options in the standard way: before rendering the create form, a
       # new model instance is assigned the default options and bound to @model_name. Usually this model is not saved
       # to the database. Instead, a second model object is created when the create request is received.
@@ -654,7 +659,7 @@ module ActionView
       #
       # Example object structure for use with this method:
       #   class Post < ActiveRecord::Base
-      #     has_and_belongs_to_many :author
+      #     has_and_belongs_to_many :authors
       #   end
       #   class Author < ActiveRecord::Base
       #     has_and_belongs_to_many :posts
diff --git a/actionpack/lib/action_view/helpers/number_helper.rb b/actionpack/lib/action_view/helpers/number_helper.rb
index fda7038..f3914e4 100644
--- a/actionpack/lib/action_view/helpers/number_helper.rb
+++ b/actionpack/lib/action_view/helpers/number_helper.rb
@@ -411,6 +411,7 @@ module ActionView
       def escape_unsafe_delimiters_and_separators(options)
         options[:separator] = ERB::Util.html_escape(options[:separator]) if options[:separator] && !options[:separator].html_safe?
         options[:delimiter] = ERB::Util.html_escape(options[:delimiter]) if options[:delimiter] && !options[:delimiter].html_safe?
+        options[:unit]      = ERB::Util.html_escape(options[:unit]) if options[:unit] && !options[:unit].html_safe?
         options
       end
 
diff --git a/actionpack/lib/action_view/helpers/tags/base.rb b/actionpack/lib/action_view/helpers/tags/base.rb
index 3fe3f4e..8607da3 100644
--- a/actionpack/lib/action_view/helpers/tags/base.rb
+++ b/actionpack/lib/action_view/helpers/tags/base.rb
@@ -119,7 +119,8 @@ module ActionView
           html_options = html_options.stringify_keys
           add_default_name_and_id(html_options)
           options[:include_blank] ||= true unless options[:prompt] || select_not_required?(html_options)
-          select = content_tag("select", add_options(option_tags, options, value(object)), html_options)
+          value = options.fetch(:selected) { value(object) }
+          select = content_tag("select", add_options(option_tags, options, value), html_options)
 
           if html_options["multiple"] && options.fetch(:include_hidden, true)
             tag("input", :disabled => html_options["disabled"], :name => html_options["name"], :type => "hidden", :value => "") + select
diff --git a/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb b/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb
index 52006d8..9b77ebe 100644
--- a/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb
+++ b/actionpack/lib/action_view/helpers/tags/collection_check_boxes.rb
@@ -27,7 +27,8 @@ module ActionView
 
           # Append a hidden field to make sure something will be sent back to the
           # server if all check boxes are unchecked.
-          hidden = @template_object.hidden_field_tag("#{tag_name}[]", "", :id => nil)
+          hidden_name = @html_options[:name] || "#{tag_name}[]"
+          hidden = @template_object.hidden_field_tag(hidden_name, "", :id => nil)
 
           rendered_collection + hidden
         end
diff --git a/actionpack/lib/action_view/helpers/tags/collection_helpers.rb b/actionpack/lib/action_view/helpers/tags/collection_helpers.rb
index cd12dda..41abd72 100644
--- a/actionpack/lib/action_view/helpers/tags/collection_helpers.rb
+++ b/actionpack/lib/action_view/helpers/tags/collection_helpers.rb
@@ -18,7 +18,8 @@ module ActionView
           end
 
           def label(label_html_options={}, &block)
-            @template_object.label(@object_name, @sanitized_attribute_name, @text, label_html_options, &block)
+            html_options = label_html_options.merge(@input_html_options)
+            @template_object.label(@object_name, @sanitized_attribute_name, @text, html_options, &block)
           end
         end
 
diff --git a/actionpack/lib/action_view/helpers/tags/color_field.rb b/actionpack/lib/action_view/helpers/tags/color_field.rb
index d8fc797..bab2835 100644
--- a/actionpack/lib/action_view/helpers/tags/color_field.rb
+++ b/actionpack/lib/action_view/helpers/tags/color_field.rb
@@ -4,7 +4,7 @@ module ActionView
       class ColorField < TextField # :nodoc:
         def render
           options = @options.stringify_keys
-          options["value"] = @options.fetch("value") { validate_color_string(value(object)) }
+          options["value"] = options.fetch("value") { validate_color_string(value(object)) }
           @options = options
           super
         end
diff --git a/actionpack/lib/action_view/helpers/tags/datetime_field.rb b/actionpack/lib/action_view/helpers/tags/datetime_field.rb
index 9a2279c..416d225 100644
--- a/actionpack/lib/action_view/helpers/tags/datetime_field.rb
+++ b/actionpack/lib/action_view/helpers/tags/datetime_field.rb
@@ -4,7 +4,7 @@ module ActionView
       class DatetimeField < TextField # :nodoc:
         def render
           options = @options.stringify_keys
-          options["value"] = @options.fetch("value") { format_date(value(object)) }
+          options["value"] = options.fetch("value") { format_date(value(object)) }
           options["min"] = format_date(options["min"])
           options["max"] = format_date(options["max"])
           @options = options
diff --git a/actionpack/lib/action_view/helpers/tags/label.rb b/actionpack/lib/action_view/helpers/tags/label.rb
index 35d3ba8..180aa9a 100644
--- a/actionpack/lib/action_view/helpers/tags/label.rb
+++ b/actionpack/lib/action_view/helpers/tags/label.rb
@@ -30,6 +30,7 @@ module ActionView
           add_default_name_and_id_for_value(tag_value, name_and_id)
           options.delete("index")
           options.delete("namespace")
+          options.delete("multiple")
           options["for"] = name_and_id["id"] unless options.key?("for")
 
           if block_given?
diff --git a/actionpack/lib/action_view/helpers/tags/text_area.rb b/actionpack/lib/action_view/helpers/tags/text_area.rb
index c81156c..9ee83ee 100644
--- a/actionpack/lib/action_view/helpers/tags/text_area.rb
+++ b/actionpack/lib/action_view/helpers/tags/text_area.rb
@@ -10,7 +10,7 @@ module ActionView
             options["cols"], options["rows"] = size.split("x") if size.respond_to?(:split)
           end
 
-          content_tag("textarea", options.delete('value') || value_before_type_cast(object), options)
+          content_tag("textarea", options.delete("value") { value_before_type_cast(object) }, options)
         end
       end
     end
diff --git a/actionpack/lib/action_view/helpers/tags/text_field.rb b/actionpack/lib/action_view/helpers/tags/text_field.rb
index baa5ff7..e910879 100644
--- a/actionpack/lib/action_view/helpers/tags/text_field.rb
+++ b/actionpack/lib/action_view/helpers/tags/text_field.rb
@@ -5,8 +5,8 @@ module ActionView
         def render
           options = @options.stringify_keys
           options["size"] = options["maxlength"] unless options.key?("size")
-          options["type"]  ||= field_type
-          options["value"] = options.fetch("value"){ value_before_type_cast(object) } unless field_type == "file"
+          options["type"] ||= field_type
+          options["value"] = options.fetch("value") { value_before_type_cast(object) } unless field_type == "file"
           options["value"] &&= ERB::Util.html_escape(options["value"])
           add_default_name_and_id(options)
           tag("input", options)
diff --git a/actionpack/lib/action_view/helpers/text_helper.rb b/actionpack/lib/action_view/helpers/text_helper.rb
index 147f9fd..285d27d 100644
--- a/actionpack/lib/action_view/helpers/text_helper.rb
+++ b/actionpack/lib/action_view/helpers/text_helper.rb
@@ -150,7 +150,7 @@ module ActionView
       def excerpt(text, phrase, options = {})
         return unless text && phrase
 
-        separator = options.fetch(:separator, "")
+        separator = options[:separator] || ''
         phrase    = Regexp.escape(phrase)
         regex     = /#{phrase}/i
 
@@ -169,7 +169,8 @@ module ActionView
         prefix, first_part   = cut_excerpt_part(:first, first_part, separator, options)
         postfix, second_part = cut_excerpt_part(:second, second_part, separator, options)
 
-        prefix + (first_part + separator + phrase + separator + second_part).strip + postfix
+        affix = [first_part, separator, phrase, separator, second_part].join.strip
+        [prefix, affix, postfix].join
       end
 
       # Attempts to pluralize the +singular+ word unless +count+ is 1. If
@@ -265,7 +266,7 @@ module ActionView
           content_tag(wrapper_tag, nil, html_options)
         else
           paragraphs.map { |paragraph|
-            content_tag(wrapper_tag, paragraph, html_options, options[:sanitize])
+            content_tag(wrapper_tag, raw(paragraph), html_options)
           }.join("\n\n").html_safe
         end
       end
diff --git a/actionpack/lib/action_view/helpers/translation_helper.rb b/actionpack/lib/action_view/helpers/translation_helper.rb
index ad8eb47..a1a2beb 100644
--- a/actionpack/lib/action_view/helpers/translation_helper.rb
+++ b/actionpack/lib/action_view/helpers/translation_helper.rb
@@ -1,24 +1,14 @@
 require 'action_view/helpers/tag_helper'
 require 'i18n/exceptions'
 
-module I18n
-  class ExceptionHandler
-    include Module.new {
-      def call(exception, locale, key, options)
-        exception.is_a?(MissingTranslation) && options[:rescue_format] == :html ? super.html_safe : super
-      end
-    }
-  end
-end
-
 module ActionView
   # = Action View Translation Helpers
   module Helpers
     module TranslationHelper
       # Delegates to <tt>I18n#translate</tt> but also performs three additional functions.
       #
-      # First, it'll pass the <tt>rescue_format: :html</tt> option to I18n so that any
-      # thrown +MissingTranslation+ messages will be turned into inline spans that
+      # First, it will ensure that any thrown +MissingTranslation+ messages will be turned 
+      # into inline spans that:
       #
       #   * have a "translation-missing" class set,
       #   * contain the missing key as a title attribute and
@@ -44,8 +34,11 @@ module ActionView
       # naming convention helps to identify translations that include HTML tags so that
       # you know what kind of output to expect when you call translate in a template.
       def translate(key, options = {})
-        options.merge!(:rescue_format => :html) unless options.key?(:rescue_format)
         options[:default] = wrap_translate_defaults(options[:default]) if options[:default]
+
+        # If the user has specified rescue_format then pass it all through, otherwise use
+        # raise and do the work ourselves
+        options[:raise] = true unless options.key?(:raise) || options.key?(:rescue_format)
         if html_safe_translation_key?(key)
           html_safe_options = options.dup
           options.except(*I18n::RESERVED_KEYS).each do |name, value|
@@ -59,6 +52,9 @@ module ActionView
         else
           I18n.translate(scope_key_by_partial(key), options)
         end
+      rescue I18n::MissingTranslationData => e
+        keys = I18n.normalize_keys(e.locale, e.key, e.options[:scope])
+        content_tag('span', keys.last.to_s.titleize, :class => 'translation_missing', :title => "translation missing: #{keys.join('.')}")
       end
       alias :t :translate
 
diff --git a/actionpack/lib/action_view/helpers/url_helper.rb b/actionpack/lib/action_view/helpers/url_helper.rb
index 22059a0..ec5ee4e 100644
--- a/actionpack/lib/action_view/helpers/url_helper.rb
+++ b/actionpack/lib/action_view/helpers/url_helper.rb
@@ -172,7 +172,7 @@ module ActionView
       #   link_to "Visit Other Site", "http://www.rubyonrails.org/", data: { confirm: "Are you sure?" }
       #   # => <a href="http://www.rubyonrails.org/" data-confirm="Are you sure?">Visit Other Site</a>
       def link_to(name = nil, options = nil, html_options = nil, &block)
-        html_options, options = options, name if block_given?
+        html_options, options, name = options, name, block if block_given?
         options ||= {}
 
         html_options = convert_options_to_data_attributes(options, html_options)
@@ -380,7 +380,7 @@ module ActionView
           if block_given?
             block.arity <= 1 ? capture(name, &block) : capture(name, options, html_options, &block)
           else
-            name
+            ERB::Util.html_escape(name)
           end
         else
           link_to(name, options, html_options)
@@ -528,12 +528,13 @@ module ActionView
 
         return false unless request.get? || request.head?
 
-        url_string = url_for(options)
+        url_string = URI.parser.unescape(url_for(options)).force_encoding(Encoding::BINARY)
 
         # We ignore any extra parameters in the request_uri if the
         # submitted url doesn't have any either. This lets the function
         # work with things like ?order=asc
         request_uri = url_string.index("?") ? request.fullpath : request.path
+        request_uri = URI.parser.unescape(request_uri).force_encoding(Encoding::BINARY)
 
         if url_string =~ /^\w+:\/\//
           url_string == "#{request.protocol}#{request.host_with_port}#{request_uri}"
diff --git a/actionpack/lib/action_view/lookup_context.rb b/actionpack/lib/action_view/lookup_context.rb
index f9d5b97..c6ff683 100644
--- a/actionpack/lib/action_view/lookup_context.rb
+++ b/actionpack/lib/action_view/lookup_context.rb
@@ -62,6 +62,13 @@ module ActionView
       @details_keys = ThreadSafe::Cache.new
 
       def self.get(details)
+        if details[:formats]
+          details = details.dup
+          syms    = Set.new Mime::SET.symbols
+          details[:formats] = details[:formats].select { |v|
+            syms.include? v
+          }
+        end
         @details_keys[details] ||= new
       end
 
diff --git a/actionpack/lib/action_view/railtie.rb b/actionpack/lib/action_view/railtie.rb
index e80e0ed..66b05d3 100644
--- a/actionpack/lib/action_view/railtie.rb
+++ b/actionpack/lib/action_view/railtie.rb
@@ -35,5 +35,9 @@ module ActionView
         end
       end
     end
+
+    rake_tasks do
+      load "action_view/tasks/dependencies.rake"
+    end
   end
 end
diff --git a/actionpack/lib/action_view/renderer/template_renderer.rb b/actionpack/lib/action_view/renderer/template_renderer.rb
index 4d5c5db..668831d 100644
--- a/actionpack/lib/action_view/renderer/template_renderer.rb
+++ b/actionpack/lib/action_view/renderer/template_renderer.rb
@@ -11,7 +11,7 @@ module ActionView
       prepend_formats(template.formats)
 
       unless context.rendered_format
-        context.rendered_format = template.formats.first || formats.last
+        context.rendered_format = template.formats.first || formats.first
       end
 
       render_template(template, options[:layout], options[:locals])
diff --git a/actionpack/lib/action_view/tasks/dependencies.rake b/actionpack/lib/action_view/tasks/dependencies.rake
new file mode 100644
index 0000000..1b9426c
--- /dev/null
+++ b/actionpack/lib/action_view/tasks/dependencies.rake
@@ -0,0 +1,17 @@
+namespace :cache_digests do
+  desc 'Lookup nested dependencies for TEMPLATE (like messages/show or comments/_comment.html)'
+  task :nested_dependencies => :environment do
+    abort 'You must provide TEMPLATE for the task to run' unless ENV['TEMPLATE'].present?
+    template, format = ENV['TEMPLATE'].split(".")
+    format ||= :html
+    puts JSON.pretty_generate ActionView::Digestor.new(template, format, ApplicationController.new.lookup_context).nested_dependencies
+  end
+
+  desc 'Lookup first-level dependencies for TEMPLATE (like messages/show or comments/_comment.html)'
+  task :dependencies => :environment do
+    abort 'You must provide TEMPLATE for the task to run' unless ENV['TEMPLATE'].present?
+    template, format = ENV['TEMPLATE'].split(".")
+    format ||= :html
+    puts JSON.pretty_generate ActionView::Digestor.new(template, format, ApplicationController.new.lookup_context).dependencies
+  end
+end
diff --git a/actionpack/test/abstract/.helper_test.rb.swp b/actionpack/test/abstract/.helper_test.rb.swp
new file mode 100644
index 0000000..d029f89
Binary files /dev/null and b/actionpack/test/abstract/.helper_test.rb.swp differ
diff --git a/actionpack/test/abstract/helper_test.rb b/actionpack/test/abstract/helper_test.rb
index 7960e5b..2cc27fb 100644
--- a/actionpack/test/abstract/helper_test.rb
+++ b/actionpack/test/abstract/helper_test.rb
@@ -48,6 +48,14 @@ module AbstractController
       end
     end
 
+    class AbstractInvalidHelpers < AbstractHelpers
+      include ActionController::Helpers
+
+      path = File.join(File.expand_path('../../fixtures', __FILE__), "helpers_missing")
+      $:.unshift(path)
+      self.helpers_path = path
+    end
+
     class TestHelpers < ActiveSupport::TestCase
       def setup
         @controller = AbstractHelpers.new
@@ -97,5 +105,17 @@ module AbstractController
         assert_equal "Hello Default", @controller.response_body
       end
     end
+
+    class InvalidHelpersTest < ActiveSupport::TestCase
+      def test_controller_raise_error_about_real_require_problem
+        e = assert_raise(LoadError) { AbstractInvalidHelpers.helper(:invalid_require) }
+        assert_equal "No such file to load -- very_invalid_file_name", e.message
+      end
+
+      def test_controller_raise_error_about_missing_helper
+        e = assert_raise(Helpers::ClassMethods::MissingHelperError) { AbstractInvalidHelpers.helper(:missing) }
+        assert_equal "Missing helper file helpers/missing_helper.rb", e.message
+      end
+    end
   end
 end
diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb
index 3b79161..586e5e3 100644
--- a/actionpack/test/controller/filters_test.rb
+++ b/actionpack/test/controller/filters_test.rb
@@ -208,6 +208,10 @@ class FilterTest < ActionController::TestCase
     before_filter(ConditionalClassFilter, :ensure_login, Proc.new {|c| c.instance_variable_set(:"@ran_proc_filter1", true)}, :except => :show_without_filter) { |c| c.instance_variable_set(:"@ran_proc_filter2", true)}
   end
 
+  class OnlyConditionalOptionsFilter < ConditionalFilterController
+    before_filter :ensure_login, :only => :index, :if => Proc.new {|c| c.instance_variable_set(:"@ran_conditional_index_proc", true) }
+  end
+
   class ConditionalOptionsFilter < ConditionalFilterController
     before_filter :ensure_login, :if => Proc.new { |c| true }
     before_filter :clean_up_tmp, :if => Proc.new { |c| false }
@@ -636,6 +640,11 @@ class FilterTest < ActionController::TestCase
     assert !assigns["ran_class_filter"]
   end
 
+  def test_running_only_condition_and_conditional_options
+    test_process(OnlyConditionalOptionsFilter, "show")
+    assert_not assigns["ran_conditional_index_proc"]
+  end
+
   def test_running_before_and_after_condition_filters
     test_process(BeforeAndAfterConditionController)
     assert_equal %w( ensure_login clean_up_tmp), assigns["ran_filter"]
diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb
index 3b874a7..c64ffef 100644
--- a/actionpack/test/controller/flash_test.rb
+++ b/actionpack/test/controller/flash_test.rb
@@ -214,6 +214,18 @@ class FlashTest < ActionController::TestCase
     get :redirect_with_foo_flash
     assert_equal "for great justice", @controller.send(:flash)[:foo]
   end
+
+  class SubclassesTestController < TestController; end
+
+  def test_add_flash_type_to_subclasses
+    TestController.add_flash_types :foo
+    assert SubclassesTestController._flash_types.include?(:foo)
+  end
+
+  def test_do_not_add_flash_type_to_parent_class
+    SubclassesTestController.add_flash_types :bar
+    assert_not TestController._flash_types.include?(:bar)
+  end
 end
 
 class FlashIntegrationTest < ActionDispatch::IntegrationTest
diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb
index f7ec6d7..e851cc6 100644
--- a/actionpack/test/controller/integration_test.rb
+++ b/actionpack/test/controller/integration_test.rb
@@ -277,7 +277,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
     end
 
     def redirect
-      redirect_to :action => "get"
+      redirect_to action_url('get')
     end
   end
 
@@ -511,8 +511,8 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest
         end
 
         set.draw do
-          match ':action', :to => controller, :via => [:get, :post]
-          get 'get/:action', :to => controller
+          match ':action', :to => controller, :via => [:get, :post], :as => :action
+          get 'get/:action', :to => controller, :as => :get_action
         end
 
         self.singleton_class.send(:include, set.url_helpers)
diff --git a/actionpack/test/controller/parameters/nested_parameters_test.rb b/actionpack/test/controller/parameters/nested_parameters_test.rb
index 91df527..3b1257e 100644
--- a/actionpack/test/controller/parameters/nested_parameters_test.rb
+++ b/actionpack/test/controller/parameters/nested_parameters_test.rb
@@ -169,4 +169,19 @@ class NestedParametersTest < ActiveSupport::TestCase
 
     assert_filtered_out permitted[:book][:authors_attributes]['-1'], :age_of_death
   end
+
+  test "nested number as key" do
+    params = ActionController::Parameters.new({
+      product: {
+        properties: {
+          '0' => "prop0",
+          '1' => "prop1"
+        }
+      }
+    })
+    params = params.require(:product).permit(:properties => ["0"])
+    assert_not_nil        params[:properties]["0"]
+    assert_nil            params[:properties]["1"]
+    assert_equal "prop0", params[:properties]["0"]
+  end
 end
diff --git a/actionpack/test/controller/parameters/parameters_permit_test.rb b/actionpack/test/controller/parameters/parameters_permit_test.rb
index 437da43..84e007b 100644
--- a/actionpack/test/controller/parameters/parameters_permit_test.rb
+++ b/actionpack/test/controller/parameters/parameters_permit_test.rb
@@ -107,6 +107,15 @@ class ParametersPermitTest < ActiveSupport::TestCase
     assert_equal [], permitted[:id]
   end
 
+  test 'do not break params filtering on nil values' do
+    params = ActionController::Parameters.new(a: 1, b: [1, 2, 3], c: nil)
+
+    permitted = params.permit(:a, c: [], b: [])
+    assert_equal 1, permitted[:a]
+    assert_equal [1, 2, 3], permitted[:b]
+    assert_equal nil, permitted[:c]
+  end
+
   test 'key to empty array: arrays of permitted scalars pass' do
     [['foo'], [1], ['foo', 'bar'], [1, 2, 3]].each do |array|
       params = ActionController::Parameters.new(id: array)
diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb
index 0e5bad7..fd83579 100644
--- a/actionpack/test/controller/render_test.rb
+++ b/actionpack/test/controller/render_test.rb
@@ -32,6 +32,10 @@ class TestControllerWithExtraEtags < ActionController::Base
   def fresh
     render text: "stale" if stale?(etag: '123')
   end
+
+  def array
+    render text: "stale" if stale?(etag: %w(1 2 3))
+  end
 end
 
 class TestController < ActionController::Base
@@ -1085,6 +1089,12 @@ class RenderTest < ActionController::TestCase
     assert_equal '<test>passed formatted html erb</test>', @response.body
   end
 
+  def test_should_render_formatted_html_erb_template_with_bad_accepts_header
+    @request.env["HTTP_ACCEPT"] = "; a=dsf"
+    get :formatted_xml_erb
+    assert_equal '<test>passed formatted html erb</test>', @response.body
+  end
+
   def test_should_render_formatted_html_erb_template_with_faulty_accepts_header
     @request.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, appliction/x-shockwave-flash, */*"
     get :formatted_xml_erb
@@ -1649,7 +1659,6 @@ class LastModifiedRenderTest < ActionController::TestCase
     assert_equal @last_modified, @response.headers['Last-Modified']
   end
 
-
   def test_request_with_bang_gets_last_modified
     get :conditional_hello_with_bangs
     assert_equal @last_modified, @response.headers['Last-Modified']
@@ -1678,7 +1687,7 @@ class EtagRenderTest < ActionController::TestCase
   end
 
   def test_multiple_etags
-    @request.if_none_match = %("#{Digest::MD5.hexdigest(ActiveSupport::Cache.expand_cache_key([ "123", 'ab', :cde, [:f] ]))}")
+    @request.if_none_match = etag(["123", 'ab', :cde, [:f]])
     get :fresh
     assert_response :not_modified
 
@@ -1686,6 +1695,20 @@ class EtagRenderTest < ActionController::TestCase
     get :fresh
     assert_response :success
   end
+
+  def test_array
+    @request.if_none_match = etag([%w(1 2 3), 'ab', :cde, [:f]])
+    get :array
+    assert_response :not_modified
+
+    @request.if_none_match = %("nomatch")
+    get :array
+    assert_response :success
+  end
+
+  def etag(record)
+    Digest::MD5.hexdigest(ActiveSupport::Cache.expand_cache_key(record)).inspect
+  end
 end
 
 
diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb
index f735564..46df1a7 100644
--- a/actionpack/test/controller/routing_test.rb
+++ b/actionpack/test/controller/routing_test.rb
@@ -1904,6 +1904,10 @@ class RackMountIntegrationTests < ActiveSupport::TestCase
     assert_equal({:controller => 'news', :action => 'index'}, @routes.recognize_path(URI.parser.escape('こんにちは/世界'), :method => :get))
   end
 
+  def test_downcased_unicode_path
+    assert_equal({:controller => 'news', :action => 'index'}, @routes.recognize_path(URI.parser.escape('こんにちは/世界').downcase, :method => :get))
+  end
+
   private
     def sort_extras!(extras)
       if extras.length == 2
diff --git a/actionpack/test/dispatch/prefix_generation_test.rb b/actionpack/test/dispatch/prefix_generation_test.rb
index 113608e..e519fff 100644
--- a/actionpack/test/dispatch/prefix_generation_test.rb
+++ b/actionpack/test/dispatch/prefix_generation_test.rb
@@ -31,6 +31,14 @@ module TestGenerationPrefix
             get "/polymorphic_path_for_engine", :to => "inside_engine_generating#polymorphic_path_for_engine"
             get "/conflicting_url", :to => "inside_engine_generating#conflicting"
             get "/foo", :to => "never#invoked", :as => :named_helper_that_should_be_invoked_only_in_respond_to_test
+
+            get "/relative_path_redirect", :to => redirect("foo")
+            get "/relative_option_redirect", :to => redirect(:path => "foo")
+            get "/relative_custom_redirect", :to => redirect { |params, request| "foo" }
+
+            get "/absolute_path_redirect", :to => redirect("/foo")
+            get "/absolute_option_redirect", :to => redirect(:path => "/foo")
+            get "/absolute_custom_redirect", :to => redirect { |params, request| "/foo" }
           end
 
           routes
@@ -182,6 +190,48 @@ module TestGenerationPrefix
       assert_equal "engine", last_response.body
     end
 
+    test "[ENGINE] relative path redirect uses SCRIPT_NAME from request" do
+      get "/awesome/blog/relative_path_redirect"
+      assert_equal 301, last_response.status
+      assert_equal "http://example.org/awesome/blog/foo", last_response.headers["Location"]
+      assert_equal %(<html><body>You are being <a href="http://example.org/awesome/blog/foo">redirected</a>.</body></html>), last_response.body
+    end
+
+    test "[ENGINE] relative option redirect uses SCRIPT_NAME from request" do
+      get "/awesome/blog/relative_option_redirect"
+      assert_equal 301, last_response.status
+      assert_equal "http://example.org/awesome/blog/foo", last_response.headers["Location"]
+      assert_equal %(<html><body>You are being <a href="http://example.org/awesome/blog/foo">redirected</a>.</body></html>), last_response.body
+    end
+
+    test "[ENGINE] relative custom redirect uses SCRIPT_NAME from request" do
+      get "/awesome/blog/relative_custom_redirect"
+      assert_equal 301, last_response.status
+      assert_equal "http://example.org/awesome/blog/foo", last_response.headers["Location"]
+      assert_equal %(<html><body>You are being <a href="http://example.org/awesome/blog/foo">redirected</a>.</body></html>), last_response.body
+    end
+
+    test "[ENGINE] absolute path redirect doesn't use SCRIPT_NAME from request" do
+      get "/awesome/blog/absolute_path_redirect"
+      assert_equal 301, last_response.status
+      assert_equal "http://example.org/foo", last_response.headers["Location"]
+      assert_equal %(<html><body>You are being <a href="http://example.org/foo">redirected</a>.</body></html>), last_response.body
+    end
+
+    test "[ENGINE] absolute option redirect doesn't use SCRIPT_NAME from request" do
+      get "/awesome/blog/absolute_option_redirect"
+      assert_equal 301, last_response.status
+      assert_equal "http://example.org/foo", last_response.headers["Location"]
+      assert_equal %(<html><body>You are being <a href="http://example.org/foo">redirected</a>.</body></html>), last_response.body
+    end
+
+    test "[ENGINE] absolute custom redirect doesn't use SCRIPT_NAME from request" do
+      get "/awesome/blog/absolute_custom_redirect"
+      assert_equal 301, last_response.status
+      assert_equal "http://example.org/foo", last_response.headers["Location"]
+      assert_equal %(<html><body>You are being <a href="http://example.org/foo">redirected</a>.</body></html>), last_response.body
+    end
+
     # Inside Application
     test "[APP] generating engine's route includes prefix" do
       get "/generate"
@@ -281,6 +331,14 @@ module TestGenerationPrefix
           routes = ActionDispatch::Routing::RouteSet.new
           routes.draw do
             get "/posts/:id", :to => "posts#show", :as => :post
+
+            get "/relative_path_redirect", :to => redirect("foo")
+            get "/relative_option_redirect", :to => redirect(:path => "foo")
+            get "/relative_custom_redirect", :to => redirect { |params, request| "foo" }
+
+            get "/absolute_path_redirect", :to => redirect("/foo")
+            get "/absolute_option_redirect", :to => redirect(:path => "/foo")
+            get "/absolute_custom_redirect", :to => redirect { |params, request| "/foo" }
           end
 
           routes
@@ -331,5 +389,47 @@ module TestGenerationPrefix
       get "/posts/1"
       assert_equal "/posts/1", last_response.body
     end
+
+    test "[ENGINE] relative path redirect uses SCRIPT_NAME from request" do
+      get "/relative_path_redirect"
+      assert_equal 301, last_response.status
+      assert_equal "http://example.org/foo", last_response.headers["Location"]
+      assert_equal %(<html><body>You are being <a href="http://example.org/foo">redirected</a>.</body></html>), last_response.body
+    end
+
+    test "[ENGINE] relative option redirect uses SCRIPT_NAME from request" do
+      get "/relative_option_redirect"
+      assert_equal 301, last_response.status
+      assert_equal "http://example.org/foo", last_response.headers["Location"]
+      assert_equal %(<html><body>You are being <a href="http://example.org/foo">redirected</a>.</body></html>), last_response.body
+    end
+
+    test "[ENGINE] relative custom redirect uses SCRIPT_NAME from request" do
+      get "/relative_custom_redirect"
+      assert_equal 301, last_response.status
+      assert_equal "http://example.org/foo", last_response.headers["Location"]
+      assert_equal %(<html><body>You are being <a href="http://example.org/foo">redirected</a>.</body></html>), last_response.body
+    end
+
+    test "[ENGINE] absolute path redirect doesn't use SCRIPT_NAME from request" do
+      get "/absolute_path_redirect"
+      assert_equal 301, last_response.status
+      assert_equal "http://example.org/foo", last_response.headers["Location"]
+      assert_equal %(<html><body>You are being <a href="http://example.org/foo">redirected</a>.</body></html>), last_response.body
+    end
+
+    test "[ENGINE] absolute option redirect doesn't use SCRIPT_NAME from request" do
+      get "/absolute_option_redirect"
+      assert_equal 301, last_response.status
+      assert_equal "http://example.org/foo", last_response.headers["Location"]
+      assert_equal %(<html><body>You are being <a href="http://example.org/foo">redirected</a>.</body></html>), last_response.body
+    end
+
+    test "[ENGINE] absolute custom redirect doesn't use SCRIPT_NAME from request" do
+      get "/absolute_custom_redirect"
+      assert_equal 301, last_response.status
+      assert_equal "http://example.org/foo", last_response.headers["Location"]
+      assert_equal %(<html><body>You are being <a href="http://example.org/foo">redirected</a>.</body></html>), last_response.body
+    end
   end
 end
diff --git a/actionpack/test/dispatch/request/json_params_parsing_test.rb b/actionpack/test/dispatch/request/json_params_parsing_test.rb
index 8d0a845..c9903ca 100644
--- a/actionpack/test/dispatch/request/json_params_parsing_test.rb
+++ b/actionpack/test/dispatch/request/json_params_parsing_test.rb
@@ -70,6 +70,13 @@ class JsonParamsParsingTest < ActionDispatch::IntegrationTest
     end
   end
 
+  test 'raw_post is not empty for JSON request' do
+    with_test_routing do
+      post '/parse', '{"posts": [{"title": "Post Title"}]}', 'CONTENT_TYPE' => 'application/json'
+      assert_equal '{"posts": [{"title": "Post Title"}]}', request.raw_post
+    end
+  end
+
   private
     def assert_parses(expected, actual, headers = {})
       with_test_routing do
diff --git a/actionpack/test/dispatch/request/query_string_parsing_test.rb b/actionpack/test/dispatch/request/query_string_parsing_test.rb
index f072a9f..0ad0dbc 100644
--- a/actionpack/test/dispatch/request/query_string_parsing_test.rb
+++ b/actionpack/test/dispatch/request/query_string_parsing_test.rb
@@ -11,6 +11,17 @@ class QueryStringParsingTest < ActionDispatch::IntegrationTest
       head :ok
     end
   end
+  class EarlyParse
+    def initialize(app)
+      @app = app
+    end
+
+    def call(env)
+      # Trigger a Rack parse so that env caches the query params
+      Rack::Request.new(env).params
+      @app.call(env)
+    end
+  end
 
   def teardown
     TestController.last_query_parameters = nil
@@ -131,6 +142,10 @@ class QueryStringParsingTest < ActionDispatch::IntegrationTest
         set.draw do
           get ':action', :to => ::QueryStringParsingTest::TestController
         end
+        @app = self.class.build_app(set) do |middleware|
+          middleware.use(EarlyParse)
+        end
+
 
         get "/parse", actual
         assert_response :ok
diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb
index 3133a14..e4c3ddd 100644
--- a/actionpack/test/dispatch/routing_test.rb
+++ b/actionpack/test/dispatch/routing_test.rb
@@ -2675,6 +2675,19 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest
     assert_raises(ArgumentError) { routes.redirect Object.new }
   end
 
+  def test_named_route_check
+    before, after = nil
+
+    draw do
+      before = has_named_route?(:hello)
+      get "/hello", as: :hello, to: "hello#world"
+      after = has_named_route?(:hello)
+    end
+
+    assert !before, "expected to not have named route :hello before route definition"
+    assert after, "expected to have named route :hello after route definition"
+  end
+
   def test_explicitly_avoiding_the_named_route
     draw do
       scope :as => "routes" do
@@ -3607,3 +3620,56 @@ class TestRouteDefaults < ActionDispatch::IntegrationTest
     assert_equal '/projects/1', url_for(controller: 'projects', action: 'show', id: 1, only_path: true)
   end
 end
+
+class TestRackAppRouteGeneration < ActionDispatch::IntegrationTest
+  stub_controllers do |routes|
+    Routes = routes
+    Routes.draw do
+      rack_app = lambda { |env| [200, { 'Content-Type' => 'text/plain' }, []] }
+      mount rack_app, at: '/account', as: 'account'
+      mount rack_app, at: '/:locale/account', as: 'localized_account'
+    end
+  end
+
+  def app
+    Routes
+  end
+
+  include Routes.url_helpers
+
+  def test_mounted_application_doesnt_match_unnamed_route
+    assert_raise(ActionController::UrlGenerationError) do
+      assert_equal '/account?controller=products', url_for(controller: 'products', action: 'index', only_path: true)
+    end
+
+    assert_raise(ActionController::UrlGenerationError) do
+      assert_equal '/de/account?controller=products', url_for(controller: 'products', action: 'index', :locale => 'de', only_path: true)
+    end
+  end
+end
+
+class TestRedirectRouteGeneration < ActionDispatch::IntegrationTest
+  stub_controllers do |routes|
+    Routes = routes
+    Routes.draw do
+      get '/account', to: redirect('/myaccount'), as: 'account'
+      get '/:locale/account', to: redirect('/%{locale}/myaccount'), as: 'localized_account'
+    end
+  end
+
+  def app
+    Routes
+  end
+
+  include Routes.url_helpers
+
+  def test_redirect_doesnt_match_unnamed_route
+    assert_raise(ActionController::UrlGenerationError) do
+      assert_equal '/account?controller=products', url_for(controller: 'products', action: 'index', only_path: true)
+    end
+
+    assert_raise(ActionController::UrlGenerationError) do
+      assert_equal '/de/account?controller=products', url_for(controller: 'products', action: 'index', :locale => 'de', only_path: true)
+    end
+  end
+end
diff --git a/actionpack/test/dispatch/ssl_test.rb b/actionpack/test/dispatch/ssl_test.rb
index a9bea7e..61b55f3 100644
--- a/actionpack/test/dispatch/ssl_test.rb
+++ b/actionpack/test/dispatch/ssl_test.rb
@@ -37,6 +37,11 @@ class SSLTest < ActionDispatch::IntegrationTest
       response.headers['Strict-Transport-Security']
   end
 
+  def test_no_hsts_with_insecure_connection
+    get "http://example.org/"
+    assert_not response.headers['Strict-Transport-Security']
+  end
+
   def test_hsts_header
     self.app = ActionDispatch::SSL.new(default_app, :hsts => true)
     get "https://example.org/"
@@ -119,6 +124,20 @@ class SSLTest < ActionDispatch::IntegrationTest
       response.headers['Set-Cookie'].split("\n")
   end
 
+  def test_flag_cookies_as_secure_with_ignore_case
+    self.app = ActionDispatch::SSL.new(lambda { |env|
+      headers = {
+        'Content-Type' => "text/html",
+        'Set-Cookie' => "problem=def; path=/; Secure; HttpOnly"
+      }
+      [200, headers, ["OK"]]
+    })
+
+    get "https://example.org/"
+    assert_equal ["problem=def; path=/; Secure; HttpOnly"],
+      response.headers['Set-Cookie'].split("\n")
+  end
+
   def test_no_cookies
     self.app = ActionDispatch::SSL.new(lambda { |env|
       [200, {'Content-Type' => "text/html"}, ["OK"]]
diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb
index 3db862c..65ad867 100644
--- a/actionpack/test/dispatch/test_request_test.rb
+++ b/actionpack/test/dispatch/test_request_test.rb
@@ -62,6 +62,36 @@ class TestRequestTest < ActiveSupport::TestCase
     assert_equal false, req.env.empty?
   end
 
+  test "default remote address is 0.0.0.0" do
+    req = ActionDispatch::TestRequest.new
+    assert_equal '0.0.0.0', req.remote_addr
+  end
+
+  test "allows remote address to be overridden" do
+    req = ActionDispatch::TestRequest.new('REMOTE_ADDR' => '127.0.0.1')
+    assert_equal '127.0.0.1', req.remote_addr
+  end
+
+  test "default host is test.host" do
+    req = ActionDispatch::TestRequest.new
+    assert_equal 'test.host', req.host
+  end
+
+  test "allows host to be overridden" do
+    req = ActionDispatch::TestRequest.new('HTTP_HOST' => 'www.example.com')
+    assert_equal 'www.example.com', req.host
+  end
+
+  test "default user agent is 'Rails Testing'" do
+    req = ActionDispatch::TestRequest.new
+    assert_equal 'Rails Testing', req.user_agent
+  end
+
+  test "allows user agent to be overridden" do
+    req = ActionDispatch::TestRequest.new('HTTP_USER_AGENT' => 'GoogleBot')
+    assert_equal 'GoogleBot', req.user_agent
+  end
+
   private
     def assert_cookies(expected, cookie_jar)
       assert_equal(expected, cookie_jar.instance_variable_get("@cookies"))
diff --git a/actionpack/test/fixtures/digestor/level/_recursion.html.erb b/actionpack/test/fixtures/digestor/level/_recursion.html.erb
new file mode 100644
index 0000000..ee5aaf0
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/level/_recursion.html.erb
@@ -0,0 +1 @@
+<%= render 'recursion' %>
diff --git a/actionpack/test/fixtures/digestor/level/recursion.html.erb b/actionpack/test/fixtures/digestor/level/recursion.html.erb
new file mode 100644
index 0000000..ee5aaf0
--- /dev/null
+++ b/actionpack/test/fixtures/digestor/level/recursion.html.erb
@@ -0,0 +1 @@
+<%= render 'recursion' %>
diff --git a/actionpack/test/fixtures/helpers_missing/invalid_require_helper.rb b/actionpack/test/fixtures/helpers_missing/invalid_require_helper.rb
new file mode 100644
index 0000000..d8801e5
--- /dev/null
+++ b/actionpack/test/fixtures/helpers_missing/invalid_require_helper.rb
@@ -0,0 +1,5 @@
+require 'very_invalid_file_name'
+
+module InvalidRequireHelper
+end
+
diff --git a/actionpack/test/journey/router/utils_test.rb b/actionpack/test/journey/router/utils_test.rb
index 057dc40..93348f4 100644
--- a/actionpack/test/journey/router/utils_test.rb
+++ b/actionpack/test/journey/router/utils_test.rb
@@ -15,6 +15,14 @@ module ActionDispatch
         def test_uri_unescape
           assert_equal "a/b c+d", Utils.unescape_uri("a%2Fb%20c+d")
         end
+
+        def test_normalize_path_not_greedy
+          assert_equal "/foo%20bar%20baz", Utils.normalize_path("/foo%20bar%20baz")
+        end
+
+        def test_normalize_path_uppercase
+          assert_equal "/foo%AAbar%AAbaz", Utils.normalize_path("/foo%aabar%aabaz")
+        end
       end
     end
   end
diff --git a/actionpack/test/journey/router_test.rb b/actionpack/test/journey/router_test.rb
index 3d52b2e..a286f77 100644
--- a/actionpack/test/journey/router_test.rb
+++ b/actionpack/test/journey/router_test.rb
@@ -4,9 +4,13 @@ require 'abstract_unit'
 module ActionDispatch
   module Journey
     class TestRouter < ActiveSupport::TestCase
+      # TODO : clean up routing tests so we don't need this hack
+      class StubDispatcher < Routing::RouteSet::Dispatcher; end
+
       attr_reader :routes
 
       def setup
+        @app       = StubDispatcher.new
         @routes    = Routes.new
         @router    = Router.new(@routes, {})
         @formatter = Formatter.new(@routes)
@@ -306,7 +310,7 @@ module ActionDispatch
 
       def test_nil_path_parts_are_ignored
         path  = Path::Pattern.new "/:controller(/:action(.:format))"
-        @router.routes.add_route nil, path, {}, {}, {}
+        @router.routes.add_route @app, path, {}, {}, {}
 
         params = { :controller => "tasks", :format => nil }
         extras = { :action => 'lol' }
@@ -321,7 +325,7 @@ module ActionDispatch
         str = Router::Strexp.new("/", Hash[params], ['/', '.', '?'], true)
         path  = Path::Pattern.new str
 
-        @router.routes.add_route nil, path, {}, {}, {}
+        @router.routes.add_route @app, path, {}, {}, {}
 
         path, _ = @formatter.generate(:path_info, nil, Hash[params], {})
         assert_equal '/', path
@@ -329,7 +333,7 @@ module ActionDispatch
 
       def test_generate_calls_param_proc
         path  = Path::Pattern.new '/:controller(/:action)'
-        @router.routes.add_route nil, path, {}, {}, {}
+        @router.routes.add_route @app, path, {}, {}, {}
 
         parameterized = []
         params = [ [:controller, "tasks"],
@@ -347,7 +351,7 @@ module ActionDispatch
 
       def test_generate_id
         path  = Path::Pattern.new '/:controller(/:action)'
-        @router.routes.add_route nil, path, {}, {}, {}
+        @router.routes.add_route @app, path, {}, {}, {}
 
         path, params = @formatter.generate(
           :path_info, nil, {:id=>1, :controller=>"tasks", :action=>"show"}, {})
@@ -357,7 +361,7 @@ module ActionDispatch
 
       def test_generate_escapes
         path  = Path::Pattern.new '/:controller(/:action)'
-        @router.routes.add_route nil, path, {}, {}, {}
+        @router.routes.add_route @app, path, {}, {}, {}
 
         path, _ = @formatter.generate(:path_info,
           nil, { :controller        => "tasks",
@@ -368,7 +372,7 @@ module ActionDispatch
 
       def test_generate_extra_params
         path  = Path::Pattern.new '/:controller(/:action)'
-        @router.routes.add_route nil, path, {}, {}, {}
+        @router.routes.add_route @app, path, {}, {}, {}
 
         path, params = @formatter.generate(:path_info,
           nil, { :id                => 1,
@@ -382,7 +386,7 @@ module ActionDispatch
 
       def test_generate_uses_recall_if_needed
         path  = Path::Pattern.new '/:controller(/:action(/:id))'
-        @router.routes.add_route nil, path, {}, {}, {}
+        @router.routes.add_route @app, path, {}, {}, {}
 
         path, params = @formatter.generate(:path_info,
           nil,
@@ -394,7 +398,7 @@ module ActionDispatch
 
       def test_generate_with_name
         path  = Path::Pattern.new '/:controller(/:action)'
-        @router.routes.add_route nil, path, {}, {}, {}
+        @router.routes.add_route @app, path, {}, {}, {}
 
         path, params = @formatter.generate(:path_info,
           "tasks",
@@ -541,7 +545,7 @@ module ActionDispatch
       def add_routes router, paths
         paths.each do |path|
           path  = Path::Pattern.new path
-          router.routes.add_route nil, path, {}, {}, {}
+          router.routes.add_route @app, path, {}, {}, {}
         end
       end
 
diff --git a/actionpack/test/routing/helper_test.rb b/actionpack/test/routing/helper_test.rb
index a5588d9..0028aaa 100644
--- a/actionpack/test/routing/helper_test.rb
+++ b/actionpack/test/routing/helper_test.rb
@@ -22,7 +22,7 @@ module ActionDispatch
         x = Class.new {
           include rs.url_helpers
         }
-        assert_raises ActionController::RoutingError do
+        assert_raises ActionController::UrlGenerationError do
           x.new.pond_duck_path Duck.new
         end
       end
diff --git a/actionpack/test/template/date_helper_test.rb b/actionpack/test/template/date_helper_test.rb
index 242b56a..5f09aef 100644
--- a/actionpack/test/template/date_helper_test.rb
+++ b/actionpack/test/template/date_helper_test.rb
@@ -19,8 +19,6 @@ class DateHelperTest < ActionView::TestCase
   end
 
   def assert_distance_of_time_in_words(from, to=nil)
-    Fixnum.send :private, :/  # test we avoid Integer#/ (redefined by mathn)
-
     to ||= from
 
     # 0..1 minute with :include_seconds => true
@@ -123,9 +121,6 @@ class DateHelperTest < ActionView::TestCase
     assert_equal "about 4 hours", distance_of_time_in_words(from + 4.hours, to)
     assert_equal "less than 20 seconds", distance_of_time_in_words(from + 19.seconds, to, :include_seconds => true)
     assert_equal "less than a minute", distance_of_time_in_words(from + 19.seconds, to, :include_seconds => false)
-
-  ensure
-    Fixnum.send :public, :/
   end
 
   def test_distance_in_words
@@ -133,6 +128,13 @@ class DateHelperTest < ActionView::TestCase
     assert_distance_of_time_in_words(from)
   end
 
+  def test_distance_in_words_with_mathn_required
+    # test we avoid Integer#/ (redefined by mathn)
+    require 'mathn'
+    from = Time.utc(2004, 6, 6, 21, 45, 0)
+    assert_distance_of_time_in_words(from)
+  end
+
   def test_time_ago_in_words_passes_include_seconds
     assert_equal "less than 20 seconds", time_ago_in_words(15.seconds.ago, :include_seconds => true)
     assert_equal "less than a minute", time_ago_in_words(15.seconds.ago, :include_seconds => false)
diff --git a/actionpack/test/template/dependency_tracker_test.rb b/actionpack/test/template/dependency_tracker_test.rb
index 9c68afb..8588925 100644
--- a/actionpack/test/template/dependency_tracker_test.rb
+++ b/actionpack/test/template/dependency_tracker_test.rb
@@ -1,24 +1,24 @@
 require 'abstract_unit'
 require 'action_view/dependency_tracker'
 
-class DependencyTrackerTest < ActionView::TestCase
-  Neckbeard = lambda {|template| template.source }
-  Bowtie = lambda {|template| template.source }
-
-  class NeckbeardTracker
-    def self.call(name, template)
-      ["foo/#{name}"]
-    end
+class NeckbeardTracker
+  def self.call(name, template)
+    ["foo/#{name}"]
   end
+end
 
-  class FakeTemplate
-    attr_reader :source, :handler
+class FakeTemplate
+  attr_reader :source, :handler
 
-    def initialize(source, handler = Neckbeard)
-      @source, @handler = source, handler
-    end
+  def initialize(source, handler = Neckbeard)
+    @source, @handler = source, handler
   end
+end
+
+Neckbeard = lambda {|template| template.source }
+Bowtie = lambda {|template| template.source }
 
+class DependencyTrackerTest < ActionView::TestCase
   def tracker
     ActionView::DependencyTracker
   end
@@ -44,3 +44,31 @@ class DependencyTrackerTest < ActionView::TestCase
     assert_equal [], dependencies
   end
 end
+
+class ERBTrackerTest < MiniTest::Unit::TestCase
+  def make_tracker(name, template)
+    ActionView::DependencyTracker::ERBTracker.new(name, template)
+  end
+
+  def test_dependency_of_erb_template_with_number_in_filename
+    template = FakeTemplate.new("<%# render 'messages/message123' %>", :erb)
+    tracker = make_tracker('messages/_message123', template)
+
+    assert_equal ["messages/message123"], tracker.dependencies
+  end
+
+  def test_finds_dependency_in_correct_directory
+    template = FakeTemplate.new("<%# render(message.topic) %>", :erb)
+    tracker = make_tracker('messages/_message', template)
+
+    assert_equal ["topics/topic"], tracker.dependencies
+  end
+
+  def test_finds_dependency_in_correct_directory_with_underscore
+    template = FakeTemplate.new("<%# render(message_type.messages) %>", :erb)
+    tracker = make_tracker('message_types/_message_type', template)
+
+    assert_equal ["messages/message"], tracker.dependencies
+  end
+end
+
diff --git a/actionpack/test/template/digestor_test.rb b/actionpack/test/template/digestor_test.rb
index 06735c3..95dca26 100644
--- a/actionpack/test/template/digestor_test.rb
+++ b/actionpack/test/template/digestor_test.rb
@@ -95,6 +95,31 @@ class TemplateDigestorTest < ActionView::TestCase
     end
   end
 
+  def test_recursion_in_renders
+    assert digest("level/recursion") # assert recursion is possible
+    assert_not_nil digest("level/recursion") # assert digest is stored
+  end
+
+  def test_chaning_the_top_templete_on_recursion
+    assert digest("level/recursion") # assert recursion is possible
+
+    assert_digest_difference("level/recursion") do
+      change_template("level/recursion")
+    end
+
+    assert_not_nil digest("level/recursion") # assert digest is stored
+  end
+
+  def test_chaning_the_partial_templete_on_recursion
+    assert digest("level/recursion") # assert recursion is possible
+
+    assert_digest_difference("level/recursion") do
+      change_template("level/_recursion")
+    end
+
+    assert_not_nil digest("level/recursion") # assert digest is stored
+  end
+
   def test_dont_generate_a_digest_for_missing_templates
     assert_equal '', digest("nothing/there")
   end
@@ -159,6 +184,40 @@ class TemplateDigestorTest < ActionView::TestCase
     assert_not_equal digest_phone, digest_fridge_phone
   end
 
+  def test_cache_template_loading
+    resolver_before = ActionView::Resolver.caching
+    ActionView::Resolver.caching = false
+    assert_digest_difference("messages/edit", true) do
+      change_template("comments/_comment")
+    end
+    ActionView::Resolver.caching = resolver_before
+  end
+
+  def test_digest_cache_cleanup_with_recursion
+    first_digest = digest("level/_recursion")
+    second_digest = digest("level/_recursion")
+
+    assert first_digest
+
+    # If the cache is cleaned up correctly, subsequent digests should return the same
+    assert_equal first_digest, second_digest
+  end
+
+  def test_digest_cache_cleanup_with_recursion_and_template_caching_off
+    resolver_before = ActionView::Resolver.caching
+    ActionView::Resolver.caching = false
+
+    first_digest = digest("level/_recursion")
+    second_digest = digest("level/_recursion")
+
+    assert first_digest
+
+    # If the cache is cleaned up correctly, subsequent digests should return the same
+    assert_equal first_digest, second_digest
+  ensure
+    ActionView::Resolver.caching = resolver_before
+  end
+
   private
     def assert_logged(message)
       old_logger = ActionView::Base.logger
@@ -175,9 +234,9 @@ class TemplateDigestorTest < ActionView::TestCase
       end
     end
 
-    def assert_digest_difference(template_name)
+    def assert_digest_difference(template_name, persistent = false)
       previous_digest = digest(template_name)
-      ActionView::Digestor.cache.clear
+      ActionView::Digestor.cache.clear unless persistent
 
       yield
 
diff --git a/actionpack/test/template/form_collections_helper_test.rb b/actionpack/test/template/form_collections_helper_test.rb
index 2131f81..48a269f 100644
--- a/actionpack/test/template/form_collections_helper_test.rb
+++ b/actionpack/test/template/form_collections_helper_test.rb
@@ -38,7 +38,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
     assert_select 'label[for=user_active_no]', 'No'
   end
 
-  test 'colection radio should sanitize collection values for labels correctly' do
+  test 'collection radio should sanitize collection values for labels correctly' do
     with_collection_radio_buttons :user, :name, ['$0.99', '$1.99'], :to_s, :to_s
     assert_select 'label[for=user_name_099]', '$0.99'
     assert_select 'label[for=user_name_199]', '$1.99'
@@ -171,6 +171,13 @@ class FormCollectionsHelperTest < ActionView::TestCase
     assert_select "input[type=hidden][name='user[category_ids][]'][value=]", :count => 1
   end
 
+  test 'collection check boxes generates a hidden field using the given :name in :html_options' do
+    collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
+    with_collection_check_boxes :user, :category_ids, collection, :id, :name, {}, {name: "user[other_category_ids][]"}
+
+    assert_select "input[type=hidden][name='user[other_category_ids][]'][value=]", :count => 1
+  end
+
   test 'collection check boxes accepts a collection and generate a serie of checkboxes with labels for label method' do
     collection = [Category.new(1, 'Category 1'), Category.new(2, 'Category 2')]
     with_collection_check_boxes :user, :category_ids, collection, :id, :name
@@ -186,7 +193,7 @@ class FormCollectionsHelperTest < ActionView::TestCase
     assert_select 'label[for=user_active_no]', 'No'
   end
 
-  test 'colection check box should sanitize collection values for labels correctly' do
+  test 'collection check box should sanitize collection values for labels correctly' do
     with_collection_check_boxes :user, :name, ['$0.99', '$1.99'], :to_s, :to_s
     assert_select 'label[for=user_name_099]', '$0.99'
     assert_select 'label[for=user_name_199]', '$1.99'
diff --git a/actionpack/test/template/form_helper_test.rb b/actionpack/test/template/form_helper_test.rb
index 1ff3202..3302ee8 100644
--- a/actionpack/test/template/form_helper_test.rb
+++ b/actionpack/test/template/form_helper_test.rb
@@ -676,6 +676,13 @@ class FormHelperTest < ActionView::TestCase
     )
   end
 
+  def test_text_area_with_nil_alternate_value
+    assert_dom_equal(
+      %{<textarea id="post_body" name="post[body]">\n</textarea>},
+      text_area("post", "body", value: nil)
+    )
+  end
+
   def test_text_area_with_html_entities
     @post.body = "The HTML Entity for & is &"
     assert_dom_equal(
@@ -702,6 +709,11 @@ class FormHelperTest < ActionView::TestCase
     assert_dom_equal(expected, color_field("car", "color"))
   end
 
+  def test_color_field_with_value_attr
+    expected = %{<input id="car_color" name="car[color]" type="color" value="#00FF00" />}
+    assert_dom_equal(expected, color_field("car", "color", value: "#00FF00"))
+  end
+
   def test_search_field
     expected = %{<input id="contact_notes_query" name="contact[notes_query]" type="search" />}
     assert_dom_equal(expected, search_field("contact", "notes_query"))
@@ -732,6 +744,12 @@ class FormHelperTest < ActionView::TestCase
     assert_dom_equal(expected, date_field("post", "written_on", min: min_value, max: max_value, step: step))
   end
 
+  def test_date_field_with_value_attr
+    expected = %{<input id="post_written_on" name="post[written_on]" type="date" value="2013-06-29" />}
+    value = Date.new(2013,6,29)
+    assert_dom_equal(expected, date_field("post", "written_on", value: value))
+  end
+
   def test_date_field_with_timewithzone_value
     previous_time_zone, Time.zone = Time.zone, 'UTC'
     expected = %{<input id="post_written_on" name="post[written_on]" type="date" value="2004-06-15" />}
@@ -802,6 +820,12 @@ class FormHelperTest < ActionView::TestCase
     assert_dom_equal(expected, datetime_field("post", "written_on", min: min_value, max: max_value, step: step))
   end
 
+  def test_datetime_field_with_value_attr
+    expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2013-06-29T13:37:00+00:00" />}
+    value = DateTime.new(2013,6,29,13,37)
+    assert_dom_equal(expected, datetime_field("post", "written_on", value: value))
+  end
+
   def test_datetime_field_with_timewithzone_value
     previous_time_zone, Time.zone = Time.zone, 'UTC'
     expected = %{<input id="post_written_on" name="post[written_on]" type="datetime" value="2004-06-15T15:30:45.000+0000" />}
@@ -1258,6 +1282,24 @@ class FormHelperTest < ActionView::TestCase
     assert_dom_equal expected, output_buffer
   end
 
+  def test_form_with_namespace_and_with_collection_radio_buttons
+    post = Post.new
+    def post.active; false; end
+
+    form_for(post, namespace: 'foo') do |f|
+      concat f.collection_radio_buttons(:active, [true, false], :to_s, :to_s)
+    end
+
+    expected = whole_form("/posts", "foo_new_post", "new_post") do
+      "<input id='foo_post_active_true' name='post[active]' type='radio' value='true' />" +
+      "<label for='foo_post_active_true'>true</label>" +
+      "<input checked='checked' id='foo_post_active_false' name='post[active]' type='radio' value='false' />" +
+      "<label for='foo_post_active_false'>false</label>"
+    end
+
+    assert_dom_equal expected, output_buffer
+  end
+
   def test_form_for_with_collection_check_boxes
     post = Post.new
     def post.tag_ids; [1, 3]; end
@@ -1337,6 +1379,24 @@ class FormHelperTest < ActionView::TestCase
     assert_dom_equal expected, output_buffer
   end
 
+  def test_form_with_namespace_and_with_collection_check_boxes
+    post = Post.new
+    def post.tag_ids; [1]; end
+    collection = [[1, "Tag 1"]]
+
+    form_for(post, namespace: 'foo') do |f|
+      concat f.collection_check_boxes(:tag_ids, collection, :first, :last)
+    end
+
+    expected = whole_form("/posts", "foo_new_post", "new_post") do
+      "<input checked='checked' id='foo_post_tag_ids_1' name='post[tag_ids][]' type='checkbox' value='1' />" +
+      "<label for='foo_post_tag_ids_1'>Tag 1</label>" +
+      "<input name='post[tag_ids][]' type='hidden' value='' />"
+    end
+
+    assert_dom_equal expected, output_buffer
+  end
+
   def test_form_for_with_file_field_generate_multipart
     Post.send :attr_accessor, :file
 
diff --git a/actionpack/test/template/form_options_helper_test.rb b/actionpack/test/template/form_options_helper_test.rb
index 1715902..7dd1c5b 100644
--- a/actionpack/test/template/form_options_helper_test.rb
+++ b/actionpack/test/template/form_options_helper_test.rb
@@ -793,6 +793,22 @@ class FormOptionsHelperTest < ActionView::TestCase
     )
   end
 
+  def test_select_not_existing_method_with_selected_value
+    @post = Post.new
+    assert_dom_equal(
+      "<select id=\"post_locale\" name=\"post[locale]\"><option value=\"en\">en</option>\n<option value=\"ru\" selected=\"selected\">ru</option></select>",
+      select("post", "locale", %w( en ru ), :selected => 'ru')
+    )
+  end
+
+  def test_select_with_prompt_and_selected_value
+    @post = Post.new
+    assert_dom_equal(
+      "<select id=\"post_category\" name=\"post[category]\"><option value=\"one\">one</option>\n<option selected=\"selected\" value=\"two\">two</option></select>",
+      select("post", "category", %w( one two ), :selected => 'two', :prompt => true)
+    )
+  end
+
   def test_select_with_disabled_array
     @post = Post.new
     @post.category = "<mus>"
diff --git a/actionpack/test/template/number_helper_test.rb b/actionpack/test/template/number_helper_test.rb
index 6e64088..be336ea 100644
--- a/actionpack/test/template/number_helper_test.rb
+++ b/actionpack/test/template/number_helper_test.rb
@@ -14,7 +14,8 @@ class NumberHelperTest < ActionView::TestCase
     assert_equal nil, number_to_currency(nil)
     assert_equal "$1,234,567,890.50", number_to_currency(1234567890.50)
     assert_equal "$1,234,567,892", number_to_currency(1234567891.50, precision: 0)
-    assert_equal "1,234,567,890.50 - Kč", number_to_currency("-1234567890.50", unit: "Kč", format: "%n %u", negative_format: "%n - %u")
+    assert_equal "1,234,567,890.50 - Kč", number_to_currency("-1234567890.50", unit: raw("Kč"), format: "%n %u", negative_format: "%n - %u")
+    assert_equal "&pound;1,234,567,890.50", number_to_currency("1234567890.50", unit: "£")
   end
 
   def test_number_to_percentage
diff --git a/actionpack/test/template/render_test.rb b/actionpack/test/template/render_test.rb
index 81f3391..34102aa 100644
--- a/actionpack/test/template/render_test.rb
+++ b/actionpack/test/template/render_test.rb
@@ -41,6 +41,11 @@ module RenderTestCases
     assert_match "<error>No Comment</error>", @view.render(:template => "comments/empty", :formats => [:xml])
   end
 
+  def test_rendered_format_without_format
+    @view.render(:inline => "test")
+    assert_equal :html, @view.lookup_context.rendered_format
+  end
+
   def test_render_partial_implicitly_use_format_of_the_rendered_template
     @view.lookup_context.formats = [:json]
     assert_equal "Hello world", @view.render(:template => "test/one", :formats => [:html])
diff --git a/actionpack/test/template/resolver_patterns_test.rb b/actionpack/test/template/resolver_patterns_test.rb
index 97b1bad..575eb9b 100644
--- a/actionpack/test/template/resolver_patterns_test.rb
+++ b/actionpack/test/template/resolver_patterns_test.rb
@@ -20,7 +20,7 @@ class ResolverPatternsTest < ActiveSupport::TestCase
     assert_equal [:html],                  templates.first.formats
   end
 
-  def test_should_return_all_templates_when_ambigous_pattern
+  def test_should_return_all_templates_when_ambiguous_pattern
     templates = @resolver.find_all("another", "custom_pattern", false, {:locale => [], :formats => [:html], :handlers => [:erb]})
     assert_equal 2, templates.size, "expected two templates"
     assert_equal "Another template!",      templates[0].source
diff --git a/actionpack/test/template/text_helper_test.rb b/actionpack/test/template/text_helper_test.rb
index 1b2234f..c2999fc 100644
--- a/actionpack/test/template/text_helper_test.rb
+++ b/actionpack/test/template/text_helper_test.rb
@@ -314,6 +314,9 @@ class TextHelperTest < ActionView::TestCase
 
     options = { :separator => "\n", :radius => 1 }
     assert_equal("...very\nvery long\nstring", excerpt("my very\nvery\nvery long\nstring", 'long', options))
+
+    assert_equal excerpt('This is a beautiful morning', 'a'),
+                 excerpt('This is a beautiful morning', 'a', separator: nil)
   end
 
   def test_word_wrap
diff --git a/actionpack/test/template/translation_helper_test.rb b/actionpack/test/template/translation_helper_test.rb
index d496dbb..0dfe47f 100644
--- a/actionpack/test/template/translation_helper_test.rb
+++ b/actionpack/test/template/translation_helper_test.rb
@@ -31,7 +31,7 @@ class TranslationHelperTest < ActiveSupport::TestCase
   end
 
   def test_delegates_to_i18n_setting_the_rescue_format_option_to_html
-    I18n.expects(:translate).with(:foo, :locale => 'en', :rescue_format => :html).returns("")
+    I18n.expects(:translate).with(:foo, :locale => 'en', :raise=>true).returns("")
     translate :foo, :locale => 'en'
   end
 
diff --git a/actionpack/test/template/url_helper_test.rb b/actionpack/test/template/url_helper_test.rb
index 9b4c419..26f0347 100644
--- a/actionpack/test/template/url_helper_test.rb
+++ b/actionpack/test/template/url_helper_test.rb
@@ -18,6 +18,7 @@ class UrlHelperTest < ActiveSupport::TestCase
     get "/" => "foo#bar"
     get "/other" => "foo#other"
     get "/article/:id" => "foo#article", :as => :article
+    get "/category/:category" => "foo#category"
   end
 
   include ActionView::Helpers::UrlHelper
@@ -307,6 +308,13 @@ class UrlHelperTest < ActiveSupport::TestCase
     )
   end
 
+  def test_link_tag_using_block_and_hash
+    assert_dom_equal(
+      %{<a href="/"><span>Example site</span></a>},
+      link_to(url_hash) { content_tag(:span, 'Example site') }
+    )
+  end
+
   def test_link_to_with_string_remote_in_non_html_options
     assert_dom_equal(
       %{<a href="/" data-remote="true">Hello</a>},
@@ -423,6 +431,11 @@ class UrlHelperTest < ActiveSupport::TestCase
       link_to_unless(true, "Showing", url_hash) {
         "test"
       }
+
+    assert_equal %{<b>Showing</b>}, link_to_unless(true, "<b>Showing</b>", url_hash)
+    assert_equal %{<a href="/"><b>Showing</b></a>}, link_to_unless(false, "<b>Showing</b>", url_hash)
+    assert_equal %{<b>Showing</b>}, link_to_unless(true, "<b>Showing</b>".html_safe, url_hash)
+    assert_equal %{<a href="/"><b>Showing</b></a>}, link_to_unless(false, "<b>Showing</b>".html_safe, url_hash)
   end
 
   def test_link_to_if
@@ -468,6 +481,26 @@ class UrlHelperTest < ActiveSupport::TestCase
     assert !current_page?('/events')
   end
 
+  def test_current_page_with_escaped_params
+    @request = request_for_url("/category/administra%c3%a7%c3%a3o")
+
+    assert current_page?(controller: 'foo', action: 'category', category: 'administração')
+  end
+
+  def test_current_page_with_escaped_params_with_different_encoding
+    @request = request_for_url("/")
+    @request.stubs(path: "/category/administra%c3%a7%c3%a3o".force_encoding(Encoding::ASCII_8BIT))
+
+    assert current_page?(:controller => 'foo', :action => 'category', category: 'administração')
+    assert current_page?("http://www.example.com/category/administra%c3%a7%c3%a3o")
+  end
+
+  def test_current_page_with_double_escaped_params
+    @request = request_for_url("/category/administra%c3%a7%c3%a3o?callback_url=http%3a%2f%2fexample.com%2ffoo")
+
+    assert current_page?(controller: 'foo', action: 'category', category: 'administração', callback_url: 'http://example.com/foo')
+  end
+
   def test_link_unless_current
     @request = request_for_url("/")
 
diff --git a/actionpack/test/ts_isolated.rb b/actionpack/test/ts_isolated.rb
deleted file mode 100644
index 55620ab..0000000
--- a/actionpack/test/ts_isolated.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-require 'active_support/testing/autorun'
-require 'rbconfig'
-require 'abstract_unit'
-
-class TestIsolated < ActiveSupport::TestCase
-  ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
-
-  Dir["#{File.dirname(__FILE__)}/{abstract,controller,dispatch,template}/**/*_test.rb"].each do |file|
-    define_method("test #{file}") do
-      command = "#{ruby} -Ilib:test #{file}"
-      result = silence_stderr { `#{command}` }
-      assert $?.to_i.zero?, "#{command}\n#{result}"
-    end
-  end
-end
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
index b0acf99..f282b51 100644
--- a/activemodel/CHANGELOG.md
+++ b/activemodel/CHANGELOG.md
@@ -1,3 +1,20 @@
+## Rails 4.0.1 (November 01, 2013) ##
+
+*   Fix `has_secure_password` to honor bcrypt-ruby's cost attribute.
+
+    *T.J. Schuck*
+
+*   `inclusion` / `exclusion` validations with ranges will only use the faster
+    `Range#cover` for numerical ranges, and the more accurate `Range#include?`
+    for non-numerical ones.
+
+    Fixes range validations like `:a..:f` that used to pass with values like `:be`.
+
+    Fixes #10593.
+
+    *Charles Bergeron*
+
+
 ## Rails 4.0.0 (June 25, 2013) ##
 
 *   Fix regression in has_secure_password. When a password is set, but a
diff --git a/activemodel/README.rdoc b/activemodel/README.rdoc
index a399fe9..46ef28d 100644
--- a/activemodel/README.rdoc
+++ b/activemodel/README.rdoc
@@ -227,7 +227,7 @@ The latest version of Active Model can be installed with RubyGems:
 
 Source code can be downloaded as part of the Rails project on GitHub
 
-* https://github.com/rails/rails/tree/master/activemodel
+* https://github.com/rails/rails/tree/4-0-stable/activemodel
 
 
 == License
diff --git a/activemodel/lib/active_model/attribute_methods.rb b/activemodel/lib/active_model/attribute_methods.rb
index 5db898b..c964b3f 100644
--- a/activemodel/lib/active_model/attribute_methods.rb
+++ b/activemodel/lib/active_model/attribute_methods.rb
@@ -1,4 +1,5 @@
 require 'thread_safe'
+require 'mutex_m'
 
 module ActiveModel
   # Raised when an attribute is not defined.
@@ -324,7 +325,9 @@ module ActiveModel
 
       # Returns true if the attribute methods defined have been generated.
       def generated_attribute_methods #:nodoc:
-        @generated_attribute_methods ||= Module.new.tap { |mod| include mod }
+        @generated_attribute_methods ||= Module.new {
+          extend Mutex_m
+        }.tap { |mod| include mod }
       end
 
       protected
diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb
index b60458b..050838b 100644
--- a/activemodel/lib/active_model/errors.rb
+++ b/activemodel/lib/active_model/errors.rb
@@ -50,7 +50,7 @@ module ActiveModel
   #
   # The above allows you to do:
   #
-  #   p = Person.new
+  #   person = Person.new
   #   person.validate!            # => ["can not be nil"]
   #   person.errors.full_messages # => ["name can not be nil"]
   #   # etc..
@@ -238,8 +238,8 @@ module ActiveModel
     # object. You can pass the <tt>:full_messages</tt> option. This determines
     # if the json object should contain full messages or not (false by default).
     #
-    #   person.as_json                      # => {:name=>["can not be nil"]}
-    #   person.as_json(full_messages: true) # => {:name=>["name can not be nil"]}
+    #   person.errors.as_json                      # => {:name=>["can not be nil"]}
+    #   person.errors.as_json(full_messages: true) # => {:name=>["name can not be nil"]}
     def as_json(options=nil)
       to_hash(options && options[:full_messages])
     end
@@ -247,8 +247,8 @@ module ActiveModel
     # Returns a Hash of attributes with their error messages. If +full_messages+
     # is +true+, it will contain full messages (see +full_message+).
     #
-    #   person.to_hash       # => {:name=>["can not be nil"]}
-    #   person.to_hash(true) # => {:name=>["name can not be nil"]}
+    #   person.errors.to_hash       # => {:name=>["can not be nil"]}
+    #   person.errors.to_hash(true) # => {:name=>["name can not be nil"]}
     def to_hash(full_messages = false)
       if full_messages
         messages = {}
diff --git a/activemodel/lib/active_model/secure_password.rb b/activemodel/lib/active_model/secure_password.rb
index 393eb9f..da1e846 100644
--- a/activemodel/lib/active_model/secure_password.rb
+++ b/activemodel/lib/active_model/secure_password.rb
@@ -18,9 +18,9 @@ module ActiveModel
       # value to the password_confirmation attribute and the the validation
       # will not be triggered.
       #
-      # You need to add bcrypt-ruby (~> 3.0.0) to Gemfile to use #has_secure_password:
+      # You need to add bcrypt-ruby (~> 3.1.2) to Gemfile to use #has_secure_password:
       #
-      #   gem 'bcrypt-ruby', '~> 3.0.0'
+      #   gem 'bcrypt-ruby', '~> 3.1.2'
       #
       # Example using Active Record (which automatically includes ActiveModel::SecurePassword):
       #
@@ -44,7 +44,7 @@ module ActiveModel
         # This is to avoid ActiveModel (and by extension the entire framework)
         # being dependent on a binary library.
         begin
-          gem 'bcrypt-ruby', '~> 3.0.0'
+          gem 'bcrypt-ruby', '~> 3.1.2'
           require 'bcrypt'
         rescue LoadError
           $stderr.puts "You don't have bcrypt-ruby installed in your application. Please add it to your Gemfile and run bundle install"
@@ -101,7 +101,7 @@ module ActiveModel
       def password=(unencrypted_password)
         unless unencrypted_password.blank?
           @password = unencrypted_password
-          cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine::DEFAULT_COST
+          cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost
           self.password_digest = BCrypt::Password.create(unencrypted_password, cost: cost)
         end
       end
diff --git a/activemodel/lib/active_model/validations/clusivity.rb b/activemodel/lib/active_model/validations/clusivity.rb
index 49df98d..6af8ba3 100644
--- a/activemodel/lib/active_model/validations/clusivity.rb
+++ b/activemodel/lib/active_model/validations/clusivity.rb
@@ -30,11 +30,18 @@ module ActiveModel
         @delimiter ||= options[:in] || options[:within]
       end
 
-      # In Ruby 1.9 <tt>Range#include?</tt> on non-numeric ranges checks all possible values in the
-      # range for equality, so it may be slow for large ranges. The new <tt>Range#cover?</tt>
-      # uses the previous logic of comparing a value with the range endpoints.
+      # In Ruby 1.9 <tt>Range#include?</tt> on non-number-or-time-ish ranges checks all
+      # possible values in the range for equality, which is slower but more accurate.
+      # <tt>Range#cover?</tt> uses the previous logic of comparing a value with the range
+      # endpoints, which is fast but is only accurate on Numeric, Time, or DateTime ranges.
       def inclusion_method(enumerable)
-        enumerable.is_a?(Range) ? :cover? : :include?
+        return :include? unless enumerable.is_a?(Range)
+        case enumerable.first
+        when Numeric, Time, DateTime
+          :cover?
+        else
+          :include?
+        end
       end
     end
   end
diff --git a/activemodel/lib/active_model/validations/inclusion.rb b/activemodel/lib/active_model/validations/inclusion.rb
index 5e45a04..257c34b 100644
--- a/activemodel/lib/active_model/validations/inclusion.rb
+++ b/activemodel/lib/active_model/validations/inclusion.rb
@@ -28,7 +28,7 @@ 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 range the test is performed with <tt>Range#cover?</tt>,
+      #   enumerable is a numerical range the test is performed with <tt>Range#cover?</tt>,
       #   otherwise with <tt>include?</tt>.
       # * <tt>:within</tt> - A synonym(or alias) for <tt>:in</tt>
       # * <tt>:message</tt> - Specifies a custom error message (default is: "is
diff --git a/activemodel/lib/active_model/version.rb b/activemodel/lib/active_model/version.rb
index 4d01964..4e69ae9 100644
--- a/activemodel/lib/active_model/version.rb
+++ b/activemodel/lib/active_model/version.rb
@@ -1,7 +1,7 @@
 module ActiveModel
   # Returns the version of the currently loaded ActiveModel as a Gem::Version
   def self.version
-    Gem::Version.new "4.0.0"
+    Gem::Version.new "4.0.2"
   end
 
   module VERSION #:nodoc:
diff --git a/activemodel/test/cases/railtie_test.rb b/activemodel/test/cases/railtie_test.rb
index a0cd140..96b3b07 100644
--- a/activemodel/test/cases/railtie_test.rb
+++ b/activemodel/test/cases/railtie_test.rb
@@ -7,9 +7,12 @@ class RailtieTest < ActiveModel::TestCase
   def setup
     require 'active_model/railtie'
 
+    # Set a fake logger to avoid creating the log directory automatically
+    fake_logger = Logger.new(nil)
+
     @app ||= Class.new(::Rails::Application) do
       config.eager_load = false
-      config.logger = Logger.new(STDOUT)
+      config.logger = fake_logger
     end
   end
 
diff --git a/activemodel/test/cases/secure_password_test.rb b/activemodel/test/cases/secure_password_test.rb
index 0b900d9..c4b9231 100644
--- a/activemodel/test/cases/secure_password_test.rb
+++ b/activemodel/test/cases/secure_password_test.rb
@@ -82,6 +82,14 @@ class SecurePasswordTest < ActiveModel::TestCase
     assert_equal BCrypt::Engine::DEFAULT_COST, @user.password_digest.cost
   end
 
+  test "Password digest cost honors bcrypt cost attribute when min_cost is false" do
+    ActiveModel::SecurePassword.min_cost = false
+    BCrypt::Engine.cost = 5
+
+    @user.password = "secret"
+    assert_equal BCrypt::Engine.cost, @user.password_digest.cost
+  end
+
   test "Password digest cost can be set to bcrypt min cost to speed up tests" do
     ActiveModel::SecurePassword.min_cost = true
 
diff --git a/activemodel/test/cases/serializers/json_serialization_test.rb b/activemodel/test/cases/serializers/json_serialization_test.rb
index 9134c49..e319a19 100644
--- a/activemodel/test/cases/serializers/json_serialization_test.rb
+++ b/activemodel/test/cases/serializers/json_serialization_test.rb
@@ -204,7 +204,7 @@ class JsonSerializationTest < ActiveModel::TestCase
     assert_no_match %r{"preferences":}, json
   end
 
-  test "custom as_json options should be extendible" do
+  test "custom as_json options should be extensible" do
     def @contact.as_json(options = {}); super(options.merge(only: [:name])); end
     json = @contact.to_json
 
diff --git a/activemodel/test/cases/serializers/xml_serialization_test.rb b/activemodel/test/cases/serializers/xml_serialization_test.rb
index 04ecf8a..4eafc64 100644
--- a/activemodel/test/cases/serializers/xml_serialization_test.rb
+++ b/activemodel/test/cases/serializers/xml_serialization_test.rb
@@ -53,8 +53,7 @@ class XmlSerializationTest < ActiveModel::TestCase
     @contact.address.city = "Springfield"
     @contact.address.apt_number = 35
     @contact.friends = [Contact.new, Contact.new]
-    @related_contact = SerializableContact.new
-    @contact.contact = @related_contact
+    @contact.contact = SerializableContact.new
   end
 
   test "should serialize default root" do
diff --git a/activemodel/test/cases/validations/inclusion_validation_test.rb b/activemodel/test/cases/validations/inclusion_validation_test.rb
index 117e910..5e8ca87 100644
--- a/activemodel/test/cases/validations/inclusion_validation_test.rb
+++ b/activemodel/test/cases/validations/inclusion_validation_test.rb
@@ -1,5 +1,6 @@
 # encoding: utf-8
 require 'cases/helper'
+require 'active_support/all'
 
 require 'models/topic'
 require 'models/person'
@@ -14,11 +15,33 @@ class InclusionValidationTest < ActiveModel::TestCase
     Topic.validates_inclusion_of( :title, :in => 'aaa'..'bbb' )
     assert Topic.new("title" => "bbc", "content" => "abc").invalid?
     assert Topic.new("title" => "aa", "content" => "abc").invalid?
+    assert Topic.new("title" => "aaab", "content" => "abc").invalid?
     assert Topic.new("title" => "aaa", "content" => "abc").valid?
     assert Topic.new("title" => "abc", "content" => "abc").valid?
     assert Topic.new("title" => "bbb", "content" => "abc").valid?
   end
 
+  def test_validates_inclusion_of_time_range
+    Topic.validates_inclusion_of(:created_at, in: 1.year.ago..Time.now)
+    assert Topic.new(title: 'aaa', created_at: 2.years.ago).invalid?
+    assert Topic.new(title: 'aaa', created_at: 3.months.ago).valid?
+    assert Topic.new(title: 'aaa', created_at: 37.weeks.from_now).invalid?
+  end
+
+  def test_validates_inclusion_of_date_range
+    Topic.validates_inclusion_of(:created_at, in: 1.year.until(Date.today)..Date.today)
+    assert Topic.new(title: 'aaa', created_at: 2.years.until(Date.today)).invalid?
+    assert Topic.new(title: 'aaa', created_at: 3.months.until(Date.today)).valid?
+    assert Topic.new(title: 'aaa', created_at: 37.weeks.since(Date.today)).invalid?
+  end
+
+  def test_validates_inclusion_of_date_time_range
+    Topic.validates_inclusion_of(:created_at, in: 1.year.until(DateTime.current)..DateTime.current)
+    assert Topic.new(title: 'aaa', created_at: 2.years.until(DateTime.current)).invalid?
+    assert Topic.new(title: 'aaa', created_at: 3.months.until(DateTime.current)).valid?
+    assert Topic.new(title: 'aaa', created_at: 37.weeks.since(DateTime.current)).invalid?
+  end
+
   def test_validates_inclusion_of
     Topic.validates_inclusion_of( :title, :in => %w( a b c d e f g ) )
 
diff --git a/activemodel/test/models/topic.rb b/activemodel/test/models/topic.rb
index c9af78f..1411a09 100644
--- a/activemodel/test/models/topic.rb
+++ b/activemodel/test/models/topic.rb
@@ -6,7 +6,7 @@ class Topic
     super | [ :message ]
   end
 
-  attr_accessor :title, :author_name, :content, :approved
+  attr_accessor :title, :author_name, :content, :approved, :created_at
   attr_accessor :after_validation_performed
 
   after_validation :perform_after_validation
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index c5f1aad..72da1b7 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,3 +1,328 @@
+## Rails 4.0.1 (November 01, 2013) ##
+
+*   `NullRelation#pluck` takes a list of columns
+
+    The method signature in `NullRelation` was updated to mimic that in
+    `Calculations`.
+
+    *Derek Prior*
+
+*   `scope_chain` should not be mutated for other reflections.
+
+    Currently `scope_chain` uses same array for building different
+    `scope_chain` for different associations. During processing
+    these arrays are sometimes mutated and because of in-place
+    mutation the changed `scope_chain` impacts other reflections.
+
+    Fix is to dup the value before adding to the `scope_chain`.
+
+    Fixes #3882.
+
+    *Neeraj Singh*
+
+*   Prevent the inversed association from being reloaded on save.
+
+    Fixes #9499.
+
+    *Dmitry Polushkin*
+
+*   `Relation#order` quotes the column name if you pass a `Symbol`.
+    Fixes #11870.
+
+    Example:
+
+        # Before
+        Post.order(:id).to_sql == '... ORDER BY "posts".id ASC'
+
+        # After
+        Post.order(:id).to_sql == '... ORDER BY "posts"."id" ASC'
+
+    *Yves Senn*
+
+*   Generate subquery for `Relation` if it passed as array condition for `where`
+    method.
+
+    Example:
+
+        # Before
+        Blog.where('id in (?)', Blog.where(id: 1))
+        # =>  SELECT "blogs".* FROM "blogs"  WHERE "blogs"."id" = 1
+        # =>  SELECT "blogs".* FROM "blogs"  WHERE (id IN (1))
+
+        # After
+        Blog.where('id in (?)', Blog.where(id: 1).select(:id))
+        # =>  SELECT "blogs".* FROM "blogs"
+        #     WHERE "blogs"."id" IN (SELECT "blogs"."id" FROM "blogs"  WHERE "blogs"."id" = 1)
+
+    Fixes #12415.
+
+    *Paul Nikitochkin*
+
+*   For missed association exception message
+    which is raised in `ActiveRecord::Associations::Preloader` class
+    added owner record class name in order to simplify to find problem code.
+
+    *Paul Nikitochkin*
+
+*   Fixes bug when using includes combined with select, the select statement was overwritten.
+
+    Fixes #11773.
+
+    *Edo Balvers*
+
+*   Objects instantiated using a null relationship will now retain the
+    attributes of the where clause.
+
+    Fixes #11676, #11675, #11376.
+
+    *Paul Nikitochkin*, *Peter Brown*, *Nthalk*
+
+*   Fixed `ActiveRecord::Associations::CollectionAssociation#find`
+    when using `has_many` association with `:inverse_of` and finding an array of one element,
+    it should return an array of one element too.
+
+    *arthurnn*
+
+*   Callbacks on has_many should access the in memory parent if a inverse_of is set.
+
+    *arthurnn*
+
+*   Migration dump UUID default functions to schema.rb.
+
+    Fixes #10751.
+
+    *kennyj*
+
+*   Fixed a bug in `ActiveRecord::Associations::CollectionAssociation#find_by_scan`
+    when using `has_many` association with `:inverse_of` option and UUID primary key.
+
+    Fixes #10450.
+
+    *kennyj*
+
+*   Fix: joins association, with defined in the scope block constraints by using several
+    where constraints and at least of them is not `Arel::Nodes::Equality`,
+    generates invalid SQL expression.
+
+    Fixes: #11963
+
+    *Paul Nikitochkin*
+
+*   Make possible to run SQLite rake tasks without the `Rails` constant defined.
+
+    *Damien Mathieu*
+
+*   Allow Relation#from to accept other relations with bind values.
+
+    *Ryan Wallace*
+
+*   Make `find_in_batches` and `find_each` work without a logger.
+
+    *Dmitry Polushkin*
+
+*   Fix inserts with prepared statements disabled.
+
+    Fixes #12023.
+
+    *Rafael Mendonça França*
+
+*   Setting a has_one association on a new record no longer causes an empty
+    transaction.
+
+    *Dylan Thacker-Smith*
+
+*   Fix `AR::Relation#merge` sometimes failing to preserve `readonly(false)` flag.
+
+    *thedarkone*
+
+*   PostgreSQL adapter recognizes negative money values formatted with
+    parentheses (eg. `($1.25) # => -1.25`)).
+    Fixes #11899.
+
+    * Yves Senn*
+
+*   Do not load all child records for inverse case.
+
+    currently `post.comments.find(Comment.first.id)` would load all
+    comments for the given post to set the inverse association.
+
+    This has a huge performance penalty. Because if post has 100k
+    records and all these 100k records would be loaded in memory
+    even though the comment id was supplied.
+
+    Fix is to use in-memory records only if loaded? is true. Otherwise
+    load the records using full sql.
+
+    Fixes #10509.
+
+    *Neeraj Singh*
+
+*   `ActiveRecord::FinderMethods#exists?` returns `true`/`false` in all cases.
+
+    *Xavier Noria*
+
+*   Load fixtures from linked folders.
+
+    *Kassio Borges*
+
+*   Create a directory for sqlite3 file if not present on the system.
+
+    *Richard Schneeman*
+
+*   Removed redundant override of `xml` column definition for PG,
+    in order to use `xml` column type instead of `text`.
+
+    *Paul Nikitochkin*, *Michael Nikitochkin*
+
+*   Revert `ActiveRecord::Relation#order` change that make new order
+    prepend the old one.
+
+    Before:
+
+        User.order("name asc").order("created_at desc")
+        # SELECT * FROM users ORDER BY created_at desc, name asc
+
+    After:
+
+        User.order("name asc").order("created_at desc")
+        # SELECT * FROM users ORDER BY name asc, created_at desc
+
+    This also affects order defined in `default_scope` or any kind of associations.
+
+    *Rafael Mendonça França*
+
+*   When using optimistic locking, `update` was not passing the column to `quote_value`
+    to allow the connection adapter to properly determine how to quote the value. This was
+    affecting certain databases that use specific column types.
+
+    Fixes #6763.
+
+    *Alfred Wong*
+
+*   `change_column` for PostgreSQL adapter respects the `:array` option.
+
+    *Yves Senn*
+
+*   Fixes bug introduced by #3329. Now, when autosaving associations,
+    deletions happen before inserts and saves. This prevents a
+    'duplicate unique value' database error that would occur if a record being created had
+    the same value on a unique indexed field as that of a record being destroyed.
+
+    *Johnny Holton*
+
+*   Flatten merged join values before building the joins.
+
+    While joining values special treatment is given to string values.
+    By flattening the array it ensures that string values are detected
+    as strings and not arrays.
+
+    Fixes #10669.
+
+    *Neeraj Singh and iwiznia*
+
+*   Remove extra select and update queries on `save`/`touch`/`destroy` Active Record model
+    with belongs to reflection with option `touch: true`.
+
+    Fixes #11288.
+
+    *Paul Nikitochkin*
+
+*   Support array as root element in JSON fields.
+
+    *Alexey Noskov & Francesco Rodriguez*
+
+*   Apply default scope when joining associations. For example:
+
+        class Post < ActiveRecord::Base
+          default_scope -> { where published: true }
+        end
+
+        class Comment
+          belongs_to :post
+        end
+
+    When calling `Comment.joins(:post)`, we expect to receive only
+    comments on published posts, since that is the default scope for
+    posts.
+
+    Before this change, the default scope from `Post` was not applied,
+    so we'd get comments on unpublished posts.
+
+    *Jon Leighton*
+
+*   `inspect` on Active Record model classes does not initiate a
+    new connection. This means that calling `inspect`, when the
+    database is missing, will no longer raise an exception.
+
+    Fixes #10936.
+
+    Example:
+
+        Author.inspect # => "Author(no database connection)"
+
+    *Yves Senn*
+
+*   Fix mysql2 adapter raises the correct exception when executing a query on a
+    closed connection.
+
+    *Yves Senn*
+
+*   Fix the `:primary_key` option for `has_many` associations.
+
+    Fixes #10693.
+
+    *Yves Senn*
+
+*   Fix bug where tiny types are incorectly coerced as booleand when the length is more than 1.
+
+    Fixes #10620.
+
+    *Aaron Patterson*
+
+*   Also support extensions in PostgreSQL 9.1. This feature has been supported since 9.1.
+
+    *kennyj*
+
+*   Deprecate `ConnectionAdapters::SchemaStatements#distinct`,
+    as it is no longer used by internals.
+
+    *Ben Woosley#
+
+*   Remove not needed bind variables. Port of commit #5082345.
+
+    Fixes #10958.
+
+    *Neeraj Singh*
+
+*   Confirm a record has not already been destroyed before decrementing counter cache.
+
+    *Ben Tucker*
+
+*   Fixed a bug in `ActiveRecord#sanitize_sql_hash_for_conditions` in which
+    `self.class` is an argument to `PredicateBuilder#build_from_hash`
+    causing `PredicateBuilder` to call non-existent method
+    `Class#reflect_on_association`.
+
+    *Zach Ohlgren*
+
+*   While removing index if column option is missing then raise IrreversibleMigration exception.
+
+    Following code should raise `IrreversibleMigration`. But the code was
+    failing since options is an array and not a hash.
+
+        def change
+          change_table :users do |t|
+            t.remove_index [:name, :email]
+          end
+        end
+
+    Fix was to check if the options is a Hash before operating on it.
+
+    Fixes #10419.
+
+    *Neeraj Singh*
+
+
 ## Rails 4.0.0 (June 25, 2013) ##
 
 *   Fix `add_column` with `array` option when using PostgreSQL. Fixes #10432
@@ -30,7 +355,6 @@
 
     *Adam Anderson*
 
-
 *   Fix pending migrations error when loading schema and `ActiveRecord::Base.table_name_prefix`
     is not blank.
 
@@ -2046,7 +2370,7 @@
 *   The primary key is always initialized in the @attributes hash to `nil` (unless
     another value has been specified).
 
-    *Aaron Paterson*
+    *Aaron Patterson*
 
 *   In previous releases, the following would generate a single query with
     an `OUTER JOIN comments`, rather than two separate queries:
@@ -2098,5 +2422,4 @@
 
     *Aaron Patterson*
 
-
 Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/activerecord/CHANGELOG.md) for previous changes.
diff --git a/activerecord/README.rdoc b/activerecord/README.rdoc
index 822e460..19faeec 100644
--- a/activerecord/README.rdoc
+++ b/activerecord/README.rdoc
@@ -192,7 +192,7 @@ The latest version of Active Record can be installed with RubyGems:
 
 Source code can be downloaded as part of the Rails project on GitHub:
 
-* https://github.com/rails/rails/tree/master/activerecord
+* https://github.com/rails/rails/tree/4-0-stable/activerecord
 
 
 == License
diff --git a/activerecord/Rakefile b/activerecord/Rakefile
index 0523314..cd73489 100644
--- a/activerecord/Rakefile
+++ b/activerecord/Rakefile
@@ -125,8 +125,6 @@ namespace :postgresql do
     %w(arunit arunit2).each do |db|
       if version < "9.1.0"
         puts "Please prepare hstore data type. See http://www.postgresql.org/docs/9.0/static/hstore.html"
-      else
-        %x( psql #{config[db]['database']} -c "CREATE EXTENSION hstore;" )
       end
     end
   end
diff --git a/activerecord/lib/active_record.rb b/activerecord/lib/active_record.rb
index 0330c0f..994cacb 100644
--- a/activerecord/lib/active_record.rb
+++ b/activerecord/lib/active_record.rb
@@ -76,6 +76,7 @@ module ActiveRecord
     autoload :AutosaveAssociation
 
     autoload :Relation
+    autoload :AssociationRelation
     autoload :NullRelation
 
     autoload_under 'relation' do
diff --git a/activerecord/lib/active_record/association_relation.rb b/activerecord/lib/active_record/association_relation.rb
new file mode 100644
index 0000000..20516bb
--- /dev/null
+++ b/activerecord/lib/active_record/association_relation.rb
@@ -0,0 +1,18 @@
+module ActiveRecord
+  class AssociationRelation < Relation
+    def initialize(klass, table, association)
+      super(klass, table)
+      @association = association
+    end
+
+    def proxy_association
+      @association
+    end
+
+    private
+
+    def exec_queries
+      super.each { |r| @association.set_inverse_instance r }
+    end
+  end
+end
diff --git a/activerecord/lib/active_record/associations/association.rb b/activerecord/lib/active_record/associations/association.rb
index 710babe..5bc8673 100644
--- a/activerecord/lib/active_record/associations/association.rb
+++ b/activerecord/lib/active_record/associations/association.rb
@@ -18,6 +18,7 @@ module ActiveRecord
     #         HasManyThroughAssociation + ThroughAssociation
     class Association #:nodoc:
       attr_reader :owner, :target, :reflection
+      attr_accessor :inversed
 
       delegate :options, :to => :reflection
 
@@ -43,6 +44,7 @@ module ActiveRecord
         @loaded = false
         @target = nil
         @stale_state = nil
+        @inversed = false
       end
 
       # Reloads the \target and returns +self+ on success.
@@ -60,8 +62,9 @@ module ActiveRecord
 
       # Asserts the \target has been loaded setting the \loaded flag to +true+.
       def loaded!
-        @loaded      = true
+        @loaded = true
         @stale_state = stale_state
+        @inversed = false
       end
 
       # The target is stale if the target no longer points to the record(s) that the
@@ -71,7 +74,7 @@ module ActiveRecord
       #
       # Note that if the target has not been loaded, it is not considered stale.
       def stale_target?
-        loaded? && @stale_state != stale_state
+        !inversed && loaded? && @stale_state != stale_state
       end
 
       # Sets the target of this association to <tt>\target</tt>, and the \loaded flag to +true+.
@@ -110,6 +113,7 @@ module ActiveRecord
         if record && invertible_for?(record)
           inverse = record.association(inverse_reflection_for(record).name)
           inverse.target = owner
+          inverse.inversed = true
         end
       end
 
@@ -122,7 +126,11 @@ module ActiveRecord
       # Can be overridden (i.e. in ThroughAssociation) to merge in other scopes (i.e. the
       # through association's scope)
       def target_scope
-        klass.all
+        all = klass.all
+        scope = AssociationRelation.new(klass, klass.arel_table, self)
+        scope.merge! all
+        scope.default_scoped = all.default_scoped?
+        scope
       end
 
       # Loads the \target if needed and returns it.
diff --git a/activerecord/lib/active_record/associations/builder/belongs_to.rb b/activerecord/lib/active_record/associations/builder/belongs_to.rb
index 543a024..19a7547 100644
--- a/activerecord/lib/active_record/associations/builder/belongs_to.rb
+++ b/activerecord/lib/active_record/associations/builder/belongs_to.rb
@@ -34,7 +34,9 @@ module ActiveRecord::Associations::Builder
         def belongs_to_counter_cache_before_destroy_for_#{name}
           unless destroyed_by_association && destroyed_by_association.foreign_key.to_sym == #{foreign_key.to_sym.inspect}
             record = #{name}
-            record.class.decrement_counter(:#{cache_column}, record.id) unless record.nil?
+            if record && !self.destroyed?
+              record.class.decrement_counter(:#{cache_column}, record.id)
+            end
           end
         end
 
@@ -68,7 +70,7 @@ module ActiveRecord::Associations::Builder
       mixin.class_eval <<-CODE, __FILE__, __LINE__ + 1
         def belongs_to_touch_after_save_or_destroy_for_#{name}
           foreign_key_field = #{reflection.foreign_key.inspect}
-          old_foreign_id    = attribute_was(foreign_key_field)
+          old_foreign_id    = changed_attributes[foreign_key_field]
 
           if old_foreign_id
             klass      = association(#{name.inspect}).klass
diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb
index 2a00ac1..10ea669 100644
--- a/activerecord/lib/active_record/associations/collection_association.rb
+++ b/activerecord/lib/active_record/associations/collection_association.rb
@@ -81,15 +81,15 @@ module ActiveRecord
         else
           if options[:finder_sql]
             find_by_scan(*args)
-          elsif options[:inverse_of]
-            args = args.flatten
-            raise RecordNotFound, "Couldn't find #{scope.klass.name} without an ID" if args.blank?
+          elsif options[:inverse_of] && loaded?
+            args_flatten = args.flatten
+            raise RecordNotFound, "Couldn't find #{scope.klass.name} without an ID" if args_flatten.blank?
 
             result = find_by_scan(*args)
 
             result_size = Array(result).size
-            if !result || result_size != args.size
-              scope.raise_record_not_found_exception!(args, result_size, args.size)
+            if !result || result_size != args_flatten.size
+              scope.raise_record_not_found_exception!(args_flatten, result_size, args_flatten.size)
             else
               result
             end
@@ -583,14 +583,14 @@ module ActiveRecord
         # specified, then #find scans the entire collection.
         def find_by_scan(*args)
           expects_array = args.first.kind_of?(Array)
-          ids           = args.flatten.compact.map{ |arg| arg.to_i }.uniq
+          ids           = args.flatten.compact.map{ |arg| arg.to_s }.uniq
 
           if ids.size == 1
             id = ids.first
-            record = load_target.detect { |r| id == r.id }
+            record = load_target.detect { |r| id == r.id.to_s }
             expects_array ? [ record ] : record
           else
-            load_target.select { |r| ids.include?(r.id) }
+            load_target.select { |r| ids.include?(r.id.to_s) }
           end
         end
 
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb
index 56e57cc..d6902a7 100644
--- a/activerecord/lib/active_record/associations/collection_proxy.rb
+++ b/activerecord/lib/active_record/associations/collection_proxy.rb
@@ -830,7 +830,7 @@ module ActiveRecord
       #   person.pets.include?(Pet.find(20)) # => true
       #   person.pets.include?(Pet.find(21)) # => false
       def include?(record)
-        @association.include?(record)
+        !!@association.include?(record)
       end
 
       def proxy_association
@@ -847,9 +847,7 @@ module ActiveRecord
 
       # Returns a <tt>Relation</tt> object for the records in this association
       def scope
-        @association.scope.tap do |scope|
-          scope.proxy_association = @association
-        end
+        @association.scope
       end
 
       # :nodoc:
diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb
index 29fae80..95822af 100644
--- a/activerecord/lib/active_record/associations/has_many_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_association.rb
@@ -32,6 +32,7 @@ module ActiveRecord
 
       def insert_record(record, validate = true, raise = false)
         set_owner_attributes(record)
+        set_inverse_instance(record)
 
         if raise
           record.save!(:validate => validate)
@@ -115,8 +116,7 @@ module ActiveRecord
             if records == :all
               scope = self.scope
             else
-              keys  = records.map { |r| r[reflection.association_primary_key] }
-              scope = self.scope.where(reflection.association_primary_key => keys)
+              scope = self.scope.where(reflection.klass.primary_key => records)
             end
 
             if method == :delete_all
diff --git a/activerecord/lib/active_record/associations/has_one_association.rb b/activerecord/lib/active_record/associations/has_one_association.rb
index 920038a..8edafcd 100644
--- a/activerecord/lib/active_record/associations/has_one_association.rb
+++ b/activerecord/lib/active_record/associations/has_one_association.rb
@@ -27,6 +27,8 @@ module ActiveRecord
 
         return self.target if !(target || record)
         if (target != record) || record.changed?
+          save &&= owner.persisted?
+
           transaction_if(save) do
             remove_target!(options[:dependent]) if target && !target.destroyed?
 
@@ -34,7 +36,7 @@ module ActiveRecord
               set_owner_attributes(record)
               set_inverse_instance(record)
 
-              if owner.persisted? && save && !record.save
+              if save && !record.save
                 nullify_owner_attributes(record)
                 set_owner_attributes(target) if target
                 raise RecordNotSaved, "Failed to save the new associated #{reflection.name}."
diff --git a/activerecord/lib/active_record/associations/join_dependency/join_association.rb b/activerecord/lib/active_record/associations/join_dependency/join_association.rb
index e4d1745..d88e62b 100644
--- a/activerecord/lib/active_record/associations/join_dependency/join_association.rb
+++ b/activerecord/lib/active_record/associations/join_dependency/join_association.rb
@@ -106,6 +106,8 @@ module ActiveRecord
               ]
             end
 
+            scope_chain_items += [reflection.klass.send(:build_default_scope)].compact
+
             scope_chain_items.each do |item|
               unless item.is_a?(Relation)
                 item = ActiveRecord::Relation.new(reflection.klass, table).instance_exec(self, &item)
diff --git a/activerecord/lib/active_record/associations/join_dependency/join_part.rb b/activerecord/lib/active_record/associations/join_dependency/join_part.rb
index b534569..8024105 100644
--- a/activerecord/lib/active_record/associations/join_dependency/join_part.rb
+++ b/activerecord/lib/active_record/associations/join_dependency/join_part.rb
@@ -62,7 +62,20 @@ module ActiveRecord
         end
 
         def extract_record(row)
-          Hash[column_names_with_alias.map{|cn, an| [cn, row[an]]}]
+          # This code is performance critical as it is called per row.
+          # see: https://github.com/rails/rails/pull/12185
+          hash = {}
+
+          index = 0
+          length = column_names_with_alias.length
+
+          while index < length
+            column_name, alias_name = column_names_with_alias[index]
+            hash[column_name] = row[alias_name]
+            index += 1
+          end
+
+          hash
         end
 
         def record_id(row)
diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb
index 82bf426..53742cc 100644
--- a/activerecord/lib/active_record/associations/preloader.rb
+++ b/activerecord/lib/active_record/associations/preloader.rb
@@ -141,10 +141,11 @@ module ActiveRecord
 
       def records_by_reflection(association)
         records.group_by do |record|
-          reflection = record.class.reflections[association]
+          record_class = record.class
+          reflection = record_class.reflections[association]
 
           unless reflection
-            raise ActiveRecord::ConfigurationError, "Association named '#{association}' was not found; " \
+            raise ActiveRecord::ConfigurationError, "Association named '#{association}' was not found on #{record_class.name}; " \
                                                     "perhaps you misspelled it?"
           end
 
diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb
index 609c6e8..bb49492 100644
--- a/activerecord/lib/active_record/attribute_methods.rb
+++ b/activerecord/lib/active_record/attribute_methods.rb
@@ -1,4 +1,5 @@
 require 'active_support/core_ext/enumerable'
+require 'mutex_m'
 
 module ActiveRecord
   # = Active Record Attribute Methods
@@ -7,6 +8,7 @@ module ActiveRecord
     include ActiveModel::AttributeMethods
 
     included do
+      initialize_generated_modules
       include Read
       include Write
       include BeforeTypeCast
@@ -18,12 +20,34 @@ module ActiveRecord
     end
 
     module ClassMethods
+      def inherited(child_class) #:nodoc:
+        child_class.initialize_generated_modules
+        super
+      end
+
+      def initialize_generated_modules # :nodoc:
+        @generated_attribute_methods = Module.new {
+          extend Mutex_m
+
+          const_set :AttrNames, Module.new {
+            def self.set_name_cache(name, value)
+              const_name = "ATTR_#{name}"
+              unless const_defined? const_name
+                const_set const_name, value.dup.freeze
+              end
+            end
+          }
+        }
+        @attribute_methods_generated = false
+        include @generated_attribute_methods
+      end
+
       # Generates all the attribute related methods for columns in the database
       # accessors, mutators and query methods.
       def define_attribute_methods # :nodoc:
         # Use a mutex; we don't want two thread simultaneously trying to define
         # attribute methods.
-        @attribute_methods_mutex.synchronize do
+        generated_attribute_methods.synchronize do
           return if attribute_methods_generated?
           superclass.define_attribute_methods unless self == base_class
           super(column_names)
@@ -32,7 +56,7 @@ module ActiveRecord
       end
 
       def attribute_methods_generated? # :nodoc:
-        @attribute_methods_generated ||= false
+        @attribute_methods_generated
       end
 
       def undefine_attribute_methods # :nodoc:
diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb
index 506f5d7..c60a735 100644
--- a/activerecord/lib/active_record/attribute_methods/read.rb
+++ b/activerecord/lib/active_record/attribute_methods/read.rb
@@ -33,8 +33,11 @@ module ActiveRecord
         protected
 
         # We want to generate the methods via module_eval rather than
-        # define_method, because define_method is slower on dispatch and
-        # uses more memory (because it creates a closure).
+        # define_method, because define_method is slower on dispatch.
+        # Evaluating many similar methods may use more memory as the instruction
+        # sequences are duplicated and cached (in MRI).  define_method may
+        # be slower on dispatch, but if you're careful about the closure
+        # created, then define_method will consume much less memory.
         #
         # But sometimes the database might return columns with
         # characters that are not allowed in normal method names (like
@@ -49,6 +52,8 @@ module ActiveRecord
         # key the @attributes_cache in read_attribute.
         def define_method_attribute(name)
           safe_name = name.unpack('h*').first
+          generated_attribute_methods::AttrNames.set_name_cache safe_name, name
+
           generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
             def __temp__#{safe_name}
               read_attribute(AttrNames::ATTR_#{safe_name}) { |n| missing_attribute(n, caller) }
@@ -77,13 +82,14 @@ module ActiveRecord
         # We use #[] first as a perf optimization for non-nil values. See https://gist.github.com/jonleighton/3552829.
         name = attr_name.to_s
         @attributes_cache[name] || @attributes_cache.fetch(name) {
-          column = @columns_hash.fetch(name) {
-            return @attributes.fetch(name) {
-              if name == 'id' && self.class.primary_key != name
-                read_attribute(self.class.primary_key)
-              end
-            }
-          }
+          column = @column_types_override[name] if @column_types_override
+          column ||= @column_types[name]
+
+          return @attributes.fetch(name) {
+            if name == 'id' && self.class.primary_key != name
+              read_attribute(self.class.primary_key)
+            end
+          } unless column
 
           value = @attributes.fetch(name) {
             return block_given? ? yield(name) : nil
diff --git a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
index 41b5a6e..f168282 100644
--- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
+++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
@@ -51,7 +51,7 @@ module ActiveRecord
         def create_time_zone_conversion_attribute?(name, column)
           time_zone_aware_attributes &&
             !self.skip_time_zone_conversion_for_attributes.include?(name.to_sym) &&
-            [:datetime, :timestamp].include?(column.type)
+            (:datetime == column.type || :timestamp == column.type)
         end
       end
     end
diff --git a/activerecord/lib/active_record/attribute_methods/write.rb b/activerecord/lib/active_record/attribute_methods/write.rb
index cd33494..541856c 100644
--- a/activerecord/lib/active_record/attribute_methods/write.rb
+++ b/activerecord/lib/active_record/attribute_methods/write.rb
@@ -14,6 +14,8 @@ module ActiveRecord
         # this code.
         def define_method_attribute=(name)
           safe_name = name.unpack('h*').first
+          generated_attribute_methods::AttrNames.set_name_cache safe_name, name
+
           generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1
             def __temp__#{safe_name}=(value)
               write_attribute(AttrNames::ATTR_#{safe_name}, value)
diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb
index 356d407..c991c87 100644
--- a/activerecord/lib/active_record/autosave_association.rb
+++ b/activerecord/lib/active_record/autosave_association.rb
@@ -335,15 +335,19 @@ module ActiveRecord
         autosave = reflection.options[:autosave]
 
         if records = associated_records_to_validate_or_save(association, @new_record_before_save, autosave)
-          records_to_destroy = []
+
+          if autosave
+            records_to_destroy = records.select(&:marked_for_destruction?)
+            records_to_destroy.each { |record| association.destroy(record) }
+            records -= records_to_destroy
+          end
+
           records.each do |record|
             next if record.destroyed?
 
             saved = true
 
-            if autosave && record.marked_for_destruction?
-              records_to_destroy << record
-            elsif autosave != false && (@new_record_before_save || record.new_record?)
+            if autosave != false && (@new_record_before_save || record.new_record?)
               if autosave
                 saved = association.insert_record(record, false)
               else
@@ -355,10 +359,6 @@ module ActiveRecord
 
             raise ActiveRecord::Rollback unless saved
           end
-
-          records_to_destroy.each do |record|
-            association.destroy(record)
-          end
         end
 
         # reconstruct the scope now that we know the owner's id
diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb
index e4c484d..128a937 100644
--- a/activerecord/lib/active_record/callbacks.rb
+++ b/activerecord/lib/active_record/callbacks.rb
@@ -23,11 +23,14 @@ module ActiveRecord
   # Check out <tt>ActiveRecord::Transactions</tt> for more details about <tt>after_commit</tt> and
   # <tt>after_rollback</tt>.
   #
+  # Additionally, an <tt>after_touch</tt> callback is triggered whenever an
+  # object is touched.
+  #
   # Lastly an <tt>after_find</tt> and <tt>after_initialize</tt> callback is triggered for each object that
   # is found and instantiated by a finder, with <tt>after_initialize</tt> being triggered after new objects
   # are instantiated as well.
   #
-  # That's a total of twelve callbacks, which gives you immense power to react and prepare for each state in the
+  # There are nineteen callbacks in total, which give you immense power to react and prepare for each state in the
   # Active Record life cycle. The sequence for calling <tt>Base#save</tt> for an existing record is similar,
   # except that each <tt>_create</tt> callback is replaced by the corresponding <tt>_update</tt> callback.
   #
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
index c64b542..adc8c73 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb
@@ -377,14 +377,14 @@ module ActiveRecord
           update_sql(sql, name)
         end
 
-      def sql_for_insert(sql, pk, id_value, sequence_name, binds)
-        [sql, binds]
-      end
+        def sql_for_insert(sql, pk, id_value, sequence_name, binds)
+          [sql, binds]
+        end
 
-      def last_inserted_id(result)
-        row = result.rows.first
-        row && row.first
-      end
+        def last_inserted_id(result)
+          row = result.rows.first
+          row && row.first
+        end
     end
   end
 end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
index 890f0a9..aac0a52 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -706,12 +706,21 @@ module ActiveRecord
       end
 
       # SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
-      # Both PostgreSQL and Oracle overrides this for custom DISTINCT syntax.
       #
-      #   distinct("posts.id", "posts.created_at desc")
+      #   distinct("posts.id", ["posts.created_at desc"])
       #
       def distinct(columns, order_by)
-        "DISTINCT #{columns}"
+        ActiveSupport::Deprecation.warn("#distinct is deprecated and shall be removed from future releases.")
+        "DISTINCT #{columns_for_distinct(columns, order_by)}"
+      end
+
+      # Given a set of columns and an ORDER BY clause, returns the columns for a SELECT DISTINCT.
+      # Both PostgreSQL and Oracle overrides this for custom DISTINCT syntax - they
+      # require the order columns appear in the SELECT.
+      #
+      #   columns_for_distinct("posts.id", ["posts.created_at desc"])
+      def columns_for_distinct(columns, orders) # :nodoc:
+        columns
       end
 
       # Adds timestamps (+created_at+ and +updated_at+) columns to the named table.
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index 26586f0..cfbb05c 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -99,6 +99,7 @@ module ActiveRecord
         @query_cache_enabled = false
         @schema_cache        = SchemaCache.new self
         @visitor             = nil
+        @prepared_statements = false
       end
 
       def valid_type?(type)
@@ -197,10 +198,11 @@ module ActiveRecord
       end
 
       def unprepared_statement
-        old, @visitor = @visitor, unprepared_visitor
+        old_prepared_statements, @prepared_statements = @prepared_statements, false
+        old_visitor, @visitor = @visitor, unprepared_visitor
         yield
       ensure
-        @visitor = old
+        @visitor, @prepared_statements = old_visitor, old_prepared_statements
       end
 
       # Returns the human-readable name of the adapter. Use mixed case - one
@@ -280,6 +282,14 @@ module ActiveRecord
         false
       end
 
+      # This is meant to be implemented by the adapters that support extensions
+      def disable_extension(name)
+      end
+
+      # This is meant to be implemented by the adapters that support extensions
+      def enable_extension(name)
+      end
+
       # A list of extensions, to be filled in by adapters that support them. At
       # the moment only postgresql does.
       def extensions
@@ -435,6 +445,10 @@ module ActiveRecord
         # override in derived class
         ActiveRecord::StatementInvalid.new(message, exception)
       end
+
+      def without_prepared_statement?(binds)
+        !@prepared_statements || binds.empty?
+      end
     end
   end
 end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
old mode 100644
new mode 100755
index d098ded..ad54bd7
--- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb
@@ -165,6 +165,7 @@ module ActiveRecord
         @quoted_column_names, @quoted_table_names = {}, {}
 
         if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
+          @prepared_statements = true
           @visitor = Arel::Visitors::MySQL.new self
         else
           @visitor = unprepared_visitor
@@ -460,7 +461,8 @@ module ActiveRecord
         sql = "SHOW FULL FIELDS FROM #{quote_table_name(table_name)}"
         execute_and_free(sql, 'SCHEMA') do |result|
           each_hash(result).map do |field|
-            new_column(field[:Field], field[:Default], field[:Type], field[:Null] == "YES", field[:Collation], field[:Extra])
+            field_name = set_field_encoding(field[:Field])
+            new_column(field_name, field[:Default], field[:Type], field[:Null] == "YES", field[:Collation], field[:Extra])
           end
         end
       end
diff --git a/activerecord/lib/active_record/connection_adapters/column.rb b/activerecord/lib/active_record/connection_adapters/column.rb
index 609ccc2..fd37cb0 100644
--- a/activerecord/lib/active_record/connection_adapters/column.rb
+++ b/activerecord/lib/active_record/connection_adapters/column.rb
@@ -13,7 +13,7 @@ module ActiveRecord
         ISO_DATETIME = /\A(\d{4})-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)(\.\d+)?\z/
       end
 
-      attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale
+      attr_reader :name, :default, :type, :limit, :null, :sql_type, :precision, :scale, :default_function
       attr_accessor :primary, :coder
 
       alias :encoded? :coder
@@ -27,16 +27,17 @@ module ActiveRecord
       # It will be mapped to one of the standard Rails SQL types in the <tt>type</tt> attribute.
       # +null+ determines if this column allows +NULL+ values.
       def initialize(name, default, sql_type = nil, null = true)
-        @name      = name
-        @sql_type  = sql_type
-        @null      = null
-        @limit     = extract_limit(sql_type)
-        @precision = extract_precision(sql_type)
-        @scale     = extract_scale(sql_type)
-        @type      = simplified_type(sql_type)
-        @default   = extract_default(default)
-        @primary   = nil
-        @coder     = nil
+        @name             = name
+        @sql_type         = sql_type
+        @null             = null
+        @limit            = extract_limit(sql_type)
+        @precision        = extract_precision(sql_type)
+        @scale            = extract_scale(sql_type)
+        @type             = simplified_type(sql_type)
+        @default          = extract_default(default)
+        @default_function = nil
+        @primary          = nil
+        @coder            = nil
       end
 
       # Returns +true+ if the column is either of type string or text.
diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
old mode 100644
new mode 100755
index 530a27d..6b985dd
--- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
@@ -213,9 +213,11 @@ module ActiveRecord
 
       # Executes the SQL statement in the context of this connection.
       def execute(sql, name = nil)
-        # make sure we carry over any changes to ActiveRecord::Base.default_timezone that have been
-        # made since we established the connection
-        @connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone
+        if @connection
+          # make sure we carry over any changes to ActiveRecord::Base.default_timezone that have been
+          # made since we established the connection
+          @connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone
+        end
 
         super
       end
@@ -268,6 +270,10 @@ module ActiveRecord
       def version
         @version ||= @connection.info[:version].scan(/^(\d+)\.(\d+)\.(\d+)/).flatten.map { |v| v.to_i }
       end
+
+      def set_field_encoding field_name
+        field_name
+      end
     end
   end
 end
diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
old mode 100644
new mode 100755
index f235214..88c9494
--- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb
@@ -279,11 +279,7 @@ module ActiveRecord
       end
 
       def exec_query(sql, name = 'SQL', binds = [])
-        # If the configuration sets prepared_statements:false, binds will
-        # always be empty, since the bind variables will have been already
-        # substituted and removed from binds by BindVisitor, so this will
-        # effectively disable prepared statement usage completely.
-        if binds.empty?
+        if without_prepared_statement?(binds)
           result_set, affected_rows = exec_without_stmt(sql, name)
         else
           result_set, affected_rows = exec_stmt(sql, name, binds)
@@ -393,6 +389,14 @@ module ActiveRecord
           TYPES[new] = TYPES[old]
         end
 
+        def self.find_type(field)
+          if field.type == Mysql::Field::TYPE_TINY && field.length > 1
+            TYPES[Mysql::Field::TYPE_LONG]
+          else
+            TYPES.fetch(field.type) { Fields::Identity.new }
+          end
+        end
+
         register_type Mysql::Field::TYPE_TINY,    Fields::Boolean.new
         register_type Mysql::Field::TYPE_LONG,    Fields::Integer.new
         alias_type Mysql::Field::TYPE_LONGLONG,   Mysql::Field::TYPE_LONG
@@ -425,9 +429,7 @@ module ActiveRecord
               if field.decimals > 0
                 types[field.name] = Fields::Decimal.new
               else
-                types[field.name] = Fields::TYPES.fetch(field.type) {
-                  Fields::Identity.new
-                }
+                types[field.name] = Fields.find_type field
               end
             }
             result_set = ActiveRecord::Result.new(types.keys, result.to_a, types)
@@ -501,12 +503,12 @@ module ActiveRecord
             cols = cache[:cols] ||= metadata.fetch_fields.map { |field|
               field.name
             }
+            metadata.free
           end
 
           result_set = ActiveRecord::Result.new(cols, stmt.to_a) if cols
           affected_rows = stmt.affected_rows
 
-          stmt.result_metadata.free if cols
           stmt.free_result
           stmt.close if binds.empty?
 
@@ -553,6 +555,14 @@ module ActiveRecord
       def version
         @version ||= @connection.server_info.scan(/^(\d+)\.(\d+)\.(\d+)/).flatten.map { |v| v.to_i }
       end
+
+      def set_field_encoding field_name
+        field_name.force_encoding(client_encoding)
+        if internal_enc = Encoding.default_internal
+          field_name = field_name.encode!(internal_enc)
+        end
+        field_name
+      end
     end
   end
 end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb b/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb
index a9ef11a..a73f0ac 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/cast.rb
@@ -60,7 +60,7 @@ module ActiveRecord
         end
 
         def json_to_string(object)
-          if Hash === object
+          if Hash === object || Array === object
             ActiveSupport::JSON.encode(object)
           else
             object
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
index 9b5170f..7237af8 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb
@@ -135,11 +135,12 @@ module ActiveRecord
 
         def exec_query(sql, name = 'SQL', binds = [])
           log(sql, name, binds) do
-            result = binds.empty? ? exec_no_cache(sql, binds) :
-                                    exec_cache(sql, binds)
+            result = without_prepared_statement?(binds) ? exec_no_cache(sql, binds) :
+                                                          exec_cache(sql, binds)
 
             types = {}
-            result.fields.each_with_index do |fname, i|
+            fields = result.fields
+            fields.each_with_index do |fname, i|
               ftype = result.ftype i
               fmod  = result.fmod i
               types[fname] = OID::TYPE_MAP.fetch(ftype, fmod) { |oid, mod|
@@ -148,7 +149,7 @@ module ActiveRecord
               }
             end
 
-            ret = ActiveRecord::Result.new(result.fields, result.values, types)
+            ret = ActiveRecord::Result.new(fields, result.values, types)
             result.clear
             return ret
           end
@@ -156,8 +157,8 @@ module ActiveRecord
 
         def exec_delete(sql, name = 'SQL', binds = [])
           log(sql, name, binds) do
-            result = binds.empty? ? exec_no_cache(sql, binds) :
-                                    exec_cache(sql, binds)
+            result = without_prepared_statement?(binds) ? exec_no_cache(sql, binds) :
+                                                          exec_cache(sql, binds)
             affected = result.cmd_tuples
             result.clear
             affected
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb
index 1be116c..ac92fec 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid.rb
@@ -38,12 +38,17 @@ module ActiveRecord
         class Money < Type
           def type_cast(value)
             return if value.nil?
+            return value unless String === value
 
             # Because money output is formatted according to the locale, there are two
             # cases to consider (note the decimal separators):
             #  (1) $12,345,678.12
             #  (2) $12.345.678,12
+            # Negative values are represented as follows:
+            #  (3) -$2.55
+            #  (4) ($2.55)
 
+            value.sub!(/^\((.+)\)$/, '-\1') # (4)
             case value
             when /^-?\D+[\d,]+\.\d{2}$/  # (1)
               value.gsub!(/[^-\d.]/, '')
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
index 40a3b82..e9daa5d 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
@@ -30,6 +30,7 @@ module ActiveRecord
           when Array
             case sql_type
             when 'point' then super(PostgreSQLColumn.point_to_string(value))
+            when 'json' then super(PostgreSQLColumn.json_to_string(value))
             else
               if column.array
                 "'#{PostgreSQLColumn.array_to_string(value, column, self).gsub(/'/, "''")}'"
@@ -98,6 +99,7 @@ module ActiveRecord
           when Array
             case column.sql_type
             when 'point' then PostgreSQLColumn.point_to_string(value)
+            when 'json' then PostgreSQLColumn.json_to_string(value)
             else
               return super(value, column) unless column.array
               PostgreSQLColumn.array_to_string(value, column, self)
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
index d9b807b..0e4f55d 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
@@ -321,6 +321,7 @@ module ActiveRecord
             result = query(<<-end_sql, 'SCHEMA')[0]
               SELECT attr.attname,
                 CASE
+                  WHEN pg_get_expr(def.adbin, def.adrelid) !~* 'nextval' THEN NULL
                   WHEN split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2) ~ '.' THEN
                     substr(split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2),
                            strpos(split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2), '.')+1)
@@ -332,7 +333,7 @@ module ActiveRecord
               JOIN pg_constraint  cons ON (conrelid = adrelid AND adnum = conkey[1])
               WHERE t.oid = '#{quote_table_name(table)}'::regclass
                 AND cons.contype = 'p'
-                AND pg_get_expr(def.adbin, def.adrelid) ~* 'nextval'
+                AND pg_get_expr(def.adbin, def.adrelid) ~* 'nextval|uuid_generate'
             end_sql
           end
 
@@ -383,8 +384,9 @@ module ActiveRecord
         def change_column(table_name, column_name, type, options = {})
           clear_cache!
           quoted_table_name = quote_table_name(table_name)
-
-          execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
+          sql_type = type_to_sql(type, options[:limit], options[:precision], options[:scale])
+          sql_type << "[]" if options[:array]
+          execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{sql_type}"
 
           change_column_default(table_name, column_name, options[:default]) if options_include_default?(options)
           change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null)
@@ -466,14 +468,9 @@ module ActiveRecord
           end
         end
 
-        # Returns a SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
-        #
         # PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and
         # requires that the ORDER BY include the distinct column.
-        #
-        #   distinct("posts.id", ["posts.created_at desc"])
-        #   # => "DISTINCT posts.id, posts.created_at AS alias_0"
-        def distinct(columns, orders) #:nodoc:
+        def columns_for_distinct(columns, orders) #:nodoc:
           order_columns = orders.map{ |s|
               # Convert Arel node to string
               s = s.to_sql unless s.is_a?(String)
@@ -481,7 +478,7 @@ module ActiveRecord
               s.gsub(/\s+(ASC|DESC)\s*(NULLS\s+(FIRST|LAST)\s*)?/i, '')
             }.reject(&:blank?).map.with_index { |column, i| "#{column} AS alias_#{i}" }
 
-          [super].concat(order_columns).join(', ')
+          [super, *order_columns].join(', ')
         end
       end
     end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
index 6040eee..d8a5e88 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -49,13 +49,17 @@ module ActiveRecord
       # Instantiates a new PostgreSQL column definition in a table.
       def initialize(name, default, oid_type, sql_type = nil, null = true)
         @oid_type = oid_type
+        default_value     = self.class.extract_value_from_default(default)
+
         if sql_type =~ /\[\]$/
           @array = true
-          super(name, self.class.extract_value_from_default(default), sql_type[0..sql_type.length - 3], null)
+          super(name, default_value, sql_type[0..sql_type.length - 3], null)
         else
           @array = false
-          super(name, self.class.extract_value_from_default(default), sql_type, null)
+          super(name, default_value, sql_type, null)
         end
+
+        @default_function = default if has_default_function?(default_value, default)
       end
 
       # :stopdoc:
@@ -138,6 +142,10 @@ module ActiveRecord
 
       private
 
+        def has_default_function?(default_value, default)
+          !default_value && (%r{\w+\(.*\)} === default)
+        end
+
         def extract_limit(sql_type)
           case sql_type
           when /^bigint/i;    8
@@ -374,15 +382,11 @@ module ActiveRecord
           self
         end
 
-        def xml(options = {})
-          column(args[0], :text, options)
-        end
-
         private
 
-        def create_column_definition(name, type)
-          ColumnDefinition.new name, type
-        end
+          def create_column_definition(name, type)
+            ColumnDefinition.new name, type
+          end
       end
 
       class Table < ActiveRecord::ConnectionAdapters::Table
@@ -436,6 +440,7 @@ module ActiveRecord
       def prepare_column_options(column, types)
         spec = super
         spec[:array] = 'true' if column.respond_to?(:array) && column.array
+        spec[:default] = "\"#{column.default_function}\"" if column.default_function
         spec
       end
 
@@ -528,6 +533,7 @@ module ActiveRecord
         super(connection, logger)
 
         if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
+          @prepared_statements = true
           @visitor = Arel::Visitors::PostgreSQL.new self
         else
           @visitor = unprepared_visitor
@@ -623,9 +629,9 @@ module ActiveRecord
         true
       end
 
-      # Returns true if pg > 9.2
+      # Returns true if pg > 9.1
       def supports_extensions?
-        postgresql_version >= 90200
+        postgresql_version >= 90100
       end
 
       # Range datatypes weren't introduced until PostgreSQL 9.2
@@ -647,9 +653,9 @@ module ActiveRecord
 
       def extension_enabled?(name)
         if supports_extensions?
-          res = exec_query "SELECT EXISTS(SELECT * FROM pg_available_extensions WHERE name = '#{name}' AND installed_version IS NOT NULL)",
+          res = exec_query "SELECT EXISTS(SELECT * FROM pg_available_extensions WHERE name = '#{name}' AND installed_version IS NOT NULL) as enabled",
             'SCHEMA'
-          res.column_types['exists'].type_cast res.rows.first.first
+          res.column_types['enabled'].type_cast res.rows.first.first
         end
       end
 
diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
index 7d940fe..140dd55 100644
--- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb
@@ -17,12 +17,14 @@ module ActiveRecord
       # Allow database path relative to Rails.root, but only if
       # the database path is not the special path that tells
       # Sqlite to build a database only in memory.
-      if defined?(Rails.root) && ':memory:' != config[:database]
-        config[:database] = File.expand_path(config[:database], Rails.root)
+      if ':memory:' != config[:database]
+        config[:database] = File.expand_path(config[:database], Rails.root) if defined?(Rails.root)
+        dirname = File.dirname(config[:database])
+        Dir.mkdir(dirname) unless File.directory?(dirname)
       end
 
       db = SQLite3::Database.new(
-        config[:database],
+        config[:database].to_s,
         :results_as_hash => true
       )
 
@@ -111,6 +113,7 @@ module ActiveRecord
         @config = config
 
         if self.class.type_cast_config_to_boolean(config.fetch(:prepared_statements) { true })
+          @prepared_statements = true
           @visitor = Arel::Visitors::SQLite.new self
         else
           @visitor = unprepared_visitor
@@ -291,8 +294,8 @@ module ActiveRecord
       def exec_query(sql, name = nil, binds = [])
         log(sql, name, binds) do
 
-          # Don't cache statements without bind values
-          if binds.empty?
+          # Don't cache statements if they are not prepared
+          if without_prepared_statement?(binds)
             stmt    = @connection.prepare(sql)
             cols    = stmt.columns
             records = stmt.to_a
diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb
index ba05370..edaa28b 100644
--- a/activerecord/lib/active_record/core.rb
+++ b/activerecord/lib/active_record/core.rb
@@ -91,20 +91,8 @@ module ActiveRecord
     end
 
     module ClassMethods
-      def inherited(child_class) #:nodoc:
-        child_class.initialize_generated_modules
-        super
-      end
-
       def initialize_generated_modules
-        @attribute_methods_mutex = Mutex.new
-
-        # force attribute methods to be higher in inheritance hierarchy than other generated methods
-        generated_attribute_methods.const_set(:AttrNames, Module.new {
-          def self.const_missing(name)
-            const_set(name, [name.to_s.sub(/ATTR_/, '')].pack('h*').freeze)
-          end
-        })
+        super
 
         generated_feature_methods
       end
@@ -123,6 +111,8 @@ module ActiveRecord
           super
         elsif abstract_class?
           "#{super}(abstract)"
+        elsif !connected?
+          "#{super}(no database connection)"
         elsif table_exists?
           attr_list = columns.map { |c| "#{c.name}: #{c.type}" } * ', '
           "#{super}(#{attr_list})"
@@ -153,7 +143,7 @@ module ActiveRecord
           else
             superclass.arel_engine
           end
-       end
+        end
       end
 
       private
@@ -177,19 +167,22 @@ module ActiveRecord
     # ==== Example:
     #   # Instantiates a single new object
     #   User.new(first_name: 'Jamie')
-    def initialize(attributes = nil)
+    def initialize(attributes = nil, options = {})
       defaults = self.class.column_defaults.dup
       defaults.each { |k, v| defaults[k] = v.dup if v.duplicable? }
 
       @attributes   = self.class.initialize_attributes(defaults)
-      @columns_hash = self.class.column_types.dup
+      @column_types_override = nil
+      @column_types = self.class.column_types
 
       init_internals
       init_changed_attributes
       ensure_proper_type
       populate_with_current_scope_attributes
 
-      assign_attributes(attributes) if attributes
+      # +options+ argument is only needed to make protected_attributes gem easier to hook.
+      # Remove it when we drop support to this gem.
+      init_attributes(attributes, options) if attributes
 
       yield self if block_given?
       run_callbacks :initialize unless _initialize_callbacks.empty?
@@ -207,7 +200,8 @@ module ActiveRecord
     #   post.title # => 'hello world'
     def init_with(coder)
       @attributes   = self.class.initialize_attributes(coder['attributes'])
-      @columns_hash = self.class.column_types.merge(coder['column_types'] || {})
+      @column_types_override = coder['column_types']
+      @column_types = self.class.column_types
 
       init_internals
 
@@ -459,5 +453,11 @@ module ActiveRecord
         @changed_attributes[attr] = orig_value if _field_changed?(attr, orig_value, @attributes[attr])
       end
     end
+
+    # This method is needed to make protected_attributes gem easier to hook.
+    # Remove it when we drop support to this gem.
+    def init_attributes(attributes, options)
+      assign_attributes(attributes)
+    end
   end
 end
diff --git a/activerecord/lib/active_record/dynamic_matchers.rb b/activerecord/lib/active_record/dynamic_matchers.rb
index 3bac31c..e650ebc 100644
--- a/activerecord/lib/active_record/dynamic_matchers.rb
+++ b/activerecord/lib/active_record/dynamic_matchers.rb
@@ -35,7 +35,7 @@ module ActiveRecord
         end
 
         def pattern
-          /^#{prefix}_([_a-zA-Z]\w*)#{suffix}$/
+          @pattern ||= /\A#{prefix}_([_a-zA-Z]\w*)#{suffix}\Z/
         end
 
         def prefix
diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb
index 45dc26f..e3019c5 100644
--- a/activerecord/lib/active_record/fixtures.rb
+++ b/activerecord/lib/active_record/fixtures.rb
@@ -639,7 +639,7 @@ module ActiveRecord
       end
 
       def read_fixture_files
-        yaml_files = Dir["#{@path}/**/*.yml"].select { |f|
+        yaml_files = Dir["#{@path}/{**,*}/*.yml"].select { |f|
           ::File.file?(f)
         } + [yaml_file_path]
 
@@ -758,7 +758,7 @@ module ActiveRecord
 
       def fixtures(*fixture_set_names)
         if fixture_set_names.first == :all
-          fixture_set_names = Dir["#{fixture_path}/**/*.{yml}"]
+          fixture_set_names = Dir["#{fixture_path}/{**,*}/*.{yml}"]
           fixture_set_names.map! { |f| f[(fixture_path.to_s.size + 1)..-5] }
         else
           fixture_set_names = fixture_set_names.flatten.map { |n| n.to_s }
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
index 209de78..4e17668 100644
--- a/activerecord/lib/active_record/locking/optimistic.rb
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -82,7 +82,7 @@ module ActiveRecord
 
             stmt = relation.where(
               relation.table[self.class.primary_key].eq(id).and(
-                relation.table[lock_col].eq(self.class.quote_value(previous_lock_value))
+                relation.table[lock_col].eq(self.class.quote_value(previous_lock_value, column_for_attribute(lock_col)))
               )
             ).arel.compile_update(arel_attributes_with_values_for_update(attribute_names))
 
diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb
index 40c4f85..c15e7a4 100644
--- a/activerecord/lib/active_record/migration.rb
+++ b/activerecord/lib/active_record/migration.rb
@@ -32,7 +32,7 @@ module ActiveRecord
 
   class PendingMigrationError < ActiveRecordError#:nodoc:
     def initialize
-      super("Migrations are pending; run 'rake db:migrate RAILS_ENV=#{Rails.env}' to resolve this issue.")
+      super("Migrations are pending; run 'bin/rake db:migrate RAILS_ENV=#{Rails.env}' to resolve this issue.")
     end
   end
 
diff --git a/activerecord/lib/active_record/migration/command_recorder.rb b/activerecord/lib/active_record/migration/command_recorder.rb
index 79c5504..9782a48 100644
--- a/activerecord/lib/active_record/migration/command_recorder.rb
+++ b/activerecord/lib/active_record/migration/command_recorder.rb
@@ -144,7 +144,10 @@ module ActiveRecord
 
       def invert_remove_index(args)
         table, options = *args
-        raise ActiveRecord::IrreversibleMigration, "remove_index is only reversible if given a :column option." unless options && options[:column]
+
+        unless options && options.is_a?(Hash) && options[:column]
+          raise ActiveRecord::IrreversibleMigration, "remove_index is only reversible if given a :column option."
+        end
 
         options = options.dup
         [:add_index, [table, options.delete(:column), options]]
diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb
index ac2d2f2..e0b16b4 100644
--- a/activerecord/lib/active_record/model_schema.rb
+++ b/activerecord/lib/active_record/model_schema.rb
@@ -224,13 +224,20 @@ module ActiveRecord
       def decorate_columns(columns_hash) # :nodoc:
         return if columns_hash.empty?
 
-        columns_hash.each do |name, col|
-          if serialized_attributes.key?(name)
-            columns_hash[name] = AttributeMethods::Serialization::Type.new(col)
-          end
-          if create_time_zone_conversion_attribute?(name, col)
-            columns_hash[name] = AttributeMethods::TimeZoneConversion::Type.new(col)
-          end
+        @serialized_column_names ||= self.columns_hash.keys.find_all do |name|
+          serialized_attributes.key?(name)
+        end
+
+        @serialized_column_names.each do |name|
+          columns_hash[name] = AttributeMethods::Serialization::Type.new(columns_hash[name])
+        end
+
+        @time_zone_column_names ||= self.columns_hash.find_all do |name, col|
+          create_time_zone_conversion_attribute?(name, col)
+        end.map!(&:first)
+
+        @time_zone_column_names.each do |name|
+          columns_hash[name] = AttributeMethods::TimeZoneConversion::Type.new(columns_hash[name])
         end
 
         columns_hash
@@ -297,16 +304,19 @@ module ActiveRecord
         undefine_attribute_methods
         connection.schema_cache.clear_table_cache!(table_name) if table_exists?
 
-        @arel_engine          = nil
-        @column_defaults      = nil
-        @column_names         = nil
-        @columns              = nil
-        @columns_hash         = nil
-        @column_types         = nil
-        @content_columns      = nil
-        @dynamic_methods_hash = nil
-        @inheritance_column   = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column
-        @relation             = nil
+        @arel_engine             = nil
+        @column_defaults         = nil
+        @column_names            = nil
+        @columns                 = nil
+        @columns_hash            = nil
+        @column_types            = nil
+        @content_columns         = nil
+        @dynamic_methods_hash    = nil
+        @inheritance_column      = nil unless defined?(@explicit_inheritance_column) && @explicit_inheritance_column
+        @relation                = nil
+        @serialized_column_names = nil
+        @time_zone_column_names  = nil
+        @cached_time_zone        = nil
       end
 
       # This is a hook for use by modules that need to do extra stuff to
diff --git a/activerecord/lib/active_record/null_relation.rb b/activerecord/lib/active_record/null_relation.rb
index 711fc8b..9820fc6 100644
--- a/activerecord/lib/active_record/null_relation.rb
+++ b/activerecord/lib/active_record/null_relation.rb
@@ -6,7 +6,7 @@ module ActiveRecord
       @records = []
     end
 
-    def pluck(_column_name)
+    def pluck(*column_names)
       []
     end
 
@@ -42,10 +42,6 @@ module ActiveRecord
       @to_sql ||= ""
     end
 
-    def where_values_hash
-      {}
-    end
-
     def count(*)
       0
     end
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index 1714bae..1d824b5 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -335,8 +335,17 @@ module ActiveRecord
 
     # Reloads the record from the database.
     #
-    # This method modifies the receiver in-place. Attributes are updated, and
-    # caches busted, in particular the associations cache.
+    # This method finds record by its primary key (which could be assigned manually) and
+    # modifies the receiver in-place:
+    #
+    #   account = Account.new
+    #   # => #<Account id: nil, email: nil>
+    #   account.id = 1
+    #   account.reload
+    #   # Account Load (1.2ms)  SELECT "accounts".* FROM "accounts" WHERE "accounts"."id" = $1 LIMIT 1  [["id", 1]]
+    #   # => #<Account id: 1, email: 'account at example.com'>
+    #
+    # Attributes are updated, and caches busted, in particular the associations cache.
     #
     # If the record no longer exists in the database <tt>ActiveRecord::RecordNotFound</tt>
     # is raised. Otherwise, in addition to the in-place modification the method
@@ -383,14 +392,16 @@ module ActiveRecord
         end
 
       @attributes.update(fresh_object.instance_variable_get('@attributes'))
-      @columns_hash = fresh_object.instance_variable_get('@columns_hash')
 
-      @attributes_cache = {}
+      @column_types           = self.class.column_types
+      @column_types_override  = fresh_object.instance_variable_get('@column_types_override')
+      @attributes_cache       = {}
       self
     end
 
     # Saves the record with the updated_at/on attributes set to the current time.
-    # Please note that no validation is performed and no callbacks are executed.
+    # Please note that no validation is performed and only the +after_touch+
+    # callback is executed.
     # If an attribute name is passed, that attribute is updated along with
     # updated_at/on attributes.
     #
diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb
index afb0be7..95ac41e 100644
--- a/activerecord/lib/active_record/railtie.rb
+++ b/activerecord/lib/active_record/railtie.rb
@@ -46,6 +46,7 @@ module ActiveRecord
           ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration
           ActiveRecord::Tasks::DatabaseTasks.migrations_paths = Rails.application.paths['db/migrate'].to_a
           ActiveRecord::Tasks::DatabaseTasks.fixtures_path = File.join Rails.root, 'test', 'fixtures'
+          ActiveRecord::Tasks::DatabaseTasks.root = Rails.root
 
           if defined?(ENGINE_PATH) && engine = Rails::Engine.find(ENGINE_PATH)
             if engine.paths['db/migrate'].existent
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index 6b5d47a..242845b 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -322,11 +322,14 @@ db_namespace = namespace :db do
     # desc "Recreate the test database from an existent schema.rb file"
     task :load_schema => 'db:test:purge' do
       begin
+        should_reconnect = ActiveRecord::Base.connection_pool.active_connection?
         ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations['test'])
         ActiveRecord::Schema.verbose = false
         db_namespace["schema:load"].invoke
       ensure
-        ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[ActiveRecord::Tasks::DatabaseTasks.env])
+        if should_reconnect
+          ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[ActiveRecord::Tasks::DatabaseTasks.env])
+        end
       end
     end
 
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index 60eda96..7dc0260 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -486,7 +486,7 @@ module ActiveRecord
           # Add to it the scope from this reflection (if any)
           scope_chain.first << scope if scope
 
-          through_scope_chain = through_reflection.scope_chain
+          through_scope_chain = through_reflection.scope_chain.map(&:dup)
 
           if options[:source_type]
             through_scope_chain.first <<
diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb
index 8222fce..d7eda35 100644
--- a/activerecord/lib/active_record/relation.rb
+++ b/activerecord/lib/active_record/relation.rb
@@ -17,7 +17,7 @@ module ActiveRecord
     include FinderMethods, Calculations, SpawnMethods, QueryMethods, Batches, Explain, Delegation
 
     attr_reader :table, :klass, :loaded
-    attr_accessor :default_scoped, :proxy_association
+    attr_accessor :default_scoped
     alias :model :klass
     alias :loaded? :loaded
     alias :default_scoped? :default_scoped
diff --git a/activerecord/lib/active_record/relation/batches.rb b/activerecord/lib/active_record/relation/batches.rb
index b921f2e..7d2416d 100644
--- a/activerecord/lib/active_record/relation/batches.rb
+++ b/activerecord/lib/active_record/relation/batches.rb
@@ -58,8 +58,8 @@ module ActiveRecord
 
       relation = self
 
-      unless arel.orders.blank? && arel.taken.blank?
-        ActiveRecord::Base.logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
+      if logger && (arel.orders.present? || arel.taken.present?)
+        logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
       end
 
       start = options.delete(:start)
diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb
index 64e1ff9..69a58d3 100644
--- a/activerecord/lib/active_record/relation/calculations.rb
+++ b/activerecord/lib/active_record/relation/calculations.rb
@@ -376,6 +376,7 @@ module ActiveRecord
       column ? column.type_cast(value) : value
     end
 
+    # TODO: refactor to allow non-string `select_values` (eg. Arel nodes).
     def select_for_count
       if select_values.present?
         select = select_values.join(", ")
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 72e9272..179d9d8 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -130,21 +130,21 @@ module ActiveRecord
       last or raise RecordNotFound
     end
 
-    # Returns truthy if a record exists in the table that matches the +id+ or
-    # conditions given, or falsy otherwise. The argument can take six forms:
+    # Returns +true+ if a record exists in the table that matches the +id+ or
+    # conditions given, or +false+ otherwise. The argument can take six forms:
     #
     # * Integer - Finds the record with this primary key.
     # * String - Finds the record with a primary key corresponding to this
     #   string (such as <tt>'5'</tt>).
     # * Array - Finds the record that matches these +find+-style conditions
-    #   (such as <tt>['color = ?', 'red']</tt>).
+    #   (such as <tt>['name LIKE ?', "%#{query}%"]</tt>).
     # * Hash - Finds the record that matches these +find+-style conditions
-    #   (such as <tt>{color: 'red'}</tt>).
+    #   (such as <tt>{name: 'David'}</tt>).
     # * +false+ - Returns always +false+.
     # * No args - Returns +false+ if the table is empty, +true+ otherwise.
     #
-    # For more information about specifying conditions as a Hash or Array,
-    # see the Conditions section in the introduction to ActiveRecord::Base.
+    # For more information about specifying conditions as a hash or array,
+    # see the Conditions section in the introduction to <tt>ActiveRecord::Base</tt>.
     #
     # Note: You can't pass in a condition as a string (like <tt>name =
     # 'Jamie'</tt>), since it would be sanitized and then queried against
@@ -171,7 +171,7 @@ module ActiveRecord
         relation = relation.where(table[primary_key].eq(conditions)) if conditions != :none
       end
 
-      connection.select_value(relation, "#{name} Exists", relation.bind_values)
+      connection.select_value(relation, "#{name} Exists", relation.bind_values) ? true : false
     rescue ThrowResult
       false
     end
@@ -222,7 +222,7 @@ module ActiveRecord
     end
 
     def construct_relation_for_association_find(join_dependency)
-      relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns)
+      relation = except(:includes, :eager_load, :preload, :select).select(join_dependency.columns + select_values)
       apply_join_dependency(relation, join_dependency)
     end
 
@@ -245,9 +245,9 @@ module ActiveRecord
 
     def construct_limited_ids_condition(relation)
       orders = relation.order_values.map { |val| val.presence }.compact
-      values = @klass.connection.distinct("#{quoted_table_name}.#{primary_key}", orders)
+      values = @klass.connection.columns_for_distinct("#{quoted_table_name}.#{quoted_primary_key}", orders)
 
-      relation = relation.dup.select(values)
+      relation = relation.dup.select(values).distinct!
 
       id_rows = @klass.connection.select_all(relation.arel, 'SQL', relation.bind_values)
       ids_array = id_rows.map {|row| row[primary_key]}
diff --git a/activerecord/lib/active_record/relation/merger.rb b/activerecord/lib/active_record/relation/merger.rb
index 936b832..b6809d3 100644
--- a/activerecord/lib/active_record/relation/merger.rb
+++ b/activerecord/lib/active_record/relation/merger.rb
@@ -62,7 +62,11 @@ module ActiveRecord
       def merge
         normal_values.each do |name|
           value = values[name]
-          relation.send("#{name}!", *value) unless value.blank?
+          # The unless clause is here mostly for performance reasons (since the `send` call might be moderately
+          # expensive), most of the time the value is going to be `nil` or `.blank?`, the only catch is that
+          # `false.blank?` returns `true`, so there needs to be an extra check so that explicit `false` values
+          # don't fall through the cracks.
+          relation.send("#{name}!", *value) unless value.nil? || (value.blank? && false != value)
         end
 
         merge_multi_values
@@ -101,8 +105,15 @@ module ActiveRecord
       end
 
       def merge_multi_values
-        relation.where_values = merged_wheres
-        relation.bind_values  = merged_binds
+        lhs_wheres = relation.where_values
+        rhs_wheres = values[:where] || []
+        lhs_binds  = relation.bind_values
+        rhs_binds  = values[:bind] || []
+
+        removed, kept = partition_overwrites(lhs_wheres, rhs_wheres)
+
+        relation.where_values = kept + rhs_wheres
+        relation.bind_values  = filter_binds(lhs_binds, removed) + rhs_binds
 
         if values[:reordering]
           # override any order specified in the original relation
@@ -125,37 +136,29 @@ module ActiveRecord
         end
       end
 
-      def merged_binds
-        if values[:bind]
-          (relation.bind_values + values[:bind]).uniq(&:first)
-        else
-          relation.bind_values
-        end
+      def filter_binds(lhs_binds, removed_wheres)
+        set = Set.new removed_wheres.map { |x| x.left.name }
+        lhs_binds.dup.delete_if { |col,_| set.include? col.name }
       end
 
-      def merged_wheres
-        values[:where] ||= []
-
-        if values[:where].empty? || relation.where_values.empty?
-          relation.where_values + values[:where]
-        else
-          # Remove equalities from the existing relation with a LHS which is
-          # present in the relation being merged in.
+      # Remove equalities from the existing relation with a LHS which is
+      # present in the relation being merged in.
+      # returns [things_to_remove, things_to_keep]
+      def partition_overwrites(lhs_wheres, rhs_wheres)
+        if lhs_wheres.empty? || rhs_wheres.empty?
+          return [[], lhs_wheres]
+        end
 
-          seen = Set.new
-          values[:where].each { |w|
-            if w.respond_to?(:operator) && w.operator == :==
-              seen << w.left
-            end
-          }
+        nodes = rhs_wheres.find_all do |w|
+          w.respond_to?(:operator) && w.operator == :==
+        end
+        seen = Set.new(nodes) { |node| node.left }
 
-          relation.where_values.reject { |w|
-            w.respond_to?(:operator) &&
-              w.operator == :== &&
-              seen.include?(w.left)
-          } + values[:where]
+        lhs_wheres.partition do |w|
+          w.respond_to?(:operator) && w.operator == :== && seen.include?(w.left)
         end
       end
+
     end
   end
 end
diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb
index 9fcd2d0..089c49f 100644
--- a/activerecord/lib/active_record/relation/query_methods.rb
+++ b/activerecord/lib/active_record/relation/query_methods.rb
@@ -285,11 +285,13 @@ module ActiveRecord
       references!(references) if references.any?
 
       # if a symbol is given we prepend the quoted table name
-      args = args.map { |arg|
-        arg.is_a?(Symbol) ? "#{quoted_table_name}.#{arg} ASC" : arg
+      args = args.map! { |arg|
+        arg.is_a?(Symbol) ?
+          Arel::Nodes::Ascending.new(klass.arel_table[arg]) :
+          arg
       }
 
-      self.order_values = args + self.order_values
+      self.order_values += args
       self
     end
 
@@ -301,7 +303,7 @@ module ActiveRecord
     #
     #   User.order('email DESC').reorder('id ASC').order('name ASC')
     #
-    # generates a query with 'ORDER BY name ASC, id ASC'.
+    # generates a query with 'ORDER BY id ASC, name ASC'.
     def reorder(*args)
       check_if_method_has_arguments!("reorder", args)
       spawn.reorder!(*args)
@@ -799,7 +801,7 @@ module ActiveRecord
     def build_arel
       arel = Arel::SelectManager.new(table.engine, table)
 
-      build_joins(arel, joins_values) unless joins_values.empty?
+      build_joins(arel, joins_values.flatten) unless joins_values.empty?
 
       collapse_wheres(arel, (where_values - ['']).uniq)
 
@@ -875,19 +877,25 @@ module ActiveRecord
     end
 
     def collapse_wheres(arel, wheres)
-      equalities = wheres.grep(Arel::Nodes::Equality)
-
-      arel.where(Arel::Nodes::And.new(equalities)) unless equalities.empty?
-
-      (wheres - equalities).each do |where|
+      predicates = wheres.map do |where|
+        next where if ::Arel::Nodes::Equality === where
         where = Arel.sql(where) if String === where
-        arel.where(Arel::Nodes::Grouping.new(where))
+        Arel::Nodes::Grouping.new(where)
       end
+
+      arel.where(Arel::Nodes::And.new(predicates)) if predicates.present?
     end
 
     def build_where(opts, other = [])
       case opts
       when String, Array
+        #TODO: Remove duplication with: /activerecord/lib/active_record/sanitization.rb:113
+        values = Hash === other.first ? other.first.values : other
+
+        values.grep(ActiveRecord::Relation) do |rel|
+          self.bind_values += rel.bind_values
+        end
+
         [@klass.send(:sanitize_sql, other.empty? ? opts : ([opts] + other))]
       when Hash
         attributes = @klass.send(:expand_hash_conditions_for_aggregates, opts)
@@ -907,6 +915,7 @@ module ActiveRecord
       case opts
       when Relation
         name ||= 'subquery'
+        self.bind_values = opts.bind_values + self.bind_values
         opts.arel.as(name.to_s)
       else
         opts
diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb
index bea195e..957f122 100644
--- a/activerecord/lib/active_record/result.rb
+++ b/activerecord/lib/active_record/result.rb
@@ -59,7 +59,21 @@ module ActiveRecord
           # used as keys in ActiveRecord::Base's @attributes hash
           columns = @columns.map { |c| c.dup.freeze }
           @rows.map { |row|
-            Hash[columns.zip(row)]
+            # In the past we used Hash[columns.zip(row)]
+            #  though elegant, the verbose way is much more efficient
+            #  both time and memory wise cause it avoids a big array allocation
+            #  this method is called a lot and needs to be micro optimised
+            hash = {}
+
+            index = 0
+            length = columns.length
+
+            while index < length
+              hash[columns[index]] = row[index]
+              index += 1
+            end
+
+            hash
           }
         end
     end
diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb
index 3c5b871..53908bc 100644
--- a/activerecord/lib/active_record/sanitization.rb
+++ b/activerecord/lib/active_record/sanitization.rb
@@ -89,7 +89,7 @@ module ActiveRecord
         attrs = expand_hash_conditions_for_aggregates(attrs)
 
         table = Arel::Table.new(table_name, arel_engine).alias(default_table_name)
-        PredicateBuilder.build_from_hash(self.class, attrs, table).map { |b|
+        PredicateBuilder.build_from_hash(self, attrs, table).map { |b|
           connection.visitor.accept b
         }.join(' AND ')
       end
@@ -126,7 +126,17 @@ module ActiveRecord
         raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size)
         bound = values.dup
         c = connection
-        statement.gsub('?') { quote_bound_value(bound.shift, c) }
+        statement.gsub('?') do
+          replace_bind_variable(bound.shift, c)
+        end
+      end
+
+      def replace_bind_variable(value, c = connection) #:nodoc:
+        if ActiveRecord::Relation === value
+          value.to_sql
+        else
+          quote_bound_value(value, c)
+        end
       end
 
       def replace_named_bind_variables(statement, bind_vars) #:nodoc:
@@ -134,7 +144,7 @@ module ActiveRecord
           if $1 == ':' # skip postgresql casts
             $& # return the whole match
           elsif bind_vars.include?(match = $2.to_sym)
-            quote_bound_value(bind_vars[match])
+            replace_bind_variable(bind_vars[match])
           else
             raise PreparedStatementInvalid, "missing value for :#{match} in #{statement}"
           end
diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb
index 10c6d27..d38b241 100644
--- a/activerecord/lib/active_record/schema_dumper.rb
+++ b/activerecord/lib/active_record/schema_dumper.rb
@@ -106,9 +106,13 @@ HEADER
           end
 
           tbl.print "  create_table #{remove_prefix_and_suffix(table).inspect}"
-          if columns.detect { |c| c.name == pk }
+          pkcol = columns.detect { |c| c.name == pk }
+          if pkcol
             if pk != 'id'
               tbl.print %Q(, primary_key: "#{pk}")
+            elsif pkcol.sql_type == 'uuid'
+              tbl.print ", id: :uuid"
+              tbl.print %Q(, default: "#{pkcol.default_function}") if pkcol.default_function
             end
           else
             tbl.print ", id: false"
diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb
index 8d0792f..71ae90b 100644
--- a/activerecord/lib/active_record/tasks/database_tasks.rb
+++ b/activerecord/lib/active_record/tasks/database_tasks.rb
@@ -23,6 +23,7 @@ module ActiveRecord
     #   * +fixtures_path+: a path to fixtures directory.
     #   * +migrations_paths+: a list of paths to directories with migrations.
     #   * +seed_loader+: an object which will load seeds, it needs to respond to the +load_seed+ method.
+    #   * +root+: a path to the root of the application.
     #
     # Example usage of +DatabaseTasks+ outside Rails could look as such:
     #
@@ -37,7 +38,7 @@ module ActiveRecord
 
       attr_writer :current_config
       attr_accessor :database_configuration, :migrations_paths, :seed_loader, :db_dir,
-                    :fixtures_path, :env
+                    :fixtures_path, :env, :root
 
       LOCAL_HOSTS    = ['127.0.0.1', 'localhost']
 
diff --git a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb
index de8b166..5688931 100644
--- a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb
+++ b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb
@@ -3,7 +3,7 @@ module ActiveRecord
     class SQLiteDatabaseTasks # :nodoc:
       delegate :connection, :establish_connection, to: ActiveRecord::Base
 
-      def initialize(configuration, root = Rails.root)
+      def initialize(configuration, root = ActiveRecord::Tasks::DatabaseTasks.root)
         @configuration, @root = configuration, root
       end
 
diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb
index a5955cc..b060dc0 100644
--- a/activerecord/lib/active_record/transactions.rb
+++ b/activerecord/lib/active_record/transactions.rb
@@ -243,7 +243,7 @@ module ActiveRecord
         if options.is_a?(Hash) && options[:on]
           assert_valid_transaction_action(options[:on])
           options[:if] = Array(options[:if])
-          fire_on = Array(options[:on]).map(&:to_sym)
+          fire_on = Array(options[:on])
           options[:if] << "transaction_include_any_action?(#{fire_on})"
         end
       end
@@ -286,17 +286,17 @@ module ActiveRecord
       clear_transaction_record_state
     end
 
-    # Call the after_commit callbacks
+    # Call the +after_commit+ callbacks.
     #
     # Ensure that it is not called if the object was never persisted (failed create),
-    # but call it after the commit of a destroyed object
+    # but call it after the commit of a destroyed object.
     def committed! #:nodoc:
       run_callbacks :commit if destroyed? || persisted?
     ensure
       clear_transaction_record_state
     end
 
-    # Call the after rollback callbacks. The restore_state argument indicates if the record
+    # Call the +after_rollback+ callbacks. The +force_restore_state+ argument indicates if the record
     # state should be rolled back to the beginning or just to the last savepoint.
     def rolledback!(force_restore_state = false) #:nodoc:
       run_callbacks :rollback
@@ -304,7 +304,7 @@ module ActiveRecord
       restore_transaction_record_state(force_restore_state)
     end
 
-    # Add the record to the current transaction so that the :after_rollback and :after_commit callbacks
+    # Add the record to the current transaction so that the +after_rollback+ and +after_commit+ callbacks
     # can be called.
     def add_to_transaction
       if self.class.connection.add_transaction_record(self)
diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb
index a705d8c..6635156 100644
--- a/activerecord/lib/active_record/validations/uniqueness.rb
+++ b/activerecord/lib/active_record/validations/uniqueness.rb
@@ -202,8 +202,8 @@ module ActiveRecord
       # will result in the default Rails exception page being shown), or you
       # can catch it and restart the transaction (e.g. by telling the user
       # that the title already exists, and asking him to re-enter the title).
-      # This technique is also known as optimistic concurrency control:
-      # http://en.wikipedia.org/wiki/Optimistic_concurrency_control.
+      # This technique is also known as
+      # {optimistic concurrency control}[http://en.wikipedia.org/wiki/Optimistic_concurrency_control].
       #
       # The bundled ActiveRecord::ConnectionAdapters distinguish unique index
       # constraint errors from other types of database errors by throwing an
diff --git a/activerecord/lib/active_record/version.rb b/activerecord/lib/active_record/version.rb
index bb97bfc..e415913 100644
--- a/activerecord/lib/active_record/version.rb
+++ b/activerecord/lib/active_record/version.rb
@@ -1,7 +1,7 @@
 module ActiveRecord
   # Returns the version of the currently loaded ActiveRecord as a Gem::Version
   def self.version
-    Gem::Version.new "4.0.0"
+    Gem::Version.new "4.0.2"
   end
 
   module VERSION #:nodoc:
diff --git a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
index a75883c..9ad0744 100644
--- a/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
+++ b/activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb
@@ -95,14 +95,39 @@ module ActiveRecord
         assert_equal @conn.default_sequence_name('ex_with_custom_index_type_pk', 'id'), seq
       end
 
+      def test_tinyint_integer_typecasting
+        @conn.exec_query('drop table if exists ex_with_non_boolean_tinyint_column')
+        @conn.exec_query(<<-eosql)
+          CREATE TABLE `ex_with_non_boolean_tinyint_column` (
+            `status` TINYINT(4))
+        eosql
+        insert(@conn, { 'status' => 2 }, 'ex_with_non_boolean_tinyint_column')
+
+        result = @conn.exec_query('SELECT status FROM ex_with_non_boolean_tinyint_column')
+
+        assert_equal 2, result.column_types['status'].type_cast(result.last['status'])
+      end
+
+      def test_supports_extensions
+        assert_not @conn.supports_extensions?, 'does not support extensions'
+      end
+
+      def test_respond_to_enable_extension
+        assert @conn.respond_to?(:enable_extension)
+      end
+
+      def test_respond_to_disable_extension
+        assert @conn.respond_to?(:disable_extension)
+      end
+
       private
-      def insert(ctx, data)
+      def insert(ctx, data, table='ex')
         binds   = data.map { |name, value|
-          [ctx.columns('ex').find { |x| x.name == name }, value]
+          [ctx.columns(table).find { |x| x.name == name }, value]
         }
         columns = binds.map(&:first).map(&:name)
 
-        sql = "INSERT INTO ex (#{columns.join(", ")})
+        sql = "INSERT INTO #{table} (#{columns.join(", ")})
                VALUES (#{(['?'] * columns.length).join(', ')})"
 
         ctx.exec_insert(sql, 'SQL', binds)
diff --git a/activerecord/test/cases/adapters/postgresql/array_test.rb b/activerecord/test/cases/adapters/postgresql/array_test.rb
index 61a3a2b..e5e877f 100644
--- a/activerecord/test/cases/adapters/postgresql/array_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/array_test.rb
@@ -27,6 +27,18 @@ class PostgresqlArrayTest < ActiveRecord::TestCase
     assert @column.array
   end
 
+  def test_change_column_with_array
+    @connection.add_column :pg_arrays, :snippets, :string, array: true, default: []
+    @connection.change_column :pg_arrays, :snippets, :text, array: true, default: "{}"
+
+    PgArray.reset_column_information
+    column = PgArray.columns.find { |c| c.name == 'snippets' }
+
+    assert_equal :text, column.type
+    assert_equal [], column.default
+    assert column.array
+  end
+
   def test_type_cast_array
     assert @column
 
diff --git a/activerecord/test/cases/adapters/postgresql/datatype_test.rb b/activerecord/test/cases/adapters/postgresql/datatype_test.rb
index b5d7ea6..1b2f5f0 100644
--- a/activerecord/test/cases/adapters/postgresql/datatype_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/datatype_test.rb
@@ -298,6 +298,14 @@ _SQL
     assert_equal(-567.89, @second_money.wealth)
   end
 
+  def test_money_type_cast
+    column = PostgresqlMoney.columns.find { |c| c.name == 'wealth' }
+    assert_equal(12345678.12, column.type_cast("$12,345,678.12"))
+    assert_equal(12345678.12, column.type_cast("$12.345.678,12"))
+    assert_equal(-1.15, column.type_cast("-$1.15"))
+    assert_equal(-2.25, column.type_cast("($2.25)"))
+  end
+
   def test_create_tstzrange
     skip "PostgreSQL 9.2 required for range datatypes" unless @connection.supports_ranges?
     tstzrange = Time.parse('2010-01-01 14:30:00 +0100')...Time.parse('2011-02-02 14:30:00 CDT')
@@ -594,7 +602,7 @@ _SQL
     @connection.reconnect!
 
     @first_timestamp_with_zone = PostgresqlTimestampWithZone.find(1)
-    assert_equal Time.utc(2010,1,1, 11,0,0), @first_timestamp_with_zone.time
+    assert_equal Time.local(2010,1,1, 11,0,0), @first_timestamp_with_zone.time
     assert_instance_of Time, @first_timestamp_with_zone.time
   ensure
     ActiveRecord::Base.default_timezone = old_default_tz
diff --git a/activerecord/test/cases/adapters/postgresql/json_test.rb b/activerecord/test/cases/adapters/postgresql/json_test.rb
index 6fc08ae..adac1d3 100644
--- a/activerecord/test/cases/adapters/postgresql/json_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/json_test.rb
@@ -83,4 +83,17 @@ class PostgresqlJSONTest < ActiveRecord::TestCase
     x = JsonDataType.first
     assert_equal(nil, x.payload)
   end
+
+  def test_select_array_json_value
+    @connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
+    x = JsonDataType.first
+    assert_equal(['v0', {'k1' => 'v1'}], x.payload)
+  end
+
+  def test_rewrite_array_json_value
+    @connection.execute %q|insert into json_data_type (payload) VALUES ('["v0",{"k1":"v1"}]')|
+    x = JsonDataType.first
+    x.payload = ['v1', {'k2' => 'v2'}, 'v3']
+    assert x.save!
+  end
 end
diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
index 17d77c5..fb88ab7 100644
--- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
@@ -226,23 +226,51 @@ module ActiveRecord
       end
 
       def test_distinct_zero_orders
-        assert_equal "DISTINCT posts.id",
-          @connection.distinct("posts.id", [])
+        assert_deprecated do
+          assert_equal "DISTINCT posts.id",
+            @connection.distinct("posts.id", [])
+        end
+      end
+
+      def test_columns_for_distinct_zero_orders
+        assert_equal "posts.id",
+          @connection.columns_for_distinct("posts.id", [])
       end
 
       def test_distinct_one_order
-        assert_equal "DISTINCT posts.id, posts.created_at AS alias_0",
-          @connection.distinct("posts.id", ["posts.created_at desc"])
+        assert_deprecated do
+          assert_equal "DISTINCT posts.id, posts.created_at AS alias_0",
+            @connection.distinct("posts.id", ["posts.created_at desc"])
+        end
+      end
+
+      def test_columns_for_distinct_one_order
+        assert_equal "posts.id, posts.created_at AS alias_0",
+          @connection.columns_for_distinct("posts.id", ["posts.created_at desc"])
       end
 
       def test_distinct_few_orders
-        assert_equal "DISTINCT posts.id, posts.created_at AS alias_0, posts.position AS alias_1",
-          @connection.distinct("posts.id", ["posts.created_at desc", "posts.position asc"])
+        assert_deprecated do
+          assert_equal "DISTINCT posts.id, posts.created_at AS alias_0, posts.position AS alias_1",
+            @connection.distinct("posts.id", ["posts.created_at desc", "posts.position asc"])
+        end
+      end
+
+      def test_columns_for_distinct_few_orders
+        assert_equal "posts.id, posts.created_at AS alias_0, posts.position AS alias_1",
+          @connection.columns_for_distinct("posts.id", ["posts.created_at desc", "posts.position asc"])
       end
 
       def test_distinct_blank_not_nil_orders
-        assert_equal "DISTINCT posts.id, posts.created_at AS alias_0",
-          @connection.distinct("posts.id", ["posts.created_at desc", "", "   "])
+        assert_deprecated do
+          assert_equal "DISTINCT posts.id, posts.created_at AS alias_0",
+            @connection.distinct("posts.id", ["posts.created_at desc", "", "   "])
+        end
+      end
+
+      def test_columns_for_distinct_blank_not_nil_orders
+        assert_equal "posts.id, posts.created_at AS alias_0",
+          @connection.columns_for_distinct("posts.id", ["posts.created_at desc", "", "   "])
       end
 
       def test_distinct_with_arel_order
@@ -250,13 +278,31 @@ module ActiveRecord
         def order.to_sql
           "posts.created_at desc"
         end
-        assert_equal "DISTINCT posts.id, posts.created_at AS alias_0",
-          @connection.distinct("posts.id", [order])
+        assert_deprecated do
+          assert_equal "DISTINCT posts.id, posts.created_at AS alias_0",
+            @connection.distinct("posts.id", [order])
+        end
+      end
+
+      def test_columns_for_distinct_with_arel_order
+        order = Object.new
+        def order.to_sql
+          "posts.created_at desc"
+        end
+        assert_equal "posts.id, posts.created_at AS alias_0",
+          @connection.columns_for_distinct("posts.id", [order])
       end
 
       def test_distinct_with_nulls
-        assert_equal "DISTINCT posts.title, posts.updater_id AS alias_0", @connection.distinct("posts.title", ["posts.updater_id desc nulls first"])
-        assert_equal "DISTINCT posts.title, posts.updater_id AS alias_0", @connection.distinct("posts.title", ["posts.updater_id desc nulls last"])
+        assert_deprecated do
+          assert_equal "DISTINCT posts.title, posts.updater_id AS alias_0", @connection.distinct("posts.title", ["posts.updater_id desc nulls first"])
+          assert_equal "DISTINCT posts.title, posts.updater_id AS alias_0", @connection.distinct("posts.title", ["posts.updater_id desc nulls last"])
+        end
+      end
+
+      def test_columns_for_distinct_with_nulls
+        assert_equal "posts.title, posts.updater_id AS alias_0", @connection.columns_for_distinct("posts.title", ["posts.updater_id desc nulls first"])
+        assert_equal "posts.title, posts.updater_id AS alias_0", @connection.columns_for_distinct("posts.title", ["posts.updater_id desc nulls last"])
       end
 
       def test_raise_error_when_cannot_translate_exception
diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb
index 57cea20..84e0cfa 100644
--- a/activerecord/test/cases/adapters/postgresql/uuid_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb
@@ -24,7 +24,7 @@ class PostgresqlUUIDTest < ActiveRecord::TestCase
     @connection.reconnect!
 
     @connection.transaction do
-      @connection.create_table('pg_uuids', id: :uuid) do |t|
+      @connection.create_table('pg_uuids', id: :uuid, default: 'uuid_generate_v1()') do |t|
         t.string 'name'
         t.uuid 'other_uuid', default: 'uuid_generate_v4()'
       end
@@ -50,6 +50,19 @@ class PostgresqlUUIDTest < ActiveRecord::TestCase
     u.reload
     assert_not_nil u.other_uuid
   end
+
+  def test_pk_and_sequence_for_uuid_primary_key
+    pk, seq = @connection.pk_and_sequence_for('pg_uuids')
+    assert_equal 'id', pk
+    assert_equal nil, seq
+  end
+
+  def test_schema_dumper_for_uuid_primary_key
+    schema = StringIO.new
+    ActiveRecord::SchemaDumper.dump(@connection, schema)
+    assert_match(/\bcreate_table "pg_uuids", id: :uuid, default: "uuid_generate_v1\(\)"/, schema.string)
+    assert_match(/t\.uuid   "other_uuid", default: "uuid_generate_v4\(\)"/, schema.string)
+  end
 end
 
 class PostgresqlUUIDTestNilDefault < ActiveRecord::TestCase
@@ -83,33 +96,42 @@ class PostgresqlUUIDTestNilDefault < ActiveRecord::TestCase
   end
 end
 
-class PostgresqlUUIDTestNilDefault < ActiveRecord::TestCase
-  class UUID < ActiveRecord::Base
-    self.table_name = 'pg_uuids'
+class PostgresqlUUIDTestInverseOf < ActiveRecord::TestCase
+  class UuidPost < ActiveRecord::Base
+    self.table_name = 'pg_uuid_posts'
+    has_many :uuid_comments, inverse_of: :uuid_post
+  end
+
+  class UuidComment < ActiveRecord::Base
+    self.table_name = 'pg_uuid_comments'
+    belongs_to :uuid_post
   end
 
   def setup
     @connection = ActiveRecord::Base.connection
-
     @connection.reconnect!
 
     @connection.transaction do
-      @connection.create_table('pg_uuids', id: false) do |t|
-        t.primary_key :id, :uuid, default: nil
-        t.string 'name'
+      @connection.create_table('pg_uuid_posts', id: :uuid) do |t|
+        t.string 'title'
+      end
+      @connection.create_table('pg_uuid_comments', id: :uuid) do |t|
+        t.uuid :uuid_post_id, default: 'uuid_generate_v4()'
+        t.string 'content'
       end
     end
   end
 
   def teardown
-    @connection.execute 'drop table if exists pg_uuids'
+    @connection.transaction do
+      @connection.execute 'drop table if exists pg_uuid_comments'
+      @connection.execute 'drop table if exists pg_uuid_posts'
+    end
   end
 
-  def test_id_allows_default_override_via_nil
-    col_desc = @connection.execute("SELECT pg_get_expr(d.adbin, d.adrelid) as default
-                                    FROM pg_attribute a
-                                    LEFT JOIN pg_attrdef d ON a.attrelid = d.adrelid AND a.attnum = d.adnum
-                                    WHERE a.attname='id' AND a.attrelid = 'pg_uuids'::regclass").first
-    assert_nil col_desc["default"]
+  def test_collection_association_with_uuid
+    post    = UuidPost.create!
+    comment = post.uuid_comments.create!
+    assert post.uuid_comments.find(comment.id)
   end
 end
diff --git a/activerecord/test/cases/adapters/postgresql/xml_test.rb b/activerecord/test/cases/adapters/postgresql/xml_test.rb
new file mode 100644
index 0000000..bf14b37
--- /dev/null
+++ b/activerecord/test/cases/adapters/postgresql/xml_test.rb
@@ -0,0 +1,38 @@
+# encoding: utf-8
+
+require 'cases/helper'
+require 'active_record/base'
+require 'active_record/connection_adapters/postgresql_adapter'
+
+class PostgresqlXMLTest < ActiveRecord::TestCase
+  class XmlDataType < ActiveRecord::Base
+    self.table_name = 'xml_data_type'
+  end
+
+  def setup
+    @connection = ActiveRecord::Base.connection
+    begin
+      @connection.transaction do
+        @connection.create_table('xml_data_type') do |t|
+          t.xml 'payload', default: {}
+        end
+      end
+    rescue ActiveRecord::StatementInvalid
+      return skip "do not test on PG without xml"
+    end
+    @column = XmlDataType.columns.find { |c| c.name == 'payload' }
+  end
+
+  def teardown
+    @connection.execute 'drop table if exists xml_data_type'
+  end
+
+  def test_column
+    assert_equal :xml, @column.type
+  end
+
+  def test_null_xml
+    @connection.execute %q|insert into xml_data_type (payload) VALUES(null)|
+    assert_nil XmlDataType.first.payload
+  end
+end
diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
index d51d425..52fb73c 100644
--- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
+++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
@@ -354,6 +354,18 @@ module ActiveRecord
         assert_nil @conn.primary_key('failboat')
       end
 
+      def test_supports_extensions
+        assert_not @conn.supports_extensions?, 'does not support extensions'
+      end
+
+      def test_respond_to_enable_extension
+        assert @conn.respond_to?(:enable_extension)
+      end
+
+      def test_respond_to_disable_extension
+        assert @conn.respond_to?(:disable_extension)
+      end
+
       private
 
       def assert_logged logs
diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb
new file mode 100644
index 0000000..5a4fe63
--- /dev/null
+++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_create_folder_test.rb
@@ -0,0 +1,21 @@
+# encoding: utf-8
+require "cases/helper"
+require 'models/owner'
+
+module ActiveRecord
+  module ConnectionAdapters
+    class SQLite3CreateFolder < ActiveRecord::TestCase
+      def test_sqlite_creates_directory
+        Dir.mktmpdir do |dir|
+          dir = Pathname.new(dir)
+          @conn = Base.sqlite3_connection :database => dir.join("db/foo.sqlite3"),
+                               :adapter => 'sqlite3',
+                               :timeout => 100
+
+          assert Dir.exists? dir.join('db')
+          assert File.exist? dir.join('db/foo.sqlite3')
+        end
+      end
+    end
+  end
+end
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index f531695..01d2268 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -1,4 +1,4 @@
-require "cases/helper"
+require 'cases/helper'
 require 'models/developer'
 require 'models/project'
 require 'models/company'
@@ -14,6 +14,8 @@ require 'models/sponsor'
 require 'models/member'
 require 'models/essay'
 require 'models/toy'
+require 'models/invoice'
+require 'models/line_item'
 
 class BelongsToAssociationsTest < ActiveRecord::TestCase
   fixtures :accounts, :companies, :developers, :projects, :topics,
@@ -324,6 +326,45 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
     assert_equal 1, Topic.find(topic.id)[:replies_count]
   end
 
+  def test_belongs_to_with_touch_option_on_touch
+    line_item = LineItem.create!
+    Invoice.create!(line_items: [line_item])
+
+    assert_queries(1) { line_item.touch }
+  end
+
+  def test_belongs_to_with_touch_option_on_touch_and_removed_parent
+    line_item = LineItem.create!
+    Invoice.create!(line_items: [line_item])
+
+    line_item.invoice = nil
+
+    assert_queries(2) { line_item.touch }
+  end
+
+  def test_belongs_to_with_touch_option_on_update
+    line_item = LineItem.create!
+    Invoice.create!(line_items: [line_item])
+
+    assert_queries(2) { line_item.update amount: 10 }
+  end
+
+  def test_belongs_to_with_touch_option_on_destroy
+    line_item = LineItem.create!
+    Invoice.create!(line_items: [line_item])
+
+    assert_queries(2) { line_item.destroy }
+  end
+
+  def test_belongs_to_with_touch_option_on_touch_and_reassigned_parent
+    line_item = LineItem.create!
+    Invoice.create!(line_items: [line_item])
+
+    line_item.invoice = Invoice.create!
+
+    assert_queries(3) { line_item.touch }
+  end
+
   def test_belongs_to_counter_after_update
     topic = Topic.create!(title: "37s")
     topic.replies.create!(title: "re: 37s", content: "rails")
@@ -414,6 +455,26 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
     assert_equal 15, topic.replies.size
   end
 
+  def test_counter_cache_double_destroy
+    topic = Topic.create :title => "Zoom-zoom-zoom"
+
+    5.times do
+      topic.replies.create(:title => "re: zoom", :content => "speedy quick!")
+    end
+
+    assert_equal 5, topic.reload[:replies_count]
+    assert_equal 5, topic.replies.size
+
+    reply = topic.replies.first
+
+    reply.destroy
+    assert_equal 4, topic.reload[:replies_count]
+
+    reply.destroy
+    assert_equal 4, topic.reload[:replies_count]
+    assert_equal 4, topic.replies.size
+  end
+
   def test_custom_counter_cache
     reply = Reply.create(:title => "re: zoom", :content => "speedy quick!")
     assert_equal 0, reply[:replies_count]
diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
index 84bdca3..ed172b0 100644
--- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb
@@ -570,9 +570,9 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase
     assert_equal high_id_jamis, projects(:active_record).developers.find_by_name('Jamis')
   end
 
-  def test_find_should_prepend_to_association_order
+  def test_find_should_append_to_association_order
     ordered_developers = projects(:active_record).developers.order('projects.id')
-    assert_equal ['projects.id', 'developers.name desc, developers.id desc'], ordered_developers.order_values
+    assert_equal ['developers.name desc, developers.id desc', 'projects.id'], ordered_developers.order_values
   end
 
   def test_dynamic_find_all_should_respect_readonly_access
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index d855702..6f86434 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -135,6 +135,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
     assert_equal 'exotic', bulb.name
   end
 
+  def test_build_from_association_should_respect_scope
+    author = Author.new
+
+    post = author.thinking_posts.build
+    assert_equal 'So I was thinking', post.title
+  end
+
   def test_create_from_association_with_nil_values_should_work
     car = Car.create(:name => 'honda')
 
@@ -308,9 +315,9 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
     assert_equal 2, companies(:first_firm).limited_clients.limit(nil).to_a.size
   end
 
-  def test_find_should_prepend_to_association_order
+  def test_find_should_append_to_association_order
     ordered_clients =  companies(:first_firm).clients_sorted_desc.order('companies.id')
-    assert_equal ['companies.id', 'id DESC'], ordered_clients.order_values
+    assert_equal ['id DESC', 'companies.id'], ordered_clients.order_values
   end
 
   def test_dynamic_find_should_respect_association_order
@@ -418,7 +425,19 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
     client_ary = firm.clients_using_finder_sql.find("2", "3")
     assert_kind_of Array, client_ary
     assert_equal 2, client_ary.size
-    assert client_ary.include?(client)
+    assert_equal true, client_ary.include?(client)
+  end
+
+  def test_find_ids_and_inverse_of
+    force_signal37_to_load_all_clients_of_firm
+
+    firm = companies(:first_firm)
+    client = firm.clients_of_firm.find(3)
+    assert_kind_of Client, client
+
+    client_ary = firm.clients_of_firm.find([3])
+    assert_kind_of Array, client_ary
+    assert_equal client, client_ary.first
   end
 
   def test_find_all
@@ -602,6 +621,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
     end
   end
 
+  def test_inverse_on_before_validate
+    firm = companies(:first_firm)
+    assert_queries(1) do
+      firm.clients_of_firm << Client.new("name" => "Natural Company")
+    end
+  end
+
   def test_new_aliased_to_build
     company = companies(:first_firm)
     new_client = assert_no_queries { company.clients_of_firm.new("name" => "Another Client") }
@@ -1220,14 +1246,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
   end
 
   def test_included_in_collection
-    assert companies(:first_firm).clients.include?(Client.find(2))
+    assert_equal true, companies(:first_firm).clients.include?(Client.find(2))
   end
 
   def test_included_in_collection_for_new_records
     client = Client.create(:name => 'Persisted')
     assert_nil client.client_of
-    assert !Firm.new.clients_of_firm.include?(client),
-           'includes a client that does not belong to any firm'
+    assert_equal false, Firm.new.clients_of_firm.include?(client),
+     'includes a client that does not belong to any firm'
   end
 
   def test_adding_array_and_collection
@@ -1254,7 +1280,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
     firm.save
     firm.reload
     assert_equal 2, firm.clients.length
-    assert !firm.clients.include?(:first_client)
+    assert_equal false, firm.clients.include?(:first_client)
   end
 
   def test_replace_failure
@@ -1332,7 +1358,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
     firm.save!
 
     assert_equal 2, firm.clients(true).size
-    assert firm.clients.include?(companies(:second_client))
+    assert_equal true, firm.clients.include?(companies(:second_client))
   end
 
   def test_get_ids_for_through
@@ -1366,7 +1392,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
 
     assert_no_queries do
       assert firm.clients.loaded?
-      assert firm.clients.include?(client)
+      assert_equal true, firm.clients.include?(client)
     end
   end
 
@@ -1377,7 +1403,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
     firm.reload
     assert ! firm.clients.loaded?
     assert_queries(1) do
-      assert firm.clients.include?(client)
+      assert_equal true, firm.clients.include?(client)
     end
     assert ! firm.clients.loaded?
   end
@@ -1388,7 +1414,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
 
     firm.reload
     assert ! firm.clients_using_sql.loaded?
-    assert firm.clients_using_sql.include?(client)
+    assert_equal true, firm.clients_using_sql.include?(client)
     assert firm.clients_using_sql.loaded?
   end
 
@@ -1398,7 +1424,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
     client = Client.create!(:name => 'Not Associated')
 
     assert ! firm.clients.loaded?
-    assert ! firm.clients.include?(client)
+    assert_equal false, firm.clients.include?(client)
   end
 
   def test_calling_first_or_last_on_association_should_not_load_association
@@ -1472,6 +1498,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
     assert_equal david.essays, Essay.where(writer_id: "David")
   end
 
+  def test_has_many_assignment_with_custom_primary_key
+    david = people(:david)
+
+    assert_equal ["A Modest Proposal"], david.essays.map(&:name)
+    david.essays = [Essay.create!(name: "Remote Work" )]
+    assert_equal ["Remote Work"], david.essays.map(&:name)
+  end
+
   def test_blank_custom_primary_key_on_new_record_should_not_run_queries
     author = Author.new
     assert !author.essays.loaded?
@@ -1605,7 +1639,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
   def test_include_method_in_has_many_association_should_return_true_for_instance_added_with_build
     post = Post.new
     comment = post.comments.build
-    assert post.comments.include?(comment)
+    assert_equal true, post.comments.include?(comment)
   end
 
   def test_load_target_respects_protected_attributes
@@ -1675,6 +1709,22 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
     assert_equal car.id, bulb.attributes_after_initialize['car_id']
   end
 
+  def test_attributes_are_set_when_initialized_from_has_many_null_relationship
+    car  = Car.new name: 'honda'
+    bulb = car.bulbs.where(name: 'headlight').first_or_initialize
+    assert_equal 'headlight', bulb.name
+  end
+
+  def test_attributes_are_set_when_initialized_from_polymorphic_has_many_null_relationship
+    post    = Post.new title: 'title', body: 'bar'
+    tag     = Tag.create!(name: 'foo')
+
+    tagging = post.taggings.where(tag: tag).first_or_initialize
+
+    assert_equal tag.id, tagging.tag_id
+    assert_equal 'Post', tagging.taggable_type
+  end
+
   def test_replace
     car = Car.create(:name => 'honda')
     bulb1 = car.bulbs.create
diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb
index 70c6b48..5a033d0 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -5,6 +5,7 @@ require 'models/reference'
 require 'models/job'
 require 'models/reader'
 require 'models/comment'
+require 'models/rating'
 require 'models/tag'
 require 'models/tagging'
 require 'models/author'
@@ -582,6 +583,11 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
     assert_equal post.author.author_favorites, post.author_favorites
   end
 
+  def test_merge_join_association_with_has_many_through_association_proxy
+    author = authors(:mary)
+    assert_nothing_raised { author.comments.ratings.to_sql }
+  end
+
   def test_has_many_association_through_a_has_many_association_with_nonstandard_primary_keys
     assert_equal 2, owners(:blackbeard).toys.count
   end
diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb
index 0e48fbc..312dbb3 100644
--- a/activerecord/test/cases/associations/has_one_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_associations_test.rb
@@ -521,6 +521,8 @@ class HasOneAssociationsTest < ActiveRecord::TestCase
     assert_no_queries { company.account = nil }
     account = Account.find(2)
     assert_queries { company.account = account }
+
+    assert_no_queries { Firm.new.account = account }
   end
 
   def test_has_one_assignment_triggers_save_on_change
diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb
index 918783e..dccd54d 100644
--- a/activerecord/test/cases/associations/inner_join_association_test.rb
+++ b/activerecord/test/cases/associations/inner_join_association_test.rb
@@ -41,6 +41,11 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
     assert_no_match(/WHERE/i, sql)
   end
 
+  def test_join_association_conditions_support_string_and_arel_expressions
+    assert_equal 0, Author.joins(:welcome_posts_with_comment).count
+    assert_equal 1, Author.joins(:welcome_posts_with_comments).count
+  end
+
   def test_join_conditions_allow_nil_associations
     authors = Author.includes(:essays).where(:essays => {:id => nil})
     assert_equal 2, authors.count
@@ -104,4 +109,12 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase
     assert !posts(:welcome).tags.empty?
     assert Post.joins(:misc_tags).where(:id => posts(:welcome).id).empty?
   end
+
+  test "the default scope of the target is applied when joining associations" do
+    author = Author.create! name: "Jon"
+    author.categorizations.create!
+    author.categorizations.create! special: true
+
+    assert_equal [author], Author.where(id: author).joins(:special_categorizations)
+  end
 end
diff --git a/activerecord/test/cases/associations/inverse_associations_test.rb b/activerecord/test/cases/associations/inverse_associations_test.rb
index ec128ac..c292dd7 100644
--- a/activerecord/test/cases/associations/inverse_associations_test.rb
+++ b/activerecord/test/cases/associations/inverse_associations_test.rb
@@ -319,10 +319,22 @@ class InverseHasManyTests < ActiveRecord::TestCase
     assert_equal man.name, man.interests.find(interest.id).man.name, "The name of the man should match after the child name is changed"
   end
 
+  def test_find_on_child_instance_with_id_should_not_load_all_child_records
+    man = Man.create!
+    interest = Interest.create!(man: man)
+
+    man.interests.find(interest.id)
+    refute man.interests.loaded?
+  end
+
   def test_raise_record_not_found_error_when_invalid_ids_are_passed
+    # delete all interest records to ensure that hard coded invalid_id(s)
+    # are indeed invalid.
+    Interest.delete_all
+
     man = Man.create!
 
-    invalid_id = 2394823094892348920348523452345
+    invalid_id = 245324523
     assert_raise(ActiveRecord::RecordNotFound) { man.interests.find(invalid_id) }
 
     invalid_ids = [8432342, 2390102913, 2453245234523452]
@@ -338,6 +350,19 @@ class InverseHasManyTests < ActiveRecord::TestCase
   def test_trying_to_use_inverses_that_dont_exist_should_raise_an_error
     assert_raise(ActiveRecord::InverseOfAssociationNotFoundError) { Man.first.secret_interests }
   end
+
+  def test_child_instance_should_point_to_parent_without_saving
+    man = Man.new
+    i = Interest.create(:topic => 'Industrial Revolution Re-enactment')
+
+    man.interests << i
+    assert_not_nil i.man
+
+    i.man.name = "Charles"
+    assert_equal i.man.name, man.name
+
+    assert !man.persisted?
+  end
 end
 
 class InverseBelongsToTests < ActiveRecord::TestCase
@@ -482,6 +507,18 @@ class InversePolymorphicBelongsToTests < ActiveRecord::TestCase
     assert_equal face.description, new_man.polymorphic_face.description, "Description of face should be the same after changes to replaced-parent-owned instance"
   end
 
+  def test_inversed_instance_should_not_be_reloaded_after_stale_state_changed
+    new_man = Man.new
+    face = Face.new
+    new_man.face = face
+
+    old_inversed_man = face.man
+    new_man.save!
+    new_inversed_man = face.man
+
+    assert_equal old_inversed_man.object_id, new_inversed_man.object_id
+  end
+
   def test_should_not_try_to_set_inverse_instances_when_the_inverse_is_a_has_many
     i = interests(:llama_wrangling)
     m = i.polymorphic_man
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
index 95c571f..0f2d22a 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -18,6 +18,8 @@ require 'models/ship'
 require 'models/liquid'
 require 'models/molecule'
 require 'models/electron'
+require 'models/man'
+require 'models/interest'
 
 class AssociationsTest < ActiveRecord::TestCase
   fixtures :accounts, :companies, :developers, :projects, :developers_projects,
@@ -242,6 +244,17 @@ class AssociationProxyTest < ActiveRecord::TestCase
     david = developers(:david)
     assert david.projects.equal?(david.projects)
   end
+
+  test "inverses get set of subsets of the association" do
+    man = Man.create
+    man.interests.create
+
+    man = Man.find(man.id)
+
+    assert_queries(1) do
+      assert_equal man, man.interests.where("1=1").first.man
+    end
+  end
 end
 
 class OverridingAssociationsTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/attribute_methods/read_test.rb b/activerecord/test/cases/attribute_methods/read_test.rb
index 8d8ff2f..900a7ef 100644
--- a/activerecord/test/cases/attribute_methods/read_test.rb
+++ b/activerecord/test/cases/attribute_methods/read_test.rb
@@ -15,13 +15,6 @@ module ActiveRecord
 
           include ActiveRecord::AttributeMethods
 
-          def self.define_attribute_methods
-            # Created in the inherited/included hook for "proper" ARs
-            @attribute_methods_mutex ||= Mutex.new
-
-            super
-          end
-
           def self.column_names
             %w{ one two three }
           end
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 536ff48..635278a 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -566,7 +566,7 @@ class TestDefaultAutosaveAssociationOnNewRecord < ActiveRecord::TestCase
 end
 
 class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
-  self.use_transactional_fixtures = false unless supports_savepoints?
+  self.use_transactional_fixtures = false
 
   def setup
     super
@@ -705,6 +705,13 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
     ids.each { |id| assert_nil klass.find_by_id(id) }
   end
 
+  def test_should_not_resave_destroyed_association
+    @pirate.birds.create!(name: :parrot)
+    @pirate.birds.first.destroy
+    @pirate.save!
+    assert @pirate.reload.birds.empty?
+  end
+
   def test_should_skip_validation_on_has_many_if_marked_for_destruction
     2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") }
 
@@ -764,6 +771,20 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
     assert_equal 2, @pirate.birds.reload.length
   end
 
+  def test_should_save_new_record_that_has_same_value_as_existing_record_marked_for_destruction_on_field_that_has_unique_index
+    Bird.connection.add_index :birds, :name, unique: true
+
+    3.times { |i| @pirate.birds.create(name: "unique_birds_#{i}") }
+
+    @pirate.birds[0].mark_for_destruction
+    @pirate.birds.build(name: @pirate.birds[0].name)
+    @pirate.save!
+
+    assert_equal 3, @pirate.birds.reload.length
+  ensure
+    Bird.connection.remove_index :birds, column: :name
+  end
+
   # Add and remove callbacks tests for association collections.
   %w{ method proc }.each do |callback_type|
     define_method("test_should_run_add_callback_#{callback_type}s_for_has_many") do
@@ -846,8 +867,10 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase
     @pirate.parrots.each { |parrot| parrot.mark_for_destruction }
     assert @pirate.save
 
-    assert_queries(0) do
-      assert @pirate.save
+    Pirate.transaction do
+      assert_queries(0) do
+        assert @pirate.save
+      end
     end
   end
 
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
old mode 100644
new mode 100755
index bd568af..36c0fd2
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -1,3 +1,5 @@
+# encoding: utf-8
+
 require "cases/helper"
 require 'models/post'
 require 'models/author'
@@ -562,6 +564,23 @@ class BasicsTest < ActiveRecord::TestCase
     assert_equal [topic_2, topic_1].sort, [topic_1, topic_2]
   end
 
+  def test_create_without_prepared_statement
+    topic = Topic.connection.unprepared_statement do
+      Topic.create(:title => 'foo')
+    end
+
+    assert_equal topic, Topic.find(topic.id)
+  end
+
+  def test_destroy_without_prepared_statement
+    topic = Topic.create(title: 'foo')
+    Topic.connection.unprepared_statement do
+      Topic.find(topic.id).destroy
+    end
+
+    assert_equal nil, Topic.find_by_id(topic.id)
+  end
+
   def test_comparison_with_different_objects
     topic = Topic.create
     category = Category.create(:name => "comparison")
@@ -587,6 +606,26 @@ class BasicsTest < ActiveRecord::TestCase
     assert_deprecated { post._attr_readonly }
   end
 
+  def test_unicode_column_name
+    Weird.reset_column_information
+    weird = Weird.create(:なまえ => 'たこ焼き仮面')
+    assert_equal 'たこ焼き仮面', weird.なまえ
+  end
+
+  def test_respect_internal_encoding
+    if current_adapter?(:PostgreSQLAdapter)
+      skip 'pg does not respect internal encoding and always returns utf8'
+    end
+    old_default_internal = Encoding.default_internal
+    silence_warnings { Encoding.default_internal = "EUC-JP" }
+
+    Weird.reset_column_information
+
+    assert_equal ["EUC-JP"], Weird.columns.map {|c| c.name.encoding.name }.uniq
+  ensure
+    silence_warnings { Encoding.default_internal = old_default_internal }
+  end
+
   def test_non_valid_identifier_column_name
     weird = Weird.create('a$b' => 'value')
     weird.reload
diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb
index ba6b0b1..edc258b 100644
--- a/activerecord/test/cases/batches_test.rb
+++ b/activerecord/test/cases/batches_test.rb
@@ -50,6 +50,16 @@ class EachTest < ActiveRecord::TestCase
     Post.order("title").find_each { |post| post }
   end
 
+  def test_logger_not_required
+    previous_logger = ActiveRecord::Base.logger
+    ActiveRecord::Base.logger = nil
+    assert_nothing_raised do
+      Post.limit(1).find_each { |post| post }
+    end
+  ensure
+    ActiveRecord::Base.logger = previous_logger
+  end
+
   def test_find_in_batches_should_return_batches
     assert_queries(Post.count + 1) do
       Post.find_in_batches(:batch_size => 1) do |batch|
diff --git a/activerecord/test/cases/disconnected_test.rb b/activerecord/test/cases/disconnected_test.rb
new file mode 100644
index 0000000..1fecfd0
--- /dev/null
+++ b/activerecord/test/cases/disconnected_test.rb
@@ -0,0 +1,27 @@
+require "cases/helper"
+
+class TestRecord < ActiveRecord::Base
+end
+
+class TestDisconnectedAdapter < ActiveRecord::TestCase
+  self.use_transactional_fixtures = false
+
+  def setup
+    skip "in-memory database mustn't disconnect" if in_memory_db?
+    @connection = ActiveRecord::Base.connection
+  end
+
+  def teardown
+    return if in_memory_db?
+    spec = ActiveRecord::Base.connection_config
+    ActiveRecord::Base.establish_connection(spec)
+  end
+
+  test "can't execute statements while disconnected" do
+    @connection.execute "SELECT count(*) from products"
+    @connection.disconnect!
+    assert_raises(ActiveRecord::StatementInvalid) do
+      @connection.execute "SELECT count(*) from products"
+    end
+  end
+end
diff --git a/activerecord/test/cases/finder_respond_to_test.rb b/activerecord/test/cases/finder_respond_to_test.rb
index 9440cd4..2d0d8ad 100644
--- a/activerecord/test/cases/finder_respond_to_test.rb
+++ b/activerecord/test/cases/finder_respond_to_test.rb
@@ -31,6 +31,11 @@ class FinderRespondToTest < ActiveRecord::TestCase
     assert_respond_to Topic, :find_all_by_title_and_author_name
   end
 
+  def test_should_respond_to_find_by_with_bang
+    ensure_topic_method_is_not_cached(:find_by_title!)
+    assert_respond_to Topic, :find_by_title!
+  end
+
   def test_should_respond_to_find_by_two_attributes
     ensure_topic_method_is_not_cached(:find_by_title_and_author_name)
     assert_respond_to Topic, :find_by_title_and_author_name
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index 557cc7e..172a5cb 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -45,16 +45,17 @@ class FinderTest < ActiveRecord::TestCase
   end
 
   def test_exists
-    assert Topic.exists?(1)
-    assert Topic.exists?("1")
-    assert Topic.exists?(:author_name => "David")
-    assert Topic.exists?(:author_name => "Mary", :approved => true)
-    assert Topic.exists?(["parent_id = ?", 1])
-    assert !Topic.exists?(45)
-    assert !Topic.exists?(Topic.new)
+    assert_equal true, Topic.exists?(1)
+    assert_equal true, Topic.exists?("1")
+    assert_equal true, Topic.exists?(author_name: "David")
+    assert_equal true, Topic.exists?(author_name: "Mary", approved: true)
+    assert_equal true, Topic.exists?(["parent_id = ?", 1])
+
+    assert_equal false, Topic.exists?(45)
+    assert_equal false, Topic.exists?(Topic.new)
 
     begin
-      assert !Topic.exists?("foo")
+      assert_equal false, Topic.exists?("foo")
     rescue ActiveRecord::StatementInvalid
       # PostgreSQL complains about string comparison with integer field
     rescue Exception
@@ -71,49 +72,62 @@ class FinderTest < ActiveRecord::TestCase
   end
 
   def test_exists_returns_true_with_one_record_and_no_args
-    assert Topic.exists?
+    assert_equal true, Topic.exists?
   end
 
   def test_exists_returns_false_with_false_arg
-    assert !Topic.exists?(false)
+    assert_equal false, Topic.exists?(false)
   end
 
   # exists? should handle nil for id's that come from URLs and always return false
   # (example: Topic.exists?(params[:id])) where params[:id] is nil
   def test_exists_with_nil_arg
-    assert !Topic.exists?(nil)
-    assert Topic.exists?
-    assert !Topic.first.replies.exists?(nil)
-    assert Topic.first.replies.exists?
+    assert_equal false, Topic.exists?(nil)
+    assert_equal true, Topic.exists?
+
+    assert_equal false, Topic.first.replies.exists?(nil)
+    assert_equal true, Topic.first.replies.exists?
   end
 
   # ensures +exists?+ runs valid SQL by excluding order value
   def test_exists_with_order
-    assert Topic.order(:id).distinct.exists?
+    assert_equal true, Topic.order(:id).distinct.exists?
   end
 
   def test_exists_with_includes_limit_and_empty_result
-    assert !Topic.includes(:replies).limit(0).exists?
-    assert !Topic.includes(:replies).limit(1).where('0 = 1').exists?
+    assert_equal false, Topic.includes(:replies).limit(0).exists?
+    assert_equal false, Topic.includes(:replies).limit(1).where('0 = 1').exists?
+  end
+
+  def test_exists_with_distinct_association_includes_and_limit
+    author = Author.first
+    assert_equal false, author.unique_categorized_posts.includes(:special_comments).limit(0).exists?
+    assert_equal true, author.unique_categorized_posts.includes(:special_comments).limit(1).exists?
+  end
+
+  def test_exists_with_distinct_association_includes_limit_and_order
+    author = Author.first
+    assert_equal false, author.unique_categorized_posts.includes(:special_comments).order('comments.taggings_count DESC').limit(0).exists?
+    assert_equal true, author.unique_categorized_posts.includes(:special_comments).order('comments.taggings_count DESC').limit(1).exists?
   end
 
   def test_exists_with_empty_table_and_no_args_given
     Topic.delete_all
-    assert !Topic.exists?
+    assert_equal false, Topic.exists?
   end
 
   def test_exists_with_aggregate_having_three_mappings
     existing_address = customers(:david).address
-    assert Customer.exists?(:address => existing_address)
+    assert_equal true, Customer.exists?(:address => existing_address)
   end
 
   def test_exists_with_aggregate_having_three_mappings_with_one_difference
     existing_address = customers(:david).address
-    assert !Customer.exists?(:address =>
+    assert_equal false, Customer.exists?(:address =>
       Address.new(existing_address.street, existing_address.city, existing_address.country + "1"))
-    assert !Customer.exists?(:address =>
+    assert_equal false, Customer.exists?(:address =>
       Address.new(existing_address.street, existing_address.city + "1", existing_address.country))
-    assert !Customer.exists?(:address =>
+    assert_equal false, Customer.exists?(:address =>
       Address.new(existing_address.street + "1", existing_address.city, existing_address.country))
   end
 
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index f6cfee0..1bc055e 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -572,7 +572,7 @@ class LoadAllFixturesTest < ActiveRecord::TestCase
   fixtures :all
 
   def test_all_there
-    assert_equal %w(developers people tasks), fixture_table_names.sort
+    assert_equal %w(admin/accounts admin/users developers people tasks), fixture_table_names.sort
   end
 end
 
@@ -581,7 +581,7 @@ class LoadAllFixturesWithPathnameTest < ActiveRecord::TestCase
   fixtures :all
 
   def test_all_there
-    assert_equal %w(developers people tasks), fixture_table_names.sort
+    assert_equal %w(admin/accounts admin/users developers people tasks), fixture_table_names.sort
   end
 end
 
diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb
index a9be132..73cf99a 100644
--- a/activerecord/test/cases/inheritance_test.rb
+++ b/activerecord/test/cases/inheritance_test.rb
@@ -313,8 +313,12 @@ class InheritanceTest < ActiveRecord::TestCase
     assert_kind_of SpecialSubscriber, SpecialSubscriber.find("webster132")
     assert_nothing_raised { s = SpecialSubscriber.new("name" => "And breaaaaathe!"); s.id = 'roger'; s.save }
   end
-end
 
+  def test_scope_inherited_properly
+    assert_nothing_raised { Company.of_first_firm }
+    assert_nothing_raised { Client.of_first_firm }
+  end
+end
 
 class InheritanceComputeTypeTest < ActiveRecord::TestCase
   fixtures :companies
diff --git a/activerecord/test/cases/invalid_connection_test.rb b/activerecord/test/cases/invalid_connection_test.rb
new file mode 100644
index 0000000..f2d8f18
--- /dev/null
+++ b/activerecord/test/cases/invalid_connection_test.rb
@@ -0,0 +1,22 @@
+require "cases/helper"
+
+class TestAdapterWithInvalidConnection < ActiveRecord::TestCase
+  self.use_transactional_fixtures = false
+
+  class Bird < ActiveRecord::Base
+  end
+
+  def setup
+    # Can't just use current adapter; sqlite3 will create a database
+    # file on the fly.
+    Bird.establish_connection adapter: 'mysql', database: 'i_do_not_exist'
+  end
+
+  def teardown
+    Bird.remove_connection
+  end
+
+  test "inspect on Model class does not raise" do
+    assert_equal "#{Bird.name}(no database connection)", Bird.inspect
+  end
+end
diff --git a/activerecord/test/cases/invertible_migration_test.rb b/activerecord/test/cases/invertible_migration_test.rb
index be59ffc..428145d 100644
--- a/activerecord/test/cases/invertible_migration_test.rb
+++ b/activerecord/test/cases/invertible_migration_test.rb
@@ -58,6 +58,24 @@ module ActiveRecord
       end
     end
 
+    class RemoveIndexMigration1 < SilentMigration
+      def self.up
+        create_table("horses") do |t|
+          t.column :name, :string
+          t.column :color, :string
+          t.index [:name, :color]
+        end
+      end
+    end
+
+    class RemoveIndexMigration2 < SilentMigration
+      def change
+        change_table("horses") do |t|
+          t.remove_index [:name, :color]
+        end
+      end
+    end
+
     class LegacyMigration < ActiveRecord::Migration
       def self.up
         create_table("horses") do |t|
@@ -104,6 +122,16 @@ module ActiveRecord
       end
     end
 
+    def test_exception_on_removing_index_without_column_option
+      RemoveIndexMigration1.new.migrate(:up)
+      migration = RemoveIndexMigration2.new
+      migration.migrate(:up)
+
+      assert_raises(IrreversibleMigration) do
+        migration.migrate(:down)
+      end
+    end
+
     def test_migrate_up
       migration = InvertibleMigration.new
       migration.migrate(:up)
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index 77891b9..351e491 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -26,6 +26,18 @@ end
 class OptimisticLockingTest < ActiveRecord::TestCase
   fixtures :people, :legacy_things, :references, :string_key_objects, :peoples_treasures
 
+  def test_quote_value_passed_lock_col
+    p1 = Person.find(1)
+    assert_equal 0, p1.lock_version
+
+    Person.expects(:quote_value).with(0, Person.columns_hash[Person.locking_column]).returns('0').once
+
+    p1.first_name = 'anika2'
+    p1.save!
+
+    assert_equal 1, p1.lock_version
+  end
+
   def test_non_integer_lock_existing
     s1 = StringKeyObject.find("record1")
     s2 = StringKeyObject.find("record1")
diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb
index a9d46f4..304a906 100644
--- a/activerecord/test/cases/reflection_test.rb
+++ b/activerecord/test/cases/reflection_test.rb
@@ -18,6 +18,11 @@ require 'models/subscription'
 require 'models/tag'
 require 'models/sponsor'
 require 'models/edge'
+require 'models/hotel'
+require 'models/chef'
+require 'models/department'
+require 'models/cake_designer'
+require 'models/drink_designer'
 
 class ReflectionTest < ActiveRecord::TestCase
   include ActiveRecord::Reflection
@@ -235,6 +240,17 @@ class ReflectionTest < ActiveRecord::TestCase
     assert_equal expected, actual
   end
 
+  def test_scope_chain_does_not_interfere_with_hmt_with_polymorphic_case
+    @hotel = Hotel.create!
+    @department = @hotel.departments.create!
+    @department.chefs.create!(employable: CakeDesigner.create!)
+    @department.chefs.create!(employable: DrinkDesigner.create!)
+
+    assert_equal 1, @hotel.cake_designers.size
+    assert_equal 1, @hotel.drink_designers.size
+    assert_equal 2, @hotel.chefs.size
+  end
+
   def test_nested?
     assert !Author.reflect_on_association(:comments).nested?
     assert Author.reflect_on_association(:tags).nested?
diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb
index 482c1b3..c884c4c 100644
--- a/activerecord/test/cases/relation_test.rb
+++ b/activerecord/test/cases/relation_test.rb
@@ -179,7 +179,15 @@ module ActiveRecord
       assert_equal ['foo = bar'], relation.where_values
     end
 
-    def test_relation_merging_with_merged_joins
+    def test_merging_readonly_false
+      relation = Relation.new FakeKlass, :b
+      readonly_false_relation = relation.readonly(false)
+      # test merging in both directions
+      assert_equal false, relation.merge(readonly_false_relation).readonly_value
+      assert_equal false, readonly_false_relation.merge(relation).readonly_value
+    end
+
+    def test_relation_merging_with_merged_joins_as_symbols
       special_comments_with_ratings = SpecialComment.joins(:ratings)
       posts_with_special_comments_with_ratings = Post.group("posts.id").joins(:special_comments).merge(special_comments_with_ratings)
       assert_equal 3, authors(:david).posts.merge(posts_with_special_comments_with_ratings).count.length
@@ -193,12 +201,18 @@ module ActiveRecord
       assert_equal false, post.respond_to?(:title), "post should not respond_to?(:body) since invoking it raises exception"
     end
 
+    def test_relation_merging_with_merged_joins_as_strings
+      join_string = "LEFT OUTER JOIN #{Rating.quoted_table_name} ON #{SpecialComment.quoted_table_name}.id = #{Rating.quoted_table_name}.comment_id"
+      special_comments_with_ratings = SpecialComment.joins join_string
+      posts_with_special_comments_with_ratings = Post.group("posts.id").joins(:special_comments).merge(special_comments_with_ratings)
+      assert_equal 3, authors(:david).posts.merge(posts_with_special_comments_with_ratings).count.length
+    end
   end
 
   class RelationMutationTest < ActiveSupport::TestCase
     class FakeKlass < Struct.new(:table_name, :name)
-      def quoted_table_name
-        %{"#{table_name}"}
+      def arel_table
+        Post.arel_table
       end
     end
 
@@ -220,7 +234,10 @@ module ActiveRecord
 
     test "#order! with symbol prepends the table name" do
       assert relation.order!(:name).equal?(relation)
-      assert_equal ['"posts".name ASC'], relation.order_values
+      node = relation.order_values.first
+      assert node.ascending?
+      assert_equal :name, node.expr.name
+      assert_equal "posts", node.expr.relation.name
     end
 
     test '#references!' do
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index cf6af4e..2cfab6a 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -139,6 +139,13 @@ class RelationTest < ActiveRecord::TestCase
     assert_equal relation.to_a, Topic.select('a.*').from(relation, :a).to_a
   end
 
+  def test_finding_with_subquery_with_binds
+    relation = Post.first.comments
+    assert_equal relation.to_a, Comment.select('*').from(relation).to_a
+    assert_equal relation.to_a, Comment.select('subquery.*').from(relation).to_a
+    assert_equal relation.to_a, Comment.select('a.*').from(relation, :a).to_a
+  end
+
   def test_finding_with_conditions
     assert_equal ["David"], Author.where(:name => 'David').map(&:name)
     assert_equal ['Mary'],  Author.where(["name = ?", 'Mary']).map(&:name)
@@ -170,6 +177,10 @@ class RelationTest < ActiveRecord::TestCase
     assert_equal topics(:fourth).title, topics.first.title
   end
 
+  def test_order_with_hash_and_symbol_generates_the_same_sql
+    assert_equal Topic.order(:id).to_sql, Topic.order(id: :asc).to_sql
+  end
+
   def test_raising_exception_on_invalid_hash_params
     assert_raise(ArgumentError) { Topic.order(:name, "id DESC", :id => :DeSc) }
   end
@@ -180,7 +191,7 @@ class RelationTest < ActiveRecord::TestCase
   end
 
   def test_finding_with_order_concatenated
-    topics = Topic.order('title').order('author_name')
+    topics = Topic.order('author_name').order('title')
     assert_equal 4, topics.to_a.size
     assert_equal topics(:fourth).title, topics.first.title
   end
@@ -258,7 +269,7 @@ class RelationTest < ActiveRecord::TestCase
 
   def test_none_chained_to_methods_firing_queries_straight_to_db
     assert_no_queries do
-      assert_equal [],    Developer.none.pluck(:id) # => uses select_all
+      assert_equal [],    Developer.none.pluck(:id, :name)
       assert_equal 0,     Developer.none.delete_all
       assert_equal 0,     Developer.none.update_all(:name => 'David')
       assert_equal 0,     Developer.none.delete(1)
@@ -288,6 +299,10 @@ class RelationTest < ActiveRecord::TestCase
     assert_equal({}, Developer.none.where_values_hash)
   end
 
+  def test_null_relation_where_values_hash
+    assert_equal({ 'salary' => 100_000 }, Developer.none.where(salary: 100_000).where_values_hash)
+  end
+
   def test_joins_with_nil_argument
     assert_nothing_raised { DependentFirm.joins(nil).first }
   end
@@ -465,6 +480,14 @@ class RelationTest < ActiveRecord::TestCase
     assert_equal Developer.where(name: 'David').map(&:id).sort, developers
   end
 
+  def test_includes_with_select
+    query = Post.select('comments_count AS ranking').order('ranking').includes(:comments)
+      .where(comments: { id: 1 })
+
+    assert_equal ['comments_count AS ranking'], query.select_values
+    assert_equal 1, query.to_a.size
+  end
+
   def test_loading_with_one_association
     posts = Post.preload(:comments)
     post = posts.find { |p| p.id == 1 }
@@ -597,6 +620,36 @@ class RelationTest < ActiveRecord::TestCase
       relation = Author.where(:id => Author.where(:id => david.id))
       assert_equal [david], relation.to_a
     }
+
+    assert_queries(1) {
+      relation = Author.where('id in (?)', Author.where(id: david).select(:id))
+      assert_equal [david], relation.to_a
+    }
+
+    assert_queries(1) do
+      relation = Author.where('id in (:author_ids)', author_ids: Author.where(id: david).select(:id))
+      assert_equal [david], relation.to_a
+    end
+  end
+
+  def test_find_all_using_where_with_relation_with_bound_values
+    david = authors(:david)
+    davids_posts = david.posts.order(:id).to_a
+
+    assert_queries(1) do
+      relation = Post.where(id: david.posts.select(:id))
+      assert_equal davids_posts, relation.order(:id).to_a
+    end
+
+    assert_queries(1) do
+      relation = Post.where('id in (?)', david.posts.select(:id))
+      assert_equal davids_posts, relation.order(:id).to_a, 'should process Relation as bind variables'
+    end
+
+    assert_queries(1) do
+      relation = Post.where('id in (:post_ids)', post_ids: david.posts.select(:id))
+      assert_equal davids_posts, relation.order(:id).to_a, 'should process Relation as named bind variables'
+    end
   end
 
   def test_find_all_using_where_with_relation_and_alternate_primary_key
@@ -1174,20 +1227,20 @@ class RelationTest < ActiveRecord::TestCase
   end
 
   def test_default_scope_order_with_scope_order
-    assert_equal 'honda', CoolCar.order_using_new_style.limit(1).first.name
-    assert_equal 'honda', FastCar.order_using_new_style.limit(1).first.name
+    assert_equal 'zyke', CoolCar.order_using_new_style.limit(1).first.name
+    assert_equal 'zyke', FastCar.order_using_new_style.limit(1).first.name
   end
 
   def test_order_using_scoping
     car1 = CoolCar.order('id DESC').scoping do
-      CoolCar.all.merge!(:order => 'id asc').first
+      CoolCar.all.merge!(order: 'id asc').first
     end
-    assert_equal 'honda', car1.name
+    assert_equal 'zyke', car1.name
 
     car2 = FastCar.order('id DESC').scoping do
-      FastCar.all.merge!(:order => 'id asc').first
+      FastCar.all.merge!(order: 'id asc').first
     end
-    assert_equal 'honda', car2.name
+    assert_equal 'zyke', car2.name
   end
 
   def test_unscoped_block_style
@@ -1546,4 +1599,14 @@ class RelationTest < ActiveRecord::TestCase
     assert merged.to_sql.include?("wtf")
     assert merged.to_sql.include?("bbq")
   end
+
+  def test_merging_removes_lhs_bind_parameters
+    left  = Post.where(id: Arel::Nodes::BindParam.new('?'))
+    column = Post.columns_hash['id']
+    left.bind_values += [[column, 20]]
+    right   = Post.where(id: 10)
+
+    merged = left.merge(right)
+    assert_equal [], merged.bind_values
+  end
 end
diff --git a/activerecord/test/cases/sanitize_test.rb b/activerecord/test/cases/sanitize_test.rb
index 817897c..766b2ff 100644
--- a/activerecord/test/cases/sanitize_test.rb
+++ b/activerecord/test/cases/sanitize_test.rb
@@ -1,10 +1,21 @@
 require "cases/helper"
 require 'models/binary'
+require 'models/author'
+require 'models/post'
 
 class SanitizeTest < ActiveRecord::TestCase
   def setup
   end
 
+  def test_sanitize_sql_hash_handles_associations
+    quoted_bambi = ActiveRecord::Base.connection.quote("Bambi")
+    quoted_column_name = ActiveRecord::Base.connection.quote_column_name("name")
+    quoted_table_name = ActiveRecord::Base.connection.quote_table_name("adorable_animals")
+    expected_value = "#{quoted_table_name}.#{quoted_column_name} = #{quoted_bambi}"
+
+    assert_equal expected_value, Binary.send(:sanitize_sql_hash, {adorable_animals: {name: 'Bambi'}})
+  end
+
   def test_sanitize_sql_array_handles_string_interpolation
     quoted_bambi = ActiveRecord::Base.connection.quote_string("Bambi")
     assert_equal "name=#{quoted_bambi}", Binary.send(:sanitize_sql_array, ["name=%s", "Bambi"])
@@ -22,4 +33,17 @@ class SanitizeTest < ActiveRecord::TestCase
     assert_equal "name=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi\nand\nThumper"])
     assert_equal "name=#{quoted_bambi_and_thumper}", Binary.send(:sanitize_sql_array, ["name=?", "Bambi\nand\nThumper".mb_chars])
   end
+
+  def test_sanitize_sql_array_handles_relations
+    david = Author.create!(name: 'David')
+    david_posts = david.posts.select(:id)
+
+    sub_query_pattern = /\(\bselect\b.*?\bwhere\b.*?\)/i
+
+    select_author_sql = Post.send(:sanitize_sql_array, ['id in (?)', david_posts])
+    assert_match(sub_query_pattern, select_author_sql, 'should sanitize `Relation` as subquery for bind variables')
+
+    select_author_sql = Post.send(:sanitize_sql_array, ['id in (:post_ids)', post_ids: david_posts])
+    assert_match(sub_query_pattern, select_author_sql, 'should sanitize `Relation` as subquery for named bind variables')
+  end
 end
diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb
index a48ae10..1ee8e60 100644
--- a/activerecord/test/cases/schema_dumper_test.rb
+++ b/activerecord/test/cases/schema_dumper_test.rb
@@ -202,6 +202,11 @@ class SchemaDumperTest < ActiveRecord::TestCase
     assert_match %r(primary_key: "movieid"), match[1], "non-standard primary key not preserved"
   end
 
+  def test_schema_dump_should_use_false_as_default
+    output = standard_dump
+    assert_match %r{t\.boolean\s+"has_fun",.+default: false}, output
+  end
+
   if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
     def test_schema_dump_should_not_add_default_value_for_mysql_text_field
       output = standard_dump
@@ -299,7 +304,7 @@ class SchemaDumperTest < ActiveRecord::TestCase
 
     def test_schema_dump_includes_uuid_shorthand_definition
       output = standard_dump
-      if %r{create_table "poistgresql_uuids"} =~ output
+      if %r{create_table "postgresql_uuids"} =~ output
         assert_match %r{t.uuid "guid"}, output
       end
     end
diff --git a/activerecord/test/cases/scoping/default_scoping_test.rb b/activerecord/test/cases/scoping/default_scoping_test.rb
index 0f69443..11578ce 100644
--- a/activerecord/test/cases/scoping/default_scoping_test.rb
+++ b/activerecord/test/cases/scoping/default_scoping_test.rb
@@ -79,7 +79,7 @@ class DefaultScopingTest < ActiveRecord::TestCase
   end
 
   def test_scope_overwrites_default
-    expected = Developer.all.merge!(:order => ' name DESC, salary DESC').to_a.collect { |dev| dev.name }
+    expected = Developer.all.merge!(order: 'salary DESC, name DESC').to_a.collect { |dev| dev.name }
     received = DeveloperOrderedBySalary.by_name.to_a.collect { |dev| dev.name }
     assert_equal expected, received
   end
@@ -91,7 +91,7 @@ class DefaultScopingTest < ActiveRecord::TestCase
   end
 
   def test_order_after_reorder_combines_orders
-    expected = Developer.order('id DESC, name DESC').collect { |dev| [dev.name, dev.id] }
+    expected = Developer.order('name DESC, id DESC').collect { |dev| [dev.name, dev.id] }
     received = Developer.order('name ASC').reorder('name DESC').order('id DESC').collect { |dev| [dev.name, dev.id] }
     assert_equal expected, received
   end
@@ -251,8 +251,8 @@ class DefaultScopingTest < ActiveRecord::TestCase
   end
 
   def test_order_in_default_scope_should_not_prevail
-    expected = Developer.all.merge!(:order => 'salary').to_a.collect { |dev| dev.salary }
-    received = DeveloperOrderedBySalary.all.merge!(:order => 'salary').to_a.collect { |dev| dev.salary }
+    expected = Developer.all.merge!(order: 'salary desc').to_a.collect { |dev| dev.salary }
+    received = DeveloperOrderedBySalary.all.merge!(order: 'salary').to_a.collect { |dev| dev.salary }
     assert_equal expected, received
   end
 
diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb
index 765e92c..05d6f2d 100644
--- a/activerecord/test/cases/serialized_attribute_test.rb
+++ b/activerecord/test/cases/serialized_attribute_test.rb
@@ -251,7 +251,7 @@ class SerializedAttributeTest < ActiveRecord::TestCase
     Topic.create(content: myobj)
 
     Topic.all.each do |topic|
-      type = topic.instance_variable_get("@columns_hash")["content"]
+      type = Topic.column_types["content"]
       assert !type.instance_variable_get("@column").is_a?(ActiveRecord::AttributeMethods::Serialization::Type)
     end
   end
diff --git a/activerecord/test/fixtures/all/admin b/activerecord/test/fixtures/all/admin
new file mode 120000
index 0000000..984d12a
--- /dev/null
+++ b/activerecord/test/fixtures/all/admin
@@ -0,0 +1 @@
+../to_be_linked/
\ No newline at end of file
diff --git a/activerecord/test/fixtures/tasks.yml b/activerecord/test/fixtures/tasks.yml
index 402ca85..c38b32b 100644
--- a/activerecord/test/fixtures/tasks.yml
+++ b/activerecord/test/fixtures/tasks.yml
@@ -1,4 +1,4 @@
-# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
+# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
 first_task:
   id: 1
   starting: 2005-03-30t06:30:00.00+01:00
diff --git a/activerecord/test/fixtures/to_be_linked/accounts.yml b/activerecord/test/fixtures/to_be_linked/accounts.yml
new file mode 100644
index 0000000..9e341a1
--- /dev/null
+++ b/activerecord/test/fixtures/to_be_linked/accounts.yml
@@ -0,0 +1,2 @@
+signals37:
+  name: 37signals
diff --git a/activerecord/test/fixtures/to_be_linked/users.yml b/activerecord/test/fixtures/to_be_linked/users.yml
new file mode 100644
index 0000000..e2884be
--- /dev/null
+++ b/activerecord/test/fixtures/to_be_linked/users.yml
@@ -0,0 +1,10 @@
+david:
+  name: David
+  account: signals37
+
+jamis:
+  name: Jamis
+  account: signals37
+  settings:
+    :symbol: symbol
+    string: string
diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb
index a96899a..0e28cd4 100644
--- a/activerecord/test/models/author.rb
+++ b/activerecord/test/models/author.rb
@@ -13,7 +13,11 @@ class Author < ActiveRecord::Base
   has_many :posts_with_extension, :class_name => "Post"
   has_one  :post_about_thinking, -> { where("posts.title like '%thinking%'") }, :class_name => 'Post'
   has_one  :post_about_thinking_with_last_comment, -> { where("posts.title like '%thinking%'").includes(:last_comment) }, :class_name => 'Post'
-  has_many :comments, :through => :posts
+  has_many :comments, through: :posts do
+    def ratings
+      Rating.joins(:comment).merge(self)
+    end
+  end
   has_many :comments_containing_the_letter_e, :through => :posts, :source => :comments
   has_many :comments_with_order_and_conditions, -> { order('comments.body').where("comments.body like 'Thank%'") }, :through => :posts, :source => :comments
   has_many :comments_with_include, -> { includes(:post) }, :through => :posts, :source => :comments
@@ -27,6 +31,13 @@ class Author < ActiveRecord::Base
   has_many :thinking_posts, -> { where(:title => 'So I was thinking') }, :dependent => :delete_all, :class_name => 'Post'
   has_many :welcome_posts, -> { where(:title => 'Welcome to the weblog') }, :class_name => 'Post'
 
+  has_many :welcome_posts_with_comment,
+           -> { where(title: 'Welcome to the weblog').where('comments_count = ?', 1) },
+           class_name: 'Post'
+  has_many :welcome_posts_with_comments,
+           -> { where(title: 'Welcome to the weblog').where(Post.arel_table[:comments_count].gt(0)) },
+           class_name: 'Post'
+
   has_many :comments_desc, -> { order('comments.id DESC') }, :through => :posts, :source => :comments
   has_many :limited_comments, -> { limit(1) }, :through => :posts, :source => :comments
   has_many :funky_comments, :through => :posts, :source => :comments
diff --git a/activerecord/test/models/cake_designer.rb b/activerecord/test/models/cake_designer.rb
new file mode 100644
index 0000000..9c57ef5
--- /dev/null
+++ b/activerecord/test/models/cake_designer.rb
@@ -0,0 +1,3 @@
+class CakeDesigner < ActiveRecord::Base
+  has_one :chef, as: :employable
+end
diff --git a/activerecord/test/models/chef.rb b/activerecord/test/models/chef.rb
new file mode 100644
index 0000000..67a4e54
--- /dev/null
+++ b/activerecord/test/models/chef.rb
@@ -0,0 +1,3 @@
+class Chef < ActiveRecord::Base
+  belongs_to :employable, polymorphic: true
+end
diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb
index 3ca8f69..3cb99f6 100644
--- a/activerecord/test/models/company.rb
+++ b/activerecord/test/models/company.rb
@@ -11,6 +11,11 @@ class Company < AbstractCompany
   has_many :contracts
   has_many :developers, :through => :contracts
 
+  scope :of_first_firm, lambda {
+    joins(:account => :firm).
+    where('firms.id' => 1)
+  }
+
   def arbitrary_method
     "I am Jack's profound disappointment"
   end
@@ -45,7 +50,7 @@ class Firm < Company
   has_many :unsorted_clients, :class_name => "Client"
   has_many :unsorted_clients_with_symbol, :class_name => :Client
   has_many :clients_sorted_desc, -> { order "id DESC" }, :class_name => "Client"
-  has_many :clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client"
+  has_many :clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client", :inverse_of => :firm
   has_many :clients_ordered_by_name, -> { order "name" }, :class_name => "Client"
   has_many :unvalidated_clients_of_firm, :foreign_key => "client_of", :class_name => "Client", :validate => false
   has_many :dependent_clients_of_firm, -> { order "id" }, :foreign_key => "client_of", :class_name => "Client", :dependent => :destroy
@@ -144,6 +149,10 @@ class Client < Company
   has_many :accounts, :through => :firm
   belongs_to :account
 
+  validate do
+    firm
+  end
+
   class RaisedOnSave < RuntimeError; end
   attr_accessor :raise_on_save
   before_save do
diff --git a/activerecord/test/models/department.rb b/activerecord/test/models/department.rb
new file mode 100644
index 0000000..08004a0
--- /dev/null
+++ b/activerecord/test/models/department.rb
@@ -0,0 +1,4 @@
+class Department < ActiveRecord::Base
+  has_many :chefs
+  belongs_to :hotel
+end
diff --git a/activerecord/test/models/drink_designer.rb b/activerecord/test/models/drink_designer.rb
new file mode 100644
index 0000000..2db968e
--- /dev/null
+++ b/activerecord/test/models/drink_designer.rb
@@ -0,0 +1,3 @@
+class DrinkDesigner < ActiveRecord::Base
+  has_one :chef, as: :employable
+end
diff --git a/activerecord/test/models/hotel.rb b/activerecord/test/models/hotel.rb
new file mode 100644
index 0000000..b352cd2
--- /dev/null
+++ b/activerecord/test/models/hotel.rb
@@ -0,0 +1,6 @@
+class Hotel < ActiveRecord::Base
+  has_many :departments
+  has_many :chefs, through: :departments
+  has_many :cake_designers, source_type: 'CakeDesigner', source: :employable, through: :chefs
+  has_many :drink_designers, source_type: 'DrinkDesigner', source: :employable, through: :chefs
+end
diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb
index 2985160..1a282db 100644
--- a/activerecord/test/models/person.rb
+++ b/activerecord/test/models/person.rb
@@ -32,6 +32,7 @@ class Person < ActiveRecord::Base
 
   has_many :agents_posts,         :through => :agents,       :source => :posts
   has_many :agents_posts_authors, :through => :agents_posts, :source => :author
+  has_many :essays, primary_key: "first_name", foreign_key: "writer_id"
 
   scope :males,   -> { where(:gender => 'M') }
   scope :females, -> { where(:gender => 'F') }
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index 8beb58f..7a24d8c 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -1,3 +1,5 @@
+# encoding: utf-8
+
 ActiveRecord::Schema.define do
   def except(adapter_names_to_exclude)
     unless [adapter_names_to_exclude].flatten.include?(adapter_name)
@@ -780,9 +782,26 @@ ActiveRecord::Schema.define do
   end
   create_table :weirds, :force => true do |t|
     t.string 'a$b'
+    t.string 'なまえ'
     t.string 'from'
   end
 
+  create_table :hotels, force: true do |t|
+  end
+  create_table :departments, force: true do |t|
+    t.integer :hotel_id
+  end
+  create_table :cake_designers, force: true do |t|
+  end
+  create_table :drink_designers, force: true do |t|
+  end
+  create_table :chefs, force: true do |t|
+    t.integer :employable_id
+    t.string :employable_type
+    t.integer :department_id
+  end
+
+
   except 'SQLite' do
     # fk_test_has_fk should be before fk_test_has_pk
     create_table :fk_test_has_fk, :force => true do |t|
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index 39820df..f0a0459 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,3 +1,76 @@
+## Rails 4.0.1 (November 01, 2013) ##
+
+*   Disable the ability to iterate over Range of AS::TimeWithZone
+    due to significant performance issues.
+
+    *Bogdan Gusiev*
+
+*   Fix `ActiveSupport::Cache::FileStore#cleanup` to no longer rely on missing `each_key` method.
+
+    *Murray Steele*
+
+*   Ensure that autoloaded constants in all-caps nestings are marked as
+    autoloaded.
+
+    *Simon Coffey*
+
+*   Adds a new deprecation behaviour that raises an exception. Throwing this
+    line into `config/environments/development.rb`:
+
+        ActiveSupport::Deprecation.behavior = :raise
+
+    will cause the application to raise an `ActiveSupport::DeprecationException`
+    on deprecations.
+
+    Use this for aggressive deprecation cleanups.
+
+    *Xavier Noria*
+
+*   Improve `ActiveSupport::Cache::MemoryStore` cache size calculation.
+    The memory used by a key/entry pair is calculated via `#cached_size`:
+
+        def cached_size(key, entry)
+          key.to_s.bytesize + entry.size + PER_ENTRY_OVERHEAD
+        end
+
+    The value of `PER_ENTRY_OVERHEAD` is 240 bytes based on an [empirical
+    estimation](https://gist.github.com/ssimeonov/6047200) for 64-bit MRI on
+    1.9.3 and 2.0.
+
+    Fixes #11512.
+
+    *Simeon Simeonov*
+
+*   Only raise `Module::DelegationError` if it's the source of the exception.
+
+    Fixes #10559.
+
+*   Add `DateTime#usec` and `DateTime#nsec` so that `ActiveSupport::TimeWithZone` keeps
+    sub-second resolution when wrapping a `DateTime` value.
+
+    Fixes #10855.
+
+    *Andrew White*
+
+*   Make `Time.at_with_coercion` retain the second fraction and return local time.
+
+    Fixes #11350.
+
+    *Neer Friedman*, *Andrew White*
+
+*   Fix return value from `BacktraceCleaner#noise` when the cleaner is configured
+    with multiple silencers.
+
+    Fixes #11030.
+
+    *Mark J. Titorenko*
+
+*   Fix `ActiveSupport::Dependencies::Loadable#load_dependency` calling
+    `#blame_file!` on Exceptions that do not have the Blamable mixin
+
+    *Andrew Kreiling*
+
+
 ## Rails 4.0.0 (June 25, 2013) ##
 
 *   Override `Time.at` to support the passing of Time-like values when called with a single argument.
diff --git a/activesupport/README.rdoc b/activesupport/README.rdoc
index f358276..58ced93 100644
--- a/activesupport/README.rdoc
+++ b/activesupport/README.rdoc
@@ -14,7 +14,7 @@ The latest version of Active Support can be installed with RubyGems:
 
 Source code can be downloaded as part of the Rails project on GitHub:
 
-* https://github.com/rails/rails/tree/master/activesupport
+* https://github.com/rails/rails/tree/4-0-stable/activesupport
 
 
 == License
diff --git a/activesupport/Rakefile b/activesupport/Rakefile
index e3788ed..f50225a 100644
--- a/activesupport/Rakefile
+++ b/activesupport/Rakefile
@@ -9,13 +9,16 @@ Rake::TestTask.new do |t|
   t.verbose = true
 end
 
+
 namespace :test do
-  Rake::TestTask.new(:isolated) do |t|
-    t.pattern = 'test/ts_isolated.rb'
+  task :isolated do
+    ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
+    Dir.glob("test/**/*_test.rb").all? do |file|
+      sh(ruby, '-Ilib:test', file)
+    end or raise "Failures"
   end
 end
 
-
 spec = eval(File.read('activesupport.gemspec'))
 
 Gem::PackageTask.new(spec) do |p|
diff --git a/activesupport/lib/active_support/backtrace_cleaner.rb b/activesupport/lib/active_support/backtrace_cleaner.rb
index 4b41e62..c719c3b 100644
--- a/activesupport/lib/active_support/backtrace_cleaner.rb
+++ b/activesupport/lib/active_support/backtrace_cleaner.rb
@@ -97,11 +97,7 @@ module ActiveSupport
       end
 
       def noise(backtrace)
-        @silencers.each do |s|
-          backtrace = backtrace.select { |line| s.call(line) }
-        end
-
-        backtrace
+        backtrace - silence(backtrace)
       end
   end
 end
diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb
index 6c220ae..fc470f3 100644
--- a/activesupport/lib/active_support/cache.rb
+++ b/activesupport/lib/active_support/cache.rb
@@ -234,7 +234,7 @@ module ActiveSupport
       # bump the cache expiration time by the value set in <tt>:race_condition_ttl</tt>.
       # Yes, this process is extending the time for a stale value by another few
       # seconds. Because of extended life of the previous cache, other processes
-      # will continue to use slightly stale data for a just a big longer. In the
+      # will continue to use slightly stale data for a just a bit longer. In the
       # meantime that first process will go ahead and will write into cache the
       # new value. After that all the processes will start getting new value.
       # The key is to keep <tt>:race_condition_ttl</tt> small.
diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb
index 0c55aa8..2670648 100644
--- a/activesupport/lib/active_support/cache/file_store.rb
+++ b/activesupport/lib/active_support/cache/file_store.rb
@@ -29,7 +29,8 @@ module ActiveSupport
 
       def cleanup(options = nil)
         options = merged_options(options)
-        each_key(options) do |key|
+        search_dir(cache_path) do |fname|
+          key = file_path_key(fname)
           entry = read_entry(key, options)
           delete_entry(key, options) if entry && entry.expired?
         end
diff --git a/activesupport/lib/active_support/cache/memory_store.rb b/activesupport/lib/active_support/cache/memory_store.rb
index 4d26fb7..d319819 100644
--- a/activesupport/lib/active_support/cache/memory_store.rb
+++ b/activesupport/lib/active_support/cache/memory_store.rb
@@ -122,6 +122,13 @@ module ActiveSupport
       end
 
       protected
+
+        PER_ENTRY_OVERHEAD = 240
+
+        def cached_size(key, entry)
+          key.to_s.bytesize + entry.size + PER_ENTRY_OVERHEAD
+        end
+
         def read_entry(key, options) # :nodoc:
           entry = @data[key]
           synchronize do
@@ -139,8 +146,11 @@ module ActiveSupport
           synchronize do
             old_entry = @data[key]
             return false if @data.key?(key) && options[:unless_exist]
-            @cache_size -= old_entry.size if old_entry
-            @cache_size += entry.size
+            if old_entry
+              @cache_size -= (old_entry.size - entry.size)
+            else
+              @cache_size += cached_size(key, entry)
+            end
             @key_access[key] = Time.now.to_f
             @data[key] = entry
             prune(@max_size * 0.75, @max_prune_time) if @cache_size > @max_size
@@ -152,7 +162,7 @@ module ActiveSupport
           synchronize do
             @key_access.delete(key)
             entry = @data.delete(key)
-            @cache_size -= entry.size if entry
+            @cache_size -= cached_size(key, entry) if entry
             !!entry
           end
         end
diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb
index 1e8f0df..22adcd6 100644
--- a/activesupport/lib/active_support/callbacks.rb
+++ b/activesupport/lib/active_support/callbacks.rb
@@ -418,7 +418,7 @@ module ActiveSupport
       #
       #   set_callback :save, :before_meth
       #
-      # The callback can specified as a symbol naming an instance method; as a
+      # The callback can be specified as a symbol naming an instance method; as a
       # proc, lambda, or block; as a string to be instance evaluated; or as an
       # object that responds to a certain method determined by the <tt>:scope</tt>
       # argument to +define_callback+.
diff --git a/activesupport/lib/active_support/core_ext/date_time/acts_like.rb b/activesupport/lib/active_support/core_ext/date_time/acts_like.rb
index c79745c..8fbbe0d 100644
--- a/activesupport/lib/active_support/core_ext/date_time/acts_like.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/acts_like.rb
@@ -1,3 +1,4 @@
+require 'date'
 require 'active_support/core_ext/object/acts_like'
 
 class DateTime
diff --git a/activesupport/lib/active_support/core_ext/date_time/conversions.rb b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
index b7d8414..ccc27b4 100644
--- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb
+++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb
@@ -79,6 +79,16 @@ class DateTime
     seconds_since_unix_epoch.to_i
   end
 
+  # Returns the fraction of a second as microseconds
+  def usec
+    (sec_fraction * 1_000_000).to_i
+  end
+
+  # Returns the fraction of a second as nanoseconds
+  def nsec
+    (sec_fraction * 1_000_000_000).to_i
+  end
+
   private
 
   def offset_in_seconds
diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb
index 6d42667..eebf7d3 100644
--- a/activesupport/lib/active_support/core_ext/module/delegation.rb
+++ b/activesupport/lib/active_support/core_ext/module/delegation.rb
@@ -179,16 +179,17 @@ class Module
         exception = %(raise "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}")
 
         module_eval(<<-EOS, file, line - 2)
-          def #{method_prefix}#{method}(#{definition})        # def customer_name(*args, &block)
-            _ = #{to}                                         #   _ = client
-            _.#{method}(#{definition})                        #   _.name(*args, &block)
-          rescue NoMethodError                                # rescue NoMethodError
-            if _.nil?                                         #   if _.nil?
-              #{exception}                                    #     # add helpful message to the exception
-            else                                              #   else
-              raise                                           #     raise
-            end                                               #   end
-          end                                                 # end
+          def #{method_prefix}#{method}(#{definition})                                          # def customer_name(*args, &block)
+            _ = #{to}                                                                           #   _ = client
+            _.#{method}(#{definition})                                                          #   _.name(*args, &block)
+          rescue NoMethodError => e                                                             # rescue NoMethodError => e
+            location = "%s:%d:in `%s'" % [__FILE__, __LINE__ - 2, '#{method_prefix}#{method}']  #   location = "%s:%d:in `%s'" % [__FILE__, __LINE__ - 2, 'customer_name']
+            if _.nil? && e.backtrace.first == location                                          #   if _.nil? && e.backtrace.first == location
+              #{exception}                                                                      #     # add helpful message to the exception
+            else                                                                                #   else
+              raise                                                                             #     raise
+            end                                                                                 #   end
+          end                                                                                   # end
         EOS
       end
     end
diff --git a/activesupport/lib/active_support/core_ext/range.rb b/activesupport/lib/active_support/core_ext/range.rb
index 1d8b1ed..9368e81 100644
--- a/activesupport/lib/active_support/core_ext/range.rb
+++ b/activesupport/lib/active_support/core_ext/range.rb
@@ -1,3 +1,4 @@
 require 'active_support/core_ext/range/conversions'
 require 'active_support/core_ext/range/include_range'
 require 'active_support/core_ext/range/overlaps'
+require 'active_support/core_ext/range/each'
diff --git a/activesupport/lib/active_support/core_ext/range/each.rb b/activesupport/lib/active_support/core_ext/range/each.rb
new file mode 100644
index 0000000..d51ea2e
--- /dev/null
+++ b/activesupport/lib/active_support/core_ext/range/each.rb
@@ -0,0 +1,24 @@
+require 'active_support/core_ext/module/aliasing'
+require 'active_support/core_ext/object/acts_like'
+
+class Range #:nodoc:
+
+  def each_with_time_with_zone(&block)
+    ensure_iteration_allowed
+    each_without_time_with_zone(&block)
+  end
+  alias_method_chain :each, :time_with_zone
+
+  def step_with_time_with_zone(n = 1, &block)
+    ensure_iteration_allowed
+    step_without_time_with_zone(n, &block)
+  end
+  alias_method_chain :step, :time_with_zone
+
+  private
+  def ensure_iteration_allowed
+    if first.acts_like?(:time)
+      raise TypeError, "can't iterate from #{first.class}"
+    end
+  end
+end
diff --git a/activesupport/lib/active_support/core_ext/thread.rb b/activesupport/lib/active_support/core_ext/thread.rb
index 5481766..e80f442 100644
--- a/activesupport/lib/active_support/core_ext/thread.rb
+++ b/activesupport/lib/active_support/core_ext/thread.rb
@@ -23,14 +23,14 @@ class Thread
   # for the fiber local. The fiber is executed in the same thread, so the
   # thread local values are available.
   def thread_variable_get(key)
-    locals[key.to_sym]
+    _locals[key.to_sym]
   end
 
   # Sets a thread local with +key+ to +value+. Note that these are local to
   # threads, and not to fibers. Please see Thread#thread_variable_get for
   # more information.
   def thread_variable_set(key, value)
-    locals[key.to_sym] = value
+    _locals[key.to_sym] = value
   end
 
   # Returns an an array of the names of the thread-local variables (as Symbols).
@@ -45,7 +45,7 @@ class Thread
   # Note that these are not fiber local variables. Please see Thread#thread_variable_get
   # for more details.
   def thread_variables
-    locals.keys
+    _locals.keys
   end
 
   # Returns <tt>true</tt> if the given string (or symbol) exists as a
@@ -59,16 +59,21 @@ class Thread
   # Note that these are not fiber local variables. Please see Thread#thread_variable_get
   # for more details.
   def thread_variable?(key)
-    locals.has_key?(key.to_sym)
+    _locals.has_key?(key.to_sym)
+  end
+
+  def freeze
+    _locals.freeze
+    super
   end
 
   private
 
-  def locals
-    if defined?(@locals)
-      @locals
+  def _locals
+    if defined?(@_locals)
+      @_locals
     else
-      LOCK.synchronize { @locals ||= {} }
+      LOCK.synchronize { @_locals ||= {} }
     end
   end
 end unless Thread.instance_methods.include?(:thread_variable_set)
diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb
index c65f20c..0e4867c 100644
--- a/activesupport/lib/active_support/core_ext/time/calculations.rb
+++ b/activesupport/lib/active_support/core_ext/time/calculations.rb
@@ -69,10 +69,15 @@ class Time
     # Layers additional behavior on Time.at so that ActiveSupport::TimeWithZone and DateTime
     # instances can be used when called with a single argument
     def at_with_coercion(*args)
-      if args.size == 1 && args.first.acts_like?(:time)
-        at_without_coercion(args.first.to_i)
+      return at_without_coercion(*args) if args.size != 1
+
+      # Time.at can be called with a time or numerical value
+      time_or_number = args.first
+
+      if time_or_number.is_a?(ActiveSupport::TimeWithZone) || time_or_number.is_a?(DateTime)
+        at_without_coercion(time_or_number.to_f).getlocal
       else
-        at_without_coercion(*args)
+        at_without_coercion(time_or_number)
       end
     end
     alias_method :at_without_coercion, :at
diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb
index fff4c77..7f2f4f5 100644
--- a/activesupport/lib/active_support/dependencies.rb
+++ b/activesupport/lib/active_support/dependencies.rb
@@ -8,6 +8,7 @@ require 'active_support/core_ext/module/introspection'
 require 'active_support/core_ext/module/anonymous'
 require 'active_support/core_ext/module/qualified_const'
 require 'active_support/core_ext/object/blank'
+require 'active_support/core_ext/kernel/reporting'
 require 'active_support/core_ext/load_error'
 require 'active_support/core_ext/name_error'
 require 'active_support/core_ext/string/starts_ends_with'
@@ -213,7 +214,7 @@ module ActiveSupport #:nodoc:
           yield
         end
       rescue Exception => exception  # errors from loading file
-        exception.blame_file! file
+        exception.blame_file! file if exception.respond_to? :blame_file!
         raise
       end
 
@@ -459,7 +460,7 @@ module ActiveSupport #:nodoc:
         if loaded.include?(expanded)
           raise "Circular dependency detected while autoloading constant #{qualified_name}"
         else
-          require_or_load(expanded)
+          require_or_load(expanded, qualified_name)
           raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false)
           return from_mod.const_get(const_name)
         end
diff --git a/activesupport/lib/active_support/deprecation/behaviors.rb b/activesupport/lib/active_support/deprecation/behaviors.rb
index 90db180..45df3ac 100644
--- a/activesupport/lib/active_support/deprecation/behaviors.rb
+++ b/activesupport/lib/active_support/deprecation/behaviors.rb
@@ -1,14 +1,24 @@
 require "active_support/notifications"
 
 module ActiveSupport
+  class DeprecationException < StandardError
+  end
+
   class Deprecation
     # Default warning behaviors per Rails.env.
     DEFAULT_BEHAVIORS = {
-      :stderr => Proc.new { |message, callstack|
+      raise: ->(message, callstack) {
+        e = DeprecationException.new(message)
+        e.set_backtrace(callstack)
+        raise e
+      },
+
+      stderr: ->(message, callstack) {
         $stderr.puts(message)
         $stderr.puts callstack.join("\n  ") if debug
       },
-      :log => Proc.new { |message, callstack|
+      
+      log: ->(message, callstack) {
         logger =
             if defined?(Rails) && Rails.logger
               Rails.logger
@@ -19,11 +29,13 @@ module ActiveSupport
         logger.warn message
         logger.debug callstack.join("\n  ") if debug
       },
-      :notify => Proc.new { |message, callstack|
+      
+      notify: ->(message, callstack) {
         ActiveSupport::Notifications.instrument("deprecation.rails",
                                                 :message => message, :callstack => callstack)
       },
-      :silence => Proc.new { |message, callstack| }
+      
+      silence: ->(message, callstack) {},
     }
 
     module Behavior
@@ -40,6 +52,7 @@ module ActiveSupport
       #
       # Available behaviors:
       #
+      # [+raise+]   Raise <tt>ActiveSupport::DeprecationException</tt>.
       # [+stderr+]  Log all deprecation warnings to +$stderr+.
       # [+log+]     Log all deprecation warnings to +Rails.logger+.
       # [+notify+]  Use +ActiveSupport::Notifications+ to notify +deprecation.rails+.
@@ -52,7 +65,7 @@ module ActiveSupport
       #   ActiveSupport::Deprecation.behavior = :stderr
       #   ActiveSupport::Deprecation.behavior = [:stderr, :log]
       #   ActiveSupport::Deprecation.behavior = MyCustomHandler
-      #   ActiveSupport::Deprecation.behavior = proc { |message, callstack|
+      #   ActiveSupport::Deprecation.behavior = ->(message, callstack) {
       #     # custom stuff
       #   }
       def behavior=(behavior)
diff --git a/activesupport/lib/active_support/multibyte/unicode.rb b/activesupport/lib/active_support/multibyte/unicode.rb
index cbc1608..bb8910a 100644
--- a/activesupport/lib/active_support/multibyte/unicode.rb
+++ b/activesupport/lib/active_support/multibyte/unicode.rb
@@ -145,7 +145,7 @@ module ActiveSupport
             ncp << (HANGUL_TBASE + tindex) unless tindex == 0
             decomposed.concat ncp
           # if the codepoint is decomposable in with the current decomposition type
-          elsif (ncp = database.codepoints[cp].decomp_mapping) and (!database.codepoints[cp].decomp_type || type == :compatability)
+          elsif (ncp = database.codepoints[cp].decomp_mapping) and (!database.codepoints[cp].decomp_type || type == :compatibility)
             decomposed.concat decompose(type, ncp.dup)
           else
             decomposed << cp
@@ -283,9 +283,9 @@ module ActiveSupport
           when :c
             compose(reorder_characters(decompose(:canonical, codepoints)))
           when :kd
-            reorder_characters(decompose(:compatability, codepoints))
+            reorder_characters(decompose(:compatibility, codepoints))
           when :kc
-            compose(reorder_characters(decompose(:compatability, codepoints)))
+            compose(reorder_characters(decompose(:compatibility, codepoints)))
           else
             raise ArgumentError, "#{form} is not a valid normalization variant", caller
         end.pack('U*')
diff --git a/activesupport/lib/active_support/number_helper.rb b/activesupport/lib/active_support/number_helper.rb
index 414960d..c9c0eff 100644
--- a/activesupport/lib/active_support/number_helper.rb
+++ b/activesupport/lib/active_support/number_helper.rb
@@ -244,14 +244,14 @@ module ActiveSupport
     #
     # ==== Examples
     #
-    #   number_to_percentage(100)                                 # => 100.000%
-    #   number_to_percentage('98')                                # => 98.000%
-    #   number_to_percentage(100, precision: 0)                   # => 100%
-    #   number_to_percentage(1000, delimiter: '.', separator: ,') # => 1.000,000%
-    #   number_to_percentage(302.24398923423, precision: 5)       # => 302.24399%
-    #   number_to_percentage(1000, locale: :fr)                   # => 1 000,000%
-    #   number_to_percentage('98a')                               # => 98a%
-    #   number_to_percentage(100, format: '%n  %')                # => 100  %
+    #   number_to_percentage(100)                                  # => 100.000%
+    #   number_to_percentage('98')                                 # => 98.000%
+    #   number_to_percentage(100, precision: 0)                    # => 100%
+    #   number_to_percentage(1000, delimiter: '.', separator: ',') # => 1.000,000%
+    #   number_to_percentage(302.24398923423, precision: 5)        # => 302.24399%
+    #   number_to_percentage(1000, locale: :fr)                    # => 1 000,000%
+    #   number_to_percentage('98a')                                # => 98a%
+    #   number_to_percentage(100, format: '%n  %')                 # => 100  %
     def number_to_percentage(number, options = {})
       return unless number
       options = options.symbolize_keys
@@ -460,7 +460,7 @@ module ActiveSupport
     # See <tt>number_to_human_size</tt> if you want to print a file
     # size.
     #
-    # You can also define you own unit-quantifier names if you want
+    # You can also define your own unit-quantifier names if you want
     # to use other decimal units (eg.: 1500 becomes "1.5
     # kilometers", 0.150 becomes "150 milliliters", etc). You may
     # define a wide range of unit quantifiers, even fractional ones
diff --git a/activesupport/lib/active_support/rescuable.rb b/activesupport/lib/active_support/rescuable.rb
index 9a038df..a7eba91 100644
--- a/activesupport/lib/active_support/rescuable.rb
+++ b/activesupport/lib/active_support/rescuable.rb
@@ -1,6 +1,5 @@
 require 'active_support/concern'
 require 'active_support/core_ext/class/attribute'
-require 'active_support/core_ext/proc'
 require 'active_support/core_ext/string/inflections'
 require 'active_support/core_ext/array/extract_options'
 
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index 4a032b0..95b9b8e 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -292,7 +292,7 @@ module ActiveSupport
       end
     end
 
-    %w(year mon month day mday wday yday hour min sec to_date).each do |method_name|
+    %w(year mon month day mday wday yday hour min sec usec nsec to_date).each do |method_name|
       class_eval <<-EOV, __FILE__, __LINE__ + 1
         def #{method_name}    # def month
           time.#{method_name} #   time.month
@@ -300,10 +300,6 @@ module ActiveSupport
       EOV
     end
 
-    def usec
-      time.respond_to?(:usec) ? time.usec : 0
-    end
-
     def to_a
       [time.sec, time.min, time.hour, time.day, time.mon, time.year, time.wday, time.yday, dst?, zone]
     end
diff --git a/activesupport/lib/active_support/version.rb b/activesupport/lib/active_support/version.rb
index 66272d0..046494b 100644
--- a/activesupport/lib/active_support/version.rb
+++ b/activesupport/lib/active_support/version.rb
@@ -1,7 +1,7 @@
 module ActiveSupport
   # Returns the version of the currently loaded ActiveSupport as a Gem::Version
   def self.version
-    Gem::Version.new "4.0.0"
+    Gem::Version.new "4.0.2"
   end
 
   module VERSION #:nodoc:
diff --git a/activesupport/test/autoloading_fixtures/html/some_class.rb b/activesupport/test/autoloading_fixtures/html/some_class.rb
new file mode 100644
index 0000000..b43d15d
--- /dev/null
+++ b/activesupport/test/autoloading_fixtures/html/some_class.rb
@@ -0,0 +1,4 @@
+module HTML
+  class SomeClass
+  end
+end
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index bcc200c..00266a4 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -689,12 +689,24 @@ class FileStoreTest < ActiveSupport::TestCase
     @cache.send(:read_entry, "winston", {})
     assert @buffer.string.present?
   end
+
+  def test_cleanup_removes_all_expired_entries
+    time = Time.now
+    @cache.write('foo', 'bar', expires_in: 10)
+    @cache.write('baz', 'qux')
+    @cache.write('quux', 'corge', expires_in: 20)
+    Time.stubs(:now).returns(time + 15)
+    @cache.cleanup
+    assert_not @cache.exist?('foo')
+    assert @cache.exist?('baz')
+    assert @cache.exist?('quux')
+  end
 end
 
 class MemoryStoreTest < ActiveSupport::TestCase
   def setup
-    @record_size = ActiveSupport::Cache::Entry.new("aaaaaaaaaa").size
-    @cache = ActiveSupport::Cache.lookup_store(:memory_store, :expires_in => 60, :size => @record_size * 10)
+    @record_size = ActiveSupport::Cache.lookup_store(:memory_store).send(:cached_size, 1, ActiveSupport::Cache::Entry.new("aaaaaaaaaa"))
+    @cache = ActiveSupport::Cache.lookup_store(:memory_store, :expires_in => 60, :size => @record_size * 10 + 1)
   end
 
   include CacheStoreBehavior
@@ -744,6 +756,30 @@ class MemoryStoreTest < ActiveSupport::TestCase
     assert !@cache.exist?(1), "no entry"
   end
 
+  def test_prune_size_on_write_based_on_key_length
+    @cache.write(1, "aaaaaaaaaa") && sleep(0.001)
+    @cache.write(2, "bbbbbbbbbb") && sleep(0.001)
+    @cache.write(3, "cccccccccc") && sleep(0.001)
+    @cache.write(4, "dddddddddd") && sleep(0.001)
+    @cache.write(5, "eeeeeeeeee") && sleep(0.001)
+    @cache.write(6, "ffffffffff") && sleep(0.001)
+    @cache.write(7, "gggggggggg") && sleep(0.001)
+    @cache.write(8, "hhhhhhhhhh") && sleep(0.001)
+    @cache.write(9, "iiiiiiiiii") && sleep(0.001)
+    long_key = '*' * 2 * @record_size
+    @cache.write(long_key, "llllllllll")
+    assert @cache.exist?(long_key)
+    assert @cache.exist?(9)
+    assert @cache.exist?(8)
+    assert @cache.exist?(7)
+    assert @cache.exist?(6)
+    assert !@cache.exist?(5), "no entry"
+    assert !@cache.exist?(4), "no entry"
+    assert !@cache.exist?(3), "no entry"
+    assert !@cache.exist?(2), "no entry"
+    assert !@cache.exist?(1), "no entry"
+  end
+
   def test_pruning_is_capped_at_a_max_time
     def @cache.delete_entry (*args)
       sleep(0.01)
diff --git a/activesupport/test/clean_backtrace_test.rb b/activesupport/test/clean_backtrace_test.rb
index b14950a..dd67a45 100644
--- a/activesupport/test/clean_backtrace_test.rb
+++ b/activesupport/test/clean_backtrace_test.rb
@@ -36,6 +36,27 @@ class BacktraceCleanerSilencerTest < ActiveSupport::TestCase
   end
 end
 
+class BacktraceCleanerMultipleSilencersTest < ActiveSupport::TestCase
+  def setup
+    @bc = ActiveSupport::BacktraceCleaner.new
+    @bc.add_silencer { |line| line =~ /mongrel/ }
+    @bc.add_silencer { |line| line =~ /yolo/ }
+  end
+
+  test "backtrace should not contain lines that match the silencers" do
+    assert_equal \
+      [ "/other/class.rb" ],
+      @bc.clean([ "/mongrel/class.rb", "/other/class.rb", "/mongrel/stuff.rb", "/other/yolo.rb" ])
+  end
+
+  test "backtrace should only contain lines that match the silencers" do
+    assert_equal \
+      [ "/mongrel/class.rb", "/mongrel/stuff.rb", "/other/yolo.rb" ],
+      @bc.clean([ "/mongrel/class.rb", "/other/class.rb", "/mongrel/stuff.rb", "/other/yolo.rb" ],
+                :noise)
+  end
+end
+
 class BacktraceCleanerFilterAndSilencerTest < ActiveSupport::TestCase
   def setup
     @bc = ActiveSupport::BacktraceCleaner.new
diff --git a/activesupport/test/core_ext/date_time_ext_test.rb b/activesupport/test/core_ext/date_time_ext_test.rb
index 3e76b8a..571344b 100644
--- a/activesupport/test/core_ext/date_time_ext_test.rb
+++ b/activesupport/test/core_ext/date_time_ext_test.rb
@@ -327,6 +327,16 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
     assert_equal 946684800, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_i
   end
 
+  def test_usec
+    assert_equal 0, DateTime.civil(2000).usec
+    assert_equal 500000, DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)).usec
+  end
+
+  def test_nsec
+    assert_equal 0, DateTime.civil(2000).nsec
+    assert_equal 500000000, DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)).nsec
+  end
+
   protected
     def with_env_tz(new_tz = 'US/Eastern')
       old_tz, ENV['TZ'] = ENV['TZ'], new_tz
diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb
index 8872611..dfc3b58 100644
--- a/activesupport/test/core_ext/module_test.rb
+++ b/activesupport/test/core_ext/module_test.rb
@@ -66,6 +66,23 @@ Tester = Struct.new(:client) do
   delegate :name, :to => :client, :prefix => false
 end
 
+Product = Struct.new(:name) do
+  delegate :name, :to => :manufacturer, :prefix => true
+  delegate :name, :to => :type, :prefix => true
+
+  def manufacturer
+    @manufacturer ||= begin
+      nil.unknown_method
+    end
+  end
+
+  def type
+    @type ||= begin
+      nil.type_name
+    end
+  end
+end
+
 class ParameterSet
   delegate :[], :[]=, :to => :@params
 
@@ -264,6 +281,16 @@ class ModuleTest < ActiveSupport::TestCase
     assert_equal [3], se.ints
   end
 
+  def test_delegation_doesnt_mask_nested_no_method_error_on_nil_receiver
+    product = Product.new('Widget')
+
+    # Nested NoMethodError is a different name from the delegation
+    assert_raise(NoMethodError) { product.manufacturer_name }
+
+    # Nested NoMethodError is the same name as the delegation
+    assert_raise(NoMethodError) { product.type_name }
+  end
+
   def test_parent
     assert_equal Yz::Zy, Yz::Zy::Cd.parent
     assert_equal Yz, Yz::Zy.parent
diff --git a/activesupport/test/core_ext/numeric_ext_test.rb b/activesupport/test/core_ext/numeric_ext_test.rb
index f22ae3c..1da72eb 100644
--- a/activesupport/test/core_ext/numeric_ext_test.rb
+++ b/activesupport/test/core_ext/numeric_ext_test.rb
@@ -77,7 +77,7 @@ class NumericExtTimeAndDateTimeTest < ActiveSupport::TestCase
     assert_equal @dtnow.advance(:days => 1).advance(:months => 2), @dtnow + 1.day + 2.months
   end
 
-  def test_duration_after_convertion_is_no_longer_accurate
+  def test_duration_after_conversion_is_no_longer_accurate
     assert_equal 30.days.to_i.since(@now), 1.month.to_i.since(@now)
     assert_equal 365.25.days.to_f.since(@now), 1.year.to_f.since(@now)
     assert_equal 30.days.to_i.since(@dtnow), 1.month.to_i.since(@dtnow)
diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb
index 3e2355a..854b0a3 100644
--- a/activesupport/test/core_ext/range_ext_test.rb
+++ b/activesupport/test/core_ext/range_ext_test.rb
@@ -54,7 +54,7 @@ class RangeTest < ActiveSupport::TestCase
     assert((1...10) === (1...10))
   end
 
-  def test_should_compare_other_with_exlusive_end
+  def test_should_compare_other_with_exclusive_end
     assert((1..10) === (1...10))
   end
 
@@ -90,4 +90,26 @@ class RangeTest < ActiveSupport::TestCase
     time_range_2 = Time.utc(2005, 12, 10, 17, 31)..Time.utc(2005, 12, 10, 18, 00)
     assert !time_range_1.overlaps?(time_range_2)
   end
+
+  def test_each_on_time_with_zone
+    twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone['Eastern Time (US & Canada)'] , Time.utc(2006,11,28,10,30))
+    assert_raises TypeError do
+      ((twz - 1.hour)..twz).each {}
+    end
+  end
+
+  def test_step_on_time_with_zone
+    twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone['Eastern Time (US & Canada)'] , Time.utc(2006,11,28,10,30))
+    assert_raises TypeError do
+      ((twz - 1.hour)..twz).step(1) {}
+    end
+  end
+
+  def test_include_on_time_with_zone
+    twz = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone['Eastern Time (US & Canada)'] , Time.utc(2006,11,28,10,30))
+    assert_raises TypeError do
+      ((twz - 1.hour)..twz).include?(twz)
+    end
+  end
+
 end
diff --git a/activesupport/test/core_ext/thread_test.rb b/activesupport/test/core_ext/thread_test.rb
index 230c120..cf1b48d 100644
--- a/activesupport/test/core_ext/thread_test.rb
+++ b/activesupport/test/core_ext/thread_test.rb
@@ -63,6 +63,15 @@ class ThreadExt < ActiveSupport::TestCase
     end
   end
 
+  def test_thread_variable_frozen_after_set
+    t = Thread.new { }.join
+    t.thread_variable_set :foo, "bar"
+    t.freeze
+    assert_raises(RuntimeError) do
+      t.thread_variable_set(:baz, "qux")
+    end
+  end
+
   def test_thread_variable_security
     t = Thread.new { sleep }
 
diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb
index eefcdbb..aecaa1b 100644
--- a/activesupport/test/core_ext/time_ext_test.rb
+++ b/activesupport/test/core_ext/time_ext_test.rb
@@ -752,6 +752,21 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
     end
   end
 
+  def test_at_with_datetime_returns_local_time
+    with_env_tz 'US/Eastern' do
+      dt = DateTime.civil(2000, 1, 1, 0, 0, 0, '+0')
+      assert_equal Time.local(1999, 12, 31, 19, 0, 0), Time.at(dt)
+      assert_equal 'EST', Time.at(dt).zone
+      assert_equal(-18000, Time.at(dt).utc_offset)
+
+      # Daylight savings
+      dt = DateTime.civil(2000, 7, 1, 1, 0, 0, '+1')
+      assert_equal Time.local(2000, 6, 30, 20, 0, 0), Time.at(dt)
+      assert_equal 'EDT', Time.at(dt).zone
+      assert_equal(-14400, Time.at(dt).utc_offset)
+    end
+  end
+
   def test_at_with_time_with_zone
     assert_equal Time.utc(2000, 1, 1, 0, 0, 0), Time.at(ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['UTC']))
 
@@ -763,6 +778,45 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase
     end
   end
 
+  def test_at_with_time_with_zone_returns_local_time
+    with_env_tz 'US/Eastern' do
+      twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 1, 1, 0, 0, 0), ActiveSupport::TimeZone['London'])
+      assert_equal Time.local(1999, 12, 31, 19, 0, 0), Time.at(twz)
+      assert_equal 'EST', Time.at(twz).zone
+      assert_equal(-18000, Time.at(twz).utc_offset)
+
+      # Daylight savings
+      twz = ActiveSupport::TimeWithZone.new(Time.utc(2000, 7, 1, 0, 0, 0), ActiveSupport::TimeZone['London'])
+      assert_equal Time.local(2000, 6, 30, 20, 0, 0), Time.at(twz)
+      assert_equal 'EDT', Time.at(twz).zone
+      assert_equal(-14400, Time.at(twz).utc_offset)
+    end
+  end
+
+  def test_at_with_time_microsecond_precision
+    assert_equal Time.at(Time.utc(2000, 1, 1, 0, 0, 0, 111)).to_f, Time.utc(2000, 1, 1, 0, 0, 0, 111).to_f
+  end
+
+  def test_at_with_utc_time
+    with_env_tz 'US/Eastern' do
+      assert_equal Time.utc(2000), Time.at(Time.utc(2000))
+      assert_equal 'UTC', Time.at(Time.utc(2000)).zone
+      assert_equal(0, Time.at(Time.utc(2000)).utc_offset)
+    end
+  end
+
+  def test_at_with_local_time
+    with_env_tz 'US/Eastern' do
+      assert_equal Time.local(2000), Time.at(Time.local(2000))
+      assert_equal 'EST', Time.at(Time.local(2000)).zone
+      assert_equal(-18000, Time.at(Time.local(2000)).utc_offset)
+
+      assert_equal Time.local(2000, 7, 1), Time.at(Time.local(2000, 7, 1))
+      assert_equal 'EDT', Time.at(Time.local(2000, 7, 1)).zone
+      assert_equal(-14400, Time.at(Time.local(2000, 7, 1)).utc_offset)
+    end
+  end
+
   def test_eql?
     assert_equal true, Time.utc(2000).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone['UTC']) )
     assert_equal true, Time.utc(2000).eql?( ActiveSupport::TimeWithZone.new(Time.utc(2000), ActiveSupport::TimeZone["Hawaii"]) )
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index 3ce3297..8095b66 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -80,6 +80,11 @@ class TimeWithZoneTest < ActiveSupport::TestCase
     ActiveSupport.use_standard_json_time_format = old
   end
 
+  def test_to_json_when_wrapping_a_date_time
+    twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000), @time_zone)
+    assert_equal '"1999-12-31T19:00:00.000-05:00"', ActiveSupport::JSON.encode(twz)
+  end
+
   def test_nsec
     local     = Time.local(2011,6,7,23,59,59,Rational(999999999, 1000))
     with_zone = ActiveSupport::TimeWithZone.new(nil, ActiveSupport::TimeZone["Hawaii"], local)
@@ -445,6 +450,11 @@ class TimeWithZoneTest < ActiveSupport::TestCase
     assert_equal 0, twz.usec
   end
 
+  def test_usec_returns_sec_fraction_when_datetime_is_wrapped
+    twz = ActiveSupport::TimeWithZone.new(DateTime.civil(2000, 1, 1, 0, 0, Rational(1,2)), @time_zone)
+    assert_equal 500000, twz.usec
+  end
+
   def test_utc_to_local_conversion_saves_period_in_instance_variable
     assert_nil @twz.instance_variable_get('@period')
     @twz.time
diff --git a/activesupport/test/dependencies/raises_exception_without_blame_file.rb b/activesupport/test/dependencies/raises_exception_without_blame_file.rb
new file mode 100644
index 0000000..4b2da6f
--- /dev/null
+++ b/activesupport/test/dependencies/raises_exception_without_blame_file.rb
@@ -0,0 +1,5 @@
+exception = Exception.new('I am not blamable!')
+class << exception
+  undef_method(:blame_file!)
+end
+raise exception
diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb
index 115a4e8..df456be 100644
--- a/activesupport/test/dependencies_test.rb
+++ b/activesupport/test/dependencies_test.rb
@@ -76,6 +76,14 @@ class DependenciesTest < ActiveSupport::TestCase
     end
   end
 
+  def test_dependency_which_raises_doesnt_blindly_call_blame_file!
+    with_loading do
+      filename = 'dependencies/raises_exception_without_blame_file'
+
+      assert_raises(Exception) { require_dependency filename }
+    end
+  end
+
   def test_warnings_should_be_enabled_on_first_load
     with_loading 'dependencies' do
       old_warnings, ActiveSupport::Dependencies.warnings_on_first_load = ActiveSupport::Dependencies.warnings_on_first_load, true
@@ -640,6 +648,14 @@ class DependenciesTest < ActiveSupport::TestCase
     Object.class_eval { remove_const :E }
   end
 
+  def test_constants_in_capitalized_nesting_marked_as_autoloaded
+    with_autoloading_fixtures do
+      ActiveSupport::Dependencies.load_missing_constant(HTML, "SomeClass")
+
+      assert ActiveSupport::Dependencies.autoloaded?("HTML::SomeClass")
+    end
+  end
+
   def test_unloadable
     with_autoloading_fixtures do
       Object.const_set :M, Module.new
diff --git a/activesupport/test/deprecation_test.rb b/activesupport/test/deprecation_test.rb
index 9616e42..9674851 100644
--- a/activesupport/test/deprecation_test.rb
+++ b/activesupport/test/deprecation_test.rb
@@ -98,6 +98,22 @@ class DeprecationTest < ActiveSupport::TestCase
     assert_match(/foo=nil/, @b)
   end
 
+  def test_raise_behaviour
+    ActiveSupport::Deprecation.behavior = :raise
+
+    message   = 'Revise this deprecated stuff now!'
+    callstack = %w(foo bar baz)
+
+    begin
+      ActiveSupport::Deprecation.behavior.first.call(message, callstack)
+    rescue ActiveSupport::DeprecationException => e
+      assert_equal message, e.message
+      assert_equal callstack, e.backtrace
+    else
+      flunk 'the :raise deprecation behaviour should raise the expected exception'
+    end
+  end
+
   def test_default_stderr_behavior
     ActiveSupport::Deprecation.behavior = :stderr
     behavior = ActiveSupport::Deprecation.behavior.first
diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb
index 8686dcf..c50ff6f 100644
--- a/activesupport/test/json/encoding_test.rb
+++ b/activesupport/test/json/encoding_test.rb
@@ -195,7 +195,7 @@ class TestJSONEncoding < ActiveSupport::TestCase
     assert_nothing_raised do
       hash = {
         "CHI" => {
-          :dislay_name => "chicago",
+          :display_name => "chicago",
           :latitude => 123.234
         }
       }
diff --git a/activesupport/test/rescuable_test.rb b/activesupport/test/rescuable_test.rb
index e099e47..ec9d231 100644
--- a/activesupport/test/rescuable_test.rb
+++ b/activesupport/test/rescuable_test.rb
@@ -97,7 +97,7 @@ class RescuableTest < ActiveSupport::TestCase
     assert_equal expected, result
   end
 
-  def test_children_should_inherit_rescue_defintions_from_parents_and_child_rescue_should_be_appended
+  def test_children_should_inherit_rescue_definitions_from_parents_and_child_rescue_should_be_appended
     expected = ["WraithAttack", "WraithAttack", "NuclearExplosion", "MadRonon", "CoolError"]
     result = @cool_stargate.send(:rescue_handlers).collect {|e| e.first}
     assert_equal expected, result
diff --git a/activesupport/test/ts_isolated.rb b/activesupport/test/ts_isolated.rb
deleted file mode 100644
index 294d659..0000000
--- a/activesupport/test/ts_isolated.rb
+++ /dev/null
@@ -1,16 +0,0 @@
-require 'active_support/testing/autorun'
-require 'active_support/test_case'
-require 'rbconfig'
-require 'active_support/core_ext/kernel/reporting'
-
-class TestIsolated < ActiveSupport::TestCase
-  ruby = File.join(*RbConfig::CONFIG.values_at('bindir', 'RUBY_INSTALL_NAME'))
-
-  Dir["#{File.dirname(__FILE__)}/**/*_test.rb"].each do |file|
-    define_method("test #{file}") do
-      command = "#{ruby} -Ilib:test #{file}"
-      result = silence_stderr { `#{command}` }
-      assert $?.to_i.zero?, "#{command}\n#{result}"
-    end
-  end
-end
diff --git a/activesupport/test/xml_mini/jdom_engine_test.rb b/activesupport/test/xml_mini/jdom_engine_test.rb
index 904ef7b..ed4de8a 100644
--- a/activesupport/test/xml_mini/jdom_engine_test.rb
+++ b/activesupport/test/xml_mini/jdom_engine_test.rb
@@ -178,7 +178,7 @@ if RUBY_PLATFORM =~ /java/
     private
       def assert_equal_rexml(xml)
         parsed_xml = XmlMini.parse(xml)
-        hash = XmlMini.with_backend('REXML') { parsed_xml }
+        hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
         assert_equal(hash, parsed_xml)
       end
   end
diff --git a/activesupport/test/xml_mini/libxml_engine_test.rb b/activesupport/test/xml_mini/libxml_engine_test.rb
index e7cb350..a8df2e1 100644
--- a/activesupport/test/xml_mini/libxml_engine_test.rb
+++ b/activesupport/test/xml_mini/libxml_engine_test.rb
@@ -195,7 +195,8 @@ class LibxmlEngineTest < ActiveSupport::TestCase
   private
     def assert_equal_rexml(xml)
       parsed_xml = XmlMini.parse(xml)
-      hash = XmlMini.with_backend('REXML') { parsed_xml }
+      xml.rewind if xml.respond_to?(:rewind)
+      hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
       assert_equal(hash, parsed_xml)
     end
 end
diff --git a/activesupport/test/xml_mini/libxmlsax_engine_test.rb b/activesupport/test/xml_mini/libxmlsax_engine_test.rb
index 0748591..d6d9063 100644
--- a/activesupport/test/xml_mini/libxmlsax_engine_test.rb
+++ b/activesupport/test/xml_mini/libxmlsax_engine_test.rb
@@ -186,7 +186,8 @@ class LibXMLSAXEngineTest < ActiveSupport::TestCase
   private
     def assert_equal_rexml(xml)
       parsed_xml = XmlMini.parse(xml)
-      hash = XmlMini.with_backend('REXML') { parsed_xml }
+      xml.rewind if xml.respond_to?(:rewind)
+      hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
       assert_equal(hash, parsed_xml)
     end
 end
diff --git a/activesupport/test/xml_mini/nokogiri_engine_test.rb b/activesupport/test/xml_mini/nokogiri_engine_test.rb
index 9375177..2e96257 100644
--- a/activesupport/test/xml_mini/nokogiri_engine_test.rb
+++ b/activesupport/test/xml_mini/nokogiri_engine_test.rb
@@ -208,7 +208,8 @@ class NokogiriEngineTest < ActiveSupport::TestCase
   private
     def assert_equal_rexml(xml)
       parsed_xml = XmlMini.parse(xml)
-      hash = XmlMini.with_backend('REXML') { parsed_xml }
+      xml.rewind if xml.respond_to?(:rewind)
+      hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
       assert_equal(hash, parsed_xml)
     end
 end
diff --git a/activesupport/test/xml_mini/nokogirisax_engine_test.rb b/activesupport/test/xml_mini/nokogirisax_engine_test.rb
index d4f63f6..1807f92 100644
--- a/activesupport/test/xml_mini/nokogirisax_engine_test.rb
+++ b/activesupport/test/xml_mini/nokogirisax_engine_test.rb
@@ -209,7 +209,8 @@ class NokogiriSAXEngineTest < ActiveSupport::TestCase
   private
     def assert_equal_rexml(xml)
       parsed_xml = XmlMini.parse(xml)
-      hash = XmlMini.with_backend('REXML') { parsed_xml }
+      xml.rewind if xml.respond_to?(:rewind)
+      hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
       assert_equal(hash, parsed_xml)
     end
 end
diff --git a/activesupport/test/xml_mini/rexml_engine_test.rb b/activesupport/test/xml_mini/rexml_engine_test.rb
index 70a3b91..0c1f118 100644
--- a/activesupport/test/xml_mini/rexml_engine_test.rb
+++ b/activesupport/test/xml_mini/rexml_engine_test.rb
@@ -30,7 +30,8 @@ class REXMLEngineTest < ActiveSupport::TestCase
   private
     def assert_equal_rexml(xml)
       parsed_xml = XmlMini.parse(xml)
-      hash = XmlMini.with_backend('REXML') { parsed_xml }
+      xml.rewind if xml.respond_to?(:rewind)
+      hash = XmlMini.with_backend('REXML') { XmlMini.parse(xml) }
       assert_equal(hash, parsed_xml)
     end
 end
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index 0395cc0..743cdfa 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,9 +1,37 @@
+## Rails 4.0.1 (November 01, 2013) ##
+
+*   Fix the event name of action_dispatch requests.
+
+    *Rafael Mendonça França*
+
+*   Make `config.log_level` work with custom loggers.
+
+    *Max Shytikov*
+
+*   Fix `rake environment` to do not eager load modules
+
+    *Paul Nikitochkin*
+
+*   Fix `rails plugin --help` command.
+
+    *Richard Schneeman*
+
+*   Omit turbolinks configuration completely on skip_javascript generator option.
+
+    *Nikita Fedyashev*
+
+
 ## Rails 4.0.0 (June 25, 2013) ##
 
 *   Clearing autoloaded constants triggers routes reloading [Fixes #10685].
 
     *Xavier Noria*
 
+*   Fixes bug with scaffold generator with `--assets=false --resource-route=false`.
+    Fixes #9525.
+
+    *Arun Agrawal*
+
 *   Move rails.png into a data-uri. One less file to get generated into a new
     application. This is also consistent with the removal of index.html.
 
diff --git a/railties/RDOC_MAIN.rdoc b/railties/RDOC_MAIN.rdoc
index cadf0fb..eccdee7 100644
--- a/railties/RDOC_MAIN.rdoc
+++ b/railties/RDOC_MAIN.rdoc
@@ -18,7 +18,7 @@ you to present the data from database rows as objects and embellish these data o
 with business logic methods. Although most \Rails models are backed by a database, models
 can also be ordinary Ruby classes, or Ruby classes that implement a set of interfaces as
 provided by the ActiveModel module. You can read more about Active Record in its
-{README}[link:/activerecord/README.rdoc].
+{README}[link:files/activerecord/README_rdoc.html].
 
 The Controller layer is responsible for handling incoming HTTP requests and providing a
 suitable response. Usually this means returning \HTML, but \Rails controllers can also
@@ -29,7 +29,7 @@ In \Rails, the Controller and View layers are handled together by Action Pack.
 These two layers are bundled in a single package due to their heavy interdependence.
 This is unlike the relationship between Active Record and Action Pack, which are
 independent. Each of these packages can be used independently outside of \Rails. You
-can read more about Action Pack in its {README}[link:/actionpack/README.rdoc].
+can read more about Action Pack in its {README}[link:files/actionpack/README_rdoc.html].
 
 == Getting Started
 
@@ -55,7 +55,7 @@ can read more about Action Pack in its {README}[link:/actionpack/README.rdoc].
 
 5. Follow the guidelines to start developing your application. You may find the following resources handy:
 
-* The README file created within your application.
+* The \README file created within your application.
 * {Getting Started with \Rails}[http://guides.rubyonrails.org/getting_started.html].
 * {Ruby on \Rails Tutorial}[http://ruby.railstutorial.org/ruby-on-rails-tutorial-book].
 * {Ruby on \Rails Guides}[http://guides.rubyonrails.org].
diff --git a/railties/README.rdoc b/railties/README.rdoc
index 6248b5f..8834a2d 100644
--- a/railties/README.rdoc
+++ b/railties/README.rdoc
@@ -17,7 +17,7 @@ The latest version of Railties can be installed with RubyGems:
 
 Source code can be downloaded as part of the Rails project on GitHub
 
-* https://github.com/rails/rails/tree/master/railties
+* https://github.com/rails/rails/tree/4-0-stable/railties
 
 == License
 
diff --git a/railties/lib/rails/api/task.rb b/railties/lib/rails/api/task.rb
index c829873..edd2283 100644
--- a/railties/lib/rails/api/task.rb
+++ b/railties/lib/rails/api/task.rb
@@ -135,12 +135,20 @@ module Rails
       def api_dir
         'doc/rdoc'
       end
+    end
 
+    class EdgeTask < RepoTask
       def rails_version
         "master@#{`git rev-parse HEAD`[0, 7]}"
       end
     end
 
+    class StableTask < RepoTask
+      def rails_version
+        File.read('RAILS_VERSION').strip
+      end
+    end
+
     class AppTask < Task
       def component_root_dir(gem_name)
         $:.grep(%r{#{gem_name}[\w.-]*/lib\z}).first[0..-5]
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index 914e439..656b9eb 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -245,7 +245,8 @@ module Rails
       require "rails/tasks"
       config = self.config
       task :environment do
-        config.eager_load = false
+        ActiveSupport.on_load(:before_initialize) { config.eager_load = false }
+
         require_environment!
       end
     end
@@ -317,9 +318,7 @@ module Rails
           middleware.use ::ActionDispatch::SSL, config.ssl_options
         end
 
-        if config.action_dispatch.x_sendfile_header.present?
-          middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
-        end
+        middleware.use ::Rack::Sendfile, config.action_dispatch.x_sendfile_header
 
         if config.serve_static_assets
           middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb
index 62d57c0..a26d41c 100644
--- a/railties/lib/rails/application/bootstrap.rb
+++ b/railties/lib/rails/application/bootstrap.rb
@@ -42,7 +42,6 @@ INFO
           logger = ActiveSupport::Logger.new f
           logger.formatter = config.log_formatter
           logger = ActiveSupport::TaggedLogging.new(logger)
-          logger.level = ActiveSupport::Logger.const_get(config.log_level.to_s.upcase)
           logger
         rescue StandardError
           logger = ActiveSupport::TaggedLogging.new(ActiveSupport::Logger.new(STDERR))
@@ -53,6 +52,8 @@ INFO
           )
           logger
         end
+
+        Rails.logger.level = ActiveSupport::Logger.const_get(config.log_level.to_s.upcase)
       end
 
       # Initialize cache early in the stack so railties can make use of it.
diff --git a/railties/lib/rails/commands.rb b/railties/lib/rails/commands.rb
index aacde52..c2ce2b4 100644
--- a/railties/lib/rails/commands.rb
+++ b/railties/lib/rails/commands.rb
@@ -35,19 +35,17 @@ command = ARGV.shift
 command = aliases[command] || command
 
 case command
-when 'generate', 'destroy', 'plugin'
+when 'plugin'
+  require "rails/commands/plugin_new"
+when 'generate', 'destroy'
   require 'rails/generators'
 
-  if command == 'plugin' && ARGV.first == 'new'
-    require "rails/commands/plugin_new"
-  else
-    require APP_PATH
-    Rails.application.require_environment!
+  require APP_PATH
+  Rails.application.require_environment!
 
-    Rails.application.load_generators
+  Rails.application.load_generators
 
-    require "rails/commands/#{command}"
-  end
+  require "rails/commands/#{command}"
 
 when 'console'
   require 'rails/commands/console'
@@ -64,7 +62,7 @@ when 'console'
   Rails::Console.start(Rails.application, options)
 
 when 'server'
-  # Change to the application's path if there is no config.ru file in current dir.
+  # Change to the application's path if there is no config.ru file in current directory.
   # This allows us to run `rails server` from other directories, but still get
   # the main config.ru and properly set the tmp directory.
   Dir.chdir(File.expand_path('../../', APP_PATH)) unless File.exists?(File.expand_path("config.ru"))
diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb
index 86f62df..58f5324 100644
--- a/railties/lib/rails/engine.rb
+++ b/railties/lib/rails/engine.rb
@@ -102,7 +102,7 @@ module Rails
   #     paths["config"]              # => ["config"]
   #     paths["config/initializers"] # => ["config/initializers"]
   #     paths["config/locales"]      # => ["config/locales"]
-  #     paths["config/routes"]       # => ["config/routes.rb"]
+  #     paths["config/routes.rb"]    # => ["config/routes.rb"]
   #   end
   #
   # The <tt>Application</tt> class adds a couple more paths to this set. And as in your
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
index 1799e82..69c10ef 100644
--- a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
+++ b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
@@ -21,8 +21,13 @@
     <%%= f.label :password_confirmation %><br>
     <%%= f.password_field :password_confirmation %>
 <% else -%>
+  <%- if attribute.reference? -%>
+    <%%= f.label :<%= attribute.column_name %> %><br>
+    <%%= f.<%= attribute.field_type %> :<%= attribute.column_name %> %>
+  <%- else -%>
     <%%= f.label :<%= attribute.name %> %><br>
     <%%= f.<%= attribute.field_type %> :<%= attribute.name %> %>
+  <%- end -%>
 <% end -%>
   </div>
 <% end -%>
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index 5877579..fbfb234 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -68,7 +68,7 @@ module Rails
       directory "bin" do |content|
         "#{shebang}\n" + content
       end
-      chmod "bin", 0755, verbose: false
+      chmod "bin", 0755 & ~File.umask, verbose: false
     end
 
     def config
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index 577ff65..5cbca83 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -16,7 +16,7 @@ group :doc do
 end
 
 # Use ActiveModel has_secure_password
-# gem 'bcrypt-ruby', '~> 3.0.0'
+# gem 'bcrypt-ruby', '~> 3.1.2'
 
 # Use unicorn as the app server
 # gem 'unicorn'
diff --git a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
index d87c7b7..c3d1578 100644
--- a/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/app/views/layouts/application.html.erb.tt
@@ -2,8 +2,13 @@
 <html>
 <head>
   <title><%= camelized %></title>
+  <%- if options[:skip_javascript] -%>
+  <%%= stylesheet_link_tag    "application", media: "all" %>
+  <%%= javascript_include_tag "application" %>
+  <%- else -%>
   <%%= stylesheet_link_tag    "application", media: "all", "data-turbolinks-track" => true %>
   <%%= javascript_include_tag "application", "data-turbolinks-track" => true %>
+  <%- end -%>
   <%%= csrf_meta_tags %>
 </head>
 <body>
diff --git a/railties/lib/rails/generators/rails/app/templates/config/routes.rb b/railties/lib/rails/generators/rails/app/templates/config/routes.rb
index 1794ffa..e1f4acf 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/routes.rb
+++ b/railties/lib/rails/generators/rails/app/templates/config/routes.rb
@@ -39,7 +39,7 @@
   #       get 'recent', on: :collection
   #     end
   #   end
-  
+
   # Example resource route with concerns:
   #   concern :toggleable do
   #     post 'toggle'
diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore
index 25a742d..6a502e9 100644
--- a/railties/lib/rails/generators/rails/app/templates/gitignore
+++ b/railties/lib/rails/generators/rails/app/templates/gitignore
@@ -1,4 +1,4 @@
-# See http://help.github.com/ignore-files/ for more about ignoring files.
+# See https://help.github.com/articles/ignoring-files for more about ignoring files.
 #
 # If you find yourself ignoring temporary files generated by your text editor
 # or operating system, you probably want to add a global ignore instead:
diff --git a/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb
index 2a0522e..e89789e 100644
--- a/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb
+++ b/railties/lib/rails/generators/rails/scaffold/scaffold_generator.rb
@@ -8,6 +8,8 @@ module Rails
 
       class_option :stylesheets, type: :boolean, desc: "Generate Stylesheets"
       class_option :stylesheet_engine, desc: "Engine for Stylesheets"
+      class_option :assets, type: :boolean
+      class_option :resource_route, type: :boolean
 
       def handle_skip
         @options = @options.merge(stylesheets: false) unless options[:assets]
diff --git a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
index 90a92e6..f19e9d1 100644
--- a/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
+++ b/railties/lib/rails/generators/test_unit/model/templates/fixtures.yml
@@ -1,4 +1,4 @@
-# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html
+# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html
 <% unless attributes.empty? -%>
 <% %w(one two).each do |name| %>
 <%= name %>:
diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb
index 6ed6722..2f62506 100644
--- a/railties/lib/rails/rack/logger.rb
+++ b/railties/lib/rails/rack/logger.rb
@@ -11,7 +11,6 @@ module Rails
       def initialize(app, taggers = nil)
         @app          = app
         @taggers      = taggers || []
-        @instrumenter = ActiveSupport::Notifications.instrumenter
       end
 
       def call(env)
@@ -33,7 +32,8 @@ module Rails
           logger.debug ''
         end
 
-        @instrumenter.start 'action_dispatch.request', request: request
+        instrumenter = ActiveSupport::Notifications.instrumenter
+        instrumenter.start 'request.action_dispatch', request: request
         logger.info started_request_message(request)
         resp = @app.call(env)
         resp[2] = ::Rack::BodyProxy.new(resp[2]) { finish(request) }
@@ -70,7 +70,8 @@ module Rails
       private
 
       def finish(request)
-        @instrumenter.finish 'action_dispatch.request', request: request
+        instrumenter = ActiveSupport::Notifications.instrumenter
+        instrumenter.finish 'request.action_dispatch', request: request
       end
 
       def development?
diff --git a/railties/lib/rails/tasks.rb b/railties/lib/rails/tasks.rb
index 9807000..142af2d 100644
--- a/railties/lib/rails/tasks.rb
+++ b/railties/lib/rails/tasks.rb
@@ -1,6 +1,6 @@
 $VERBOSE = nil
 
-# Load Rails rakefile extensions
+# Load Rails Rakefile extensions
 %w(
   annotations
   documentation
diff --git a/railties/lib/rails/tasks/documentation.rake b/railties/lib/rails/tasks/documentation.rake
index 67270e7..d45e892 100644
--- a/railties/lib/rails/tasks/documentation.rake
+++ b/railties/lib/rails/tasks/documentation.rake
@@ -68,8 +68,8 @@ end
 
 namespace :doc do
   task :guides do
-    # FIXME: Reaching outside lib directory is a bad idea
-    require File.expand_path('../../../../../guides/rails_guides', __FILE__)
+    rails_gem_dir = Gem::Specification.find_by_name("rails").gem_dir
+    require File.expand_path(File.join(rails_gem_dir, "/guides/rails_guides"))
     RailsGuides::Generator.new(Rails.root.join("doc/guides")).generate
   end
 end
diff --git a/railties/lib/rails/templates/rails/welcome/index.html.erb b/railties/lib/rails/templates/rails/welcome/index.html.erb
index 4c4c80e..eb620ca 100644
--- a/railties/lib/rails/templates/rails/welcome/index.html.erb
+++ b/railties/lib/rails/templates/rails/welcome/index.html.erb
@@ -232,8 +232,8 @@
             </li>
 
             <li>
-              <h2>Create your database</h2>
-              <p>Run <code>rake db:create</code> to create your database. If you're not using SQLite (the default), edit <span class="filename">config/database.yml</span> with your username and password.</p>
+              <h2>Configure your database</h2>
+              <p>If you're not using SQLite (the default), edit <span class="filename">config/database.yml</span> with your username and password.</p>
             </li>
           </ol>
         </div>
diff --git a/railties/lib/rails/version.rb b/railties/lib/rails/version.rb
index 180c971..325c07e 100644
--- a/railties/lib/rails/version.rb
+++ b/railties/lib/rails/version.rb
@@ -2,7 +2,7 @@ module Rails
   module VERSION
     MAJOR = 4
     MINOR = 0
-    TINY  = 0
+    TINY  = 2
     PRE   = nil
 
     STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb
index 34432ea..891e57e 100644
--- a/railties/test/application/assets_test.rb
+++ b/railties/test/application/assets_test.rb
@@ -91,7 +91,7 @@ module ApplicationTests
         class UsersController < ApplicationController; end
       eoruby
       app_file "app/models/user.rb", <<-eoruby
-        class User < ActiveRecord::Base; end
+        class User < ActiveRecord::Base; raise 'should not be reached'; end
       eoruby
 
       ENV['RAILS_ENV']  = 'production'
diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb
index aeab311..3e9f682 100644
--- a/railties/test/application/configuration_test.rb
+++ b/railties/test/application/configuration_test.rb
@@ -671,5 +671,13 @@ module ApplicationTests
         end
       end
     end
+
+    test "config.log_level with custom logger" do
+      make_basic_app do |app|
+        app.config.logger = Logger.new(STDOUT)
+        app.config.log_level = :info
+      end
+      assert_equal Logger::INFO, Rails.logger.level
+    end
   end
 end
diff --git a/railties/test/application/middleware/remote_ip_test.rb b/railties/test/application/middleware/remote_ip_test.rb
index 91c5807..946b82e 100644
--- a/railties/test/application/middleware/remote_ip_test.rb
+++ b/railties/test/application/middleware/remote_ip_test.rb
@@ -33,6 +33,16 @@ module ApplicationTests
       end
     end
 
+    test "works with both headers individually" do
+      make_basic_app
+      assert_nothing_raised(ActionDispatch::RemoteIp::IpSpoofAttackError) do
+        assert_equal "1.1.1.1", remote_ip("HTTP_X_FORWARDED_FOR" => "1.1.1.1")
+      end
+      assert_nothing_raised(ActionDispatch::RemoteIp::IpSpoofAttackError) do
+        assert_equal "1.1.1.2", remote_ip("HTTP_CLIENT_IP" => "1.1.1.2")
+      end
+    end
+
     test "can disable IP spoofing check" do
       make_basic_app do |app|
         app.config.action_dispatch.ip_spoofing_check = false
diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb
index d8076c7..a74d60a 100644
--- a/railties/test/application/middleware_test.rb
+++ b/railties/test/application/middleware_test.rb
@@ -19,8 +19,6 @@ module ApplicationTests
     end
 
     test "default middleware stack" do
-      add_to_config "config.action_dispatch.x_sendfile_header = 'X-Sendfile'"
-
       boot!
 
       assert_equal [
@@ -49,12 +47,6 @@ module ApplicationTests
       ], middleware
     end
 
-    test "Rack::Sendfile is not included by default" do
-      boot!
-
-      assert !middleware.include?("Rack::Sendfile"), "Rack::Sendfile is not included in the default stack unless you set config.action_dispatch.x_sendfile_header"
-    end
-
     test "Rack::Cache is not included by default" do
       boot!
 
@@ -135,7 +127,7 @@ module ApplicationTests
     end
 
     test "insert middleware after" do
-      add_to_config "config.middleware.insert_after ActionDispatch::Static, Rack::Config"
+      add_to_config "config.middleware.insert_after Rack::Sendfile, Rack::Config"
       boot!
       assert_equal "Rack::Config", middleware.second
     end
@@ -143,16 +135,16 @@ module ApplicationTests
     test "Rails.cache does not respond to middleware" do
       add_to_config "config.cache_store = :memory_store"
       boot!
-      assert_equal "Rack::Runtime", middleware.third
+      assert_equal "Rack::Runtime", middleware.fourth
     end
 
     test "Rails.cache does respond to middleware" do
       boot!
-      assert_equal "Rack::Runtime", middleware.fourth
+      assert_equal "Rack::Runtime", middleware.fifth
     end
 
     test "insert middleware before" do
-      add_to_config "config.middleware.insert_before ActionDispatch::Static, Rack::Config"
+      add_to_config "config.middleware.insert_before Rack::Sendfile, Rack::Config"
       boot!
       assert_equal "Rack::Config", middleware.first
     end
diff --git a/railties/test/application/rake_test.rb b/railties/test/application/rake_test.rb
index fa3ab96..72f2ecb 100644
--- a/railties/test/application/rake_test.rb
+++ b/railties/test/application/rake_test.rb
@@ -9,7 +9,6 @@ module ApplicationTests
     def setup
       build_app
       boot_rails
-      FileUtils.rm_rf("#{app_path}/config/environments")
     end
 
     def teardown
@@ -56,10 +55,8 @@ module ApplicationTests
       assert_match "Doing something...", output
     end
 
-    def test_does_not_explode_when_accessing_a_model_with_eager_load
+    def test_does_not_explode_when_accessing_a_model
       add_to_config <<-RUBY
-        config.eager_load = true
-
         rake_tasks do
           task do_nothing: :environment do
             Hello.new.world
@@ -67,33 +64,38 @@ module ApplicationTests
         end
       RUBY
 
-      app_file "app/models/hello.rb", <<-RUBY
-      class Hello
-        def world
-          puts "Hello world"
+      app_file 'app/models/hello.rb', <<-RUBY
+        class Hello
+          def world
+            puts 'Hello world'
+          end
         end
-      end
       RUBY
 
-      output = Dir.chdir(app_path){ `rake do_nothing` }
-      assert_match "Hello world", output
+      output = Dir.chdir(app_path) { `rake do_nothing` }
+      assert_match 'Hello world', output
     end
 
-    def test_should_not_eager_load_model_path_for_rake
+    def test_should_not_eager_load_model_for_rake
       add_to_config <<-RUBY
-        config.eager_load = true
-
         rake_tasks do
           task do_nothing: :environment do
           end
         end
       RUBY
 
-      app_file "app/models/hello.rb", <<-RUBY
-      raise 'should not be pre-required for rake even `eager_load=true`'
+      add_to_env_config 'production', <<-RUBY
+        config.eager_load = true
+      RUBY
+
+      app_file 'app/models/hello.rb', <<-RUBY
+        raise 'should not be pre-required for rake even eager_load=true'
       RUBY
 
-      Dir.chdir(app_path){ `rake do_nothing` }
+      Dir.chdir(app_path) do
+        assert system('rake do_nothing RAILS_ENV=production'),
+               'should not be pre-required for rake even eager_load=true'
+      end
     end
 
     def test_code_statistics_sanity
diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb
index 25372d0..0f8d673 100644
--- a/railties/test/application/routing_test.rb
+++ b/railties/test/application/routing_test.rb
@@ -372,6 +372,51 @@ module ApplicationTests
       end
     end
 
+    test 'named routes are cleared when reloading' do
+      app('development')
+
+      controller :foo, <<-RUBY
+        class FooController < ApplicationController
+          def index
+            render text: "foo"
+          end
+        end
+      RUBY
+
+      controller :bar, <<-RUBY
+        class BarController < ApplicationController
+          def index
+            render text: "bar"
+          end
+        end
+      RUBY
+
+      app_file 'config/routes.rb', <<-RUBY
+        Rails.application.routes.draw do
+          get ':locale/foo', to: 'foo#index', as: 'foo'
+        end
+      RUBY
+
+      get '/en/foo'
+      assert_equal 'foo', last_response.body
+      assert_equal '/en/foo', Rails.application.routes.url_helpers.foo_path(:locale => 'en')
+
+      app_file 'config/routes.rb', <<-RUBY
+        Rails.application.routes.draw do
+          get ':locale/bar', to: 'bar#index', as: 'foo'
+        end
+      RUBY
+
+      Rails.application.reload_routes!
+
+      get '/en/foo'
+      assert_equal 404, last_response.status
+
+      get '/en/bar'
+      assert_equal 'bar', last_response.body
+      assert_equal '/en/bar', Rails.application.routes.url_helpers.foo_path(:locale => 'en')
+    end
+
     test 'resource routing with irregular inflection' do
       app_file 'config/initializers/inflection.rb', <<-RUBY
         ActiveSupport::Inflector.inflections do |inflect|
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 74c4c4e..6c48869 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -53,9 +53,10 @@ class AppGeneratorTest < Rails::Generators::TestCase
 
   def test_assets
     run_generator
-    assert_file "app/views/layouts/application.html.erb", /stylesheet_link_tag\s+"application"/
-    assert_file "app/views/layouts/application.html.erb", /javascript_include_tag\s+"application"/
-    assert_file "app/assets/stylesheets/application.css"
+
+    assert_file("app/views/layouts/application.html.erb", /stylesheet_link_tag\s+"application", media: "all", "data-turbolinks-track" => true/)
+    assert_file("app/views/layouts/application.html.erb", /javascript_include_tag\s+"application", "data-turbolinks-track" => true/)
+    assert_file("app/assets/stylesheets/application.css")
   end
 
   def test_invalid_application_name_raises_an_error
@@ -295,6 +296,10 @@ class AppGeneratorTest < Rails::Generators::TestCase
     assert_file "app/assets/javascripts/application.js" do |contents|
       assert_no_match %r{^//=\s+require\s}, contents
     end
+    assert_file "app/views/layouts/application.html.erb" do |contents|
+      assert_match(/stylesheet_link_tag\s+"application", media: "all" %>/, contents)
+      assert_match(/javascript_include_tag\s+"application" \%>/, contents)
+    end
     assert_file "Gemfile" do |content|
       assert_match(/coffee-rails/, content)
     end
diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb
index 25f2991..524bbde 100644
--- a/railties/test/generators/scaffold_generator_test.rb
+++ b/railties/test/generators/scaffold_generator_test.rb
@@ -239,13 +239,27 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
     assert_file "config/routes.rb", /\.routes\.draw do\s*\|map\|\s*$/
   end
 
-  def test_scaffold_generator_no_assets
+  def test_scaffold_generator_no_assets_with_switch_no_assets
     run_generator [ "posts", "--no-assets" ]
     assert_no_file "app/assets/stylesheets/scaffold.css"
     assert_no_file "app/assets/javascripts/posts.js"
     assert_no_file "app/assets/stylesheets/posts.css"
   end
 
+  def test_scaffold_generator_no_assets_with_switch_assets_false
+    run_generator [ "posts", "--assets=false" ]
+    assert_no_file "app/assets/stylesheets/scaffold.css"
+    assert_no_file "app/assets/javascripts/posts.js"
+    assert_no_file "app/assets/stylesheets/posts.css"
+  end
+
+  def test_scaffold_generator_no_assets_with_switch_resource_route_false
+    run_generator [ "posts", "--resource-route=false" ]
+    assert_file "config/routes.rb" do |route|
+      assert_no_match(/resources :posts$/, route)
+    end
+  end
+
   def test_scaffold_generator_no_stylesheets
     run_generator [ "posts", "--no-stylesheets" ]
     assert_no_file "app/assets/stylesheets/scaffold.css"
@@ -272,6 +286,30 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
     end
   end
 
+  def test_scaffold_generator_belongs_to
+    run_generator ["account", "name", "currency:belongs_to"]
+
+    assert_file "app/models/account.rb", /belongs_to :currency/
+
+    assert_migration "db/migrate/create_accounts.rb" do |m|
+      assert_method :change, m do |up|
+        assert_match(/t\.string :name/, up)
+        assert_match(/t\.belongs_to :currency/, up)
+      end
+    end
+
+    assert_file "app/controllers/accounts_controller.rb" do |content|
+      assert_instance_method :account_params, content do |m|
+        assert_match(/permit\(:name, :currency_id\)/, m)
+      end
+    end
+
+    assert_file "app/views/accounts/_form.html.erb" do |content|
+      assert_match(/^\W{4}<%= f\.text_field :name %>/, content)
+      assert_match(/^\W{4}<%= f\.text_field :currency_id %>/, content)
+    end
+  end
+
   def test_scaffold_generator_password_digest
     run_generator ["user", "name", "password:digest"]
 
diff --git a/railties/test/rack_logger_test.rb b/railties/test/rack_logger_test.rb
index 3a9392f..cfd2c5b 100644
--- a/railties/test/rack_logger_test.rb
+++ b/railties/test/rack_logger_test.rb
@@ -38,7 +38,7 @@ module Rails
       def setup
         @subscriber = Subscriber.new
         @notifier = ActiveSupport::Notifications.notifier
-        notifier.subscribe 'action_dispatch.request', subscriber
+        notifier.subscribe 'request.action_dispatch', subscriber
       end
 
       def teardown
diff --git a/tools/profile b/tools/profile
index 665efe0..fbea674 100755
--- a/tools/profile
+++ b/tools/profile
@@ -4,7 +4,6 @@
 ENV['NO_RELOAD'] ||= '1'
 ENV['RAILS_ENV'] ||= 'development'
 
-Gem.source_index
 require 'benchmark'
 
 module RequireProfiler
diff --git a/version.rb b/version.rb
index 180c971..325c07e 100644
--- a/version.rb
+++ b/version.rb
@@ -2,7 +2,7 @@ module Rails
   module VERSION
     MAJOR = 4
     MINOR = 0
-    TINY  = 0
+    TINY  = 2
     PRE   = nil
 
     STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-ruby-extras/rails.git



More information about the Pkg-ruby-extras-commits mailing list