aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.github/stale.yml24
-rw-r--r--.travis.yml17
-rw-r--r--Gemfile2
-rw-r--r--Gemfile.lock76
-rw-r--r--RAILS_VERSION2
-rw-r--r--RELEASING_RAILS.md2
-rw-r--r--actioncable/CHANGELOG.md46
-rw-r--r--actioncable/README.md4
-rw-r--r--actioncable/lib/action_cable/connection/authorization.rb10
-rw-r--r--actioncable/lib/action_cable/gem_version.rb4
-rw-r--r--actioncable/package.json2
-rw-r--r--actioncable/test/channel/stream_test.rb4
-rw-r--r--actionmailer/CHANGELOG.md34
-rw-r--r--actionmailer/lib/action_mailer/gem_version.rb4
-rw-r--r--actionpack/CHANGELOG.md409
-rw-r--r--actionpack/lib/action_controller/metal/mime_responds.rb2
-rw-r--r--actionpack/lib/action_dispatch/http/mime_negotiation.rb4
-rw-r--r--actionpack/lib/action_dispatch/http/mime_type.rb18
-rw-r--r--actionpack/lib/action_dispatch/http/parameters.rb11
-rw-r--r--actionpack/lib/action_dispatch/http/request.rb14
-rw-r--r--actionpack/lib/action_dispatch/http/response.rb4
-rw-r--r--actionpack/lib/action_dispatch/http/url.rb2
-rw-r--r--actionpack/lib/action_dispatch/journey/formatter.rb2
-rw-r--r--actionpack/lib/action_dispatch/journey/gtg/transition_table.rb1
-rw-r--r--actionpack/lib/action_dispatch/journey/route.rb9
-rw-r--r--actionpack/lib/action_dispatch/journey/router/utils.rb2
-rw-r--r--actionpack/lib/action_dispatch/journey/visitors.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb10
-rw-r--r--actionpack/lib/action_dispatch/middleware/flash.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/remote_ip.rb6
-rw-r--r--actionpack/lib/action_dispatch/middleware/session/abstract_store.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/show_exceptions.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb4
-rw-r--r--actionpack/lib/action_dispatch/request/session.rb8
-rw-r--r--actionpack/lib/action_dispatch/request/utils.rb3
-rw-r--r--actionpack/lib/action_dispatch/routing.rb2
-rw-r--r--actionpack/lib/action_dispatch/routing/inspector.rb2
-rw-r--r--actionpack/lib/action_dispatch/routing/mapper.rb50
-rw-r--r--actionpack/lib/action_dispatch/routing/redirection.rb4
-rw-r--r--actionpack/lib/action_dispatch/routing/route_set.rb2
-rw-r--r--actionpack/lib/action_dispatch/routing/url_for.rb4
-rw-r--r--actionpack/lib/action_dispatch/system_test_case.rb2
-rw-r--r--actionpack/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/response.rb2
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/routing.rb8
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb8
-rw-r--r--actionpack/lib/action_dispatch/testing/test_request.rb2
-rw-r--r--actionpack/lib/action_pack/gem_version.rb4
-rw-r--r--actionpack/test/controller/api/with_helpers_test.rb26
-rw-r--r--actionview/CHANGELOG.md217
-rw-r--r--actionview/app/assets/javascripts/features/disable.coffee4
-rw-r--r--actionview/app/assets/javascripts/rails-ujs.coffee7
-rw-r--r--actionview/lib/action_view/digestor.rb6
-rw-r--r--actionview/lib/action_view/gem_version.rb4
-rw-r--r--actionview/package.json2
-rw-r--r--actionview/test/template/digestor_test.rb4
-rw-r--r--actionview/test/ujs/public/test/data-confirm.js28
-rw-r--r--activejob/CHANGELOG.md50
-rw-r--r--activejob/lib/active_job/gem_version.rb4
-rw-r--r--activemodel/CHANGELOG.md32
-rw-r--r--activemodel/lib/active_model/gem_version.rb4
-rw-r--r--activemodel/lib/active_model/validations/numericality.rb1
-rw-r--r--activemodel/test/cases/validations/numericality_validation_test.rb9
-rw-r--r--activerecord/CHANGELOG.md772
-rw-r--r--activerecord/lib/active_record/associations/collection_proxy.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract/quoting.rb15
-rw-r--r--activerecord/lib/active_record/connection_adapters/abstract_adapter.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/oid/bytea.rb2
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb6
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb47
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql/utils.rb4
-rw-r--r--activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb26
-rw-r--r--activerecord/lib/active_record/gem_version.rb4
-rw-r--r--activerecord/lib/active_record/log_subscriber.rb18
-rw-r--r--activerecord/lib/active_record/migration/compatibility.rb5
-rw-r--r--activerecord/lib/active_record/railties/databases.rake7
-rw-r--r--activerecord/lib/active_record/relation/predicate_builder.rb21
-rw-r--r--activerecord/lib/active_record/tasks/database_tasks.rb4
-rw-r--r--activerecord/lib/active_record/transactions.rb2
-rw-r--r--activerecord/test/cases/adapters/postgresql/bytea_test.rb1
-rw-r--r--activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb175
-rw-r--r--activerecord/test/cases/adapters/postgresql/statement_pool_test.rb8
-rw-r--r--activerecord/test/cases/associations/callbacks_test.rb2
-rw-r--r--activerecord/test/cases/associations/cascaded_eager_loading_test.rb2
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb6
-rw-r--r--activerecord/test/cases/associations/has_one_through_associations_test.rb2
-rw-r--r--activerecord/test/cases/associations/inner_join_association_test.rb2
-rw-r--r--activerecord/test/cases/associations/join_model_test.rb2
-rw-r--r--activerecord/test/cases/associations/left_outer_join_association_test.rb2
-rw-r--r--activerecord/test/cases/associations/nested_through_associations_test.rb2
-rw-r--r--activerecord/test/cases/associations_test.rb4
-rw-r--r--activerecord/test/cases/base_test.rb2
-rw-r--r--activerecord/test/cases/bind_parameter_test.rb121
-rw-r--r--activerecord/test/cases/fixtures_test.rb2
-rw-r--r--activerecord/test/cases/json_serialization_test.rb2
-rw-r--r--activerecord/test/cases/readonly_test.rb2
-rw-r--r--activerecord/test/cases/relation/merging_test.rb4
-rw-r--r--activerecord/test/cases/relation/where_test.rb2
-rw-r--r--activerecord/test/cases/relation_test.rb2
-rw-r--r--activerecord/test/cases/relations_test.rb2
-rw-r--r--activerecord/test/cases/scoping/relation_scoping_test.rb4
-rw-r--r--activerecord/test/cases/tasks/database_tasks_test.rb8
-rw-r--r--activerecord/test/cases/transactions_test.rb2
-rw-r--r--activerecord/test/cases/yaml_serialization_test.rb2
-rw-r--r--activesupport/CHANGELOG.md629
-rw-r--r--activesupport/lib/active_support/core_ext/object/duplicable.rb38
-rw-r--r--activesupport/lib/active_support/deprecation.rb3
-rw-r--r--activesupport/lib/active_support/deprecation/constant_accessor.rb50
-rw-r--r--activesupport/lib/active_support/gem_version.rb4
-rw-r--r--activesupport/lib/active_support/values/time_zone.rb17
-rw-r--r--activesupport/test/core_ext/object/duplicable_test.rb5
-rw-r--r--activesupport/test/deprecation_test.rb23
-rw-r--r--activesupport/test/time_zone_test.rb4
-rwxr-xr-xci/travis.rb1
-rw-r--r--guides/CHANGELOG.md7
-rw-r--r--guides/bug_report_templates/action_controller_gem.rb2
-rw-r--r--guides/bug_report_templates/action_controller_master.rb1
-rw-r--r--guides/bug_report_templates/active_job_gem.rb2
-rw-r--r--guides/bug_report_templates/active_job_master.rb1
-rw-r--r--guides/bug_report_templates/active_record_gem.rb2
-rw-r--r--guides/bug_report_templates/active_record_master.rb1
-rw-r--r--guides/bug_report_templates/active_record_migrations_gem.rb2
-rw-r--r--guides/bug_report_templates/active_record_migrations_master.rb1
-rw-r--r--guides/bug_report_templates/generic_gem.rb2
-rw-r--r--guides/bug_report_templates/generic_master.rb1
-rw-r--r--guides/source/_welcome.html.erb3
-rw-r--r--guides/source/action_cable_overview.md6
-rw-r--r--guides/source/caching_with_rails.md8
-rw-r--r--guides/source/command_line.md10
-rw-r--r--guides/source/configuring.md2
-rw-r--r--guides/source/contributing_to_ruby_on_rails.md6
-rw-r--r--guides/source/debugging_rails_applications.md12
-rw-r--r--guides/source/documents.yaml5
-rw-r--r--guides/source/getting_started.md2
-rw-r--r--guides/source/security.md4
-rw-r--r--guides/source/testing.md6
-rw-r--r--railties/CHANGELOG.md200
-rw-r--r--railties/lib/rails/application/configuration.rb12
-rw-r--r--railties/lib/rails/commands/destroy/destroy_command.rb3
-rw-r--r--railties/lib/rails/commands/runner/runner_command.rb5
-rw-r--r--railties/lib/rails/commands/server/server_command.rb6
-rw-r--r--railties/lib/rails/gem_version.rb4
-rw-r--r--railties/lib/rails/generators/app_base.rb16
-rw-r--r--railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb6
-rw-r--r--railties/lib/rails/generators/named_base.rb4
-rw-r--r--railties/lib/rails/generators/rails/app/app_generator.rb37
-rw-r--r--railties/lib/rails/generators/rails/app/templates/Gemfile2
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt1
-rw-r--r--railties/lib/rails/generators/rails/app/templates/config/secrets.yml4
-rw-r--r--railties/lib/rails/tasks/framework.rake2
-rw-r--r--railties/test/application/generators_test.rb3
-rw-r--r--railties/test/application/middleware/cache_test.rb16
-rw-r--r--railties/test/application/rake/migrations_test.rb16
-rw-r--r--railties/test/application/runner_test.rb8
-rw-r--r--railties/test/commands/server_test.rb8
-rw-r--r--railties/test/generators/api_app_generator_test.rb22
-rw-r--r--railties/test/generators/app_generator_test.rb46
-rw-r--r--railties/test/generators/scaffold_generator_test.rb8
-rw-r--r--version.rb4
159 files changed, 943 insertions, 2890 deletions
diff --git a/.github/stale.yml b/.github/stale.yml
new file mode 100644
index 0000000000..387b8fea9c
--- /dev/null
+++ b/.github/stale.yml
@@ -0,0 +1,24 @@
+# Number of days of inactivity before an issue becomes stale
+days: 90
+# Issues with these labels will never be considered stale
+exemptLabels:
+ - pinned
+ - security
+ - With reproduction steps
+ - attached PR
+ - regression
+ - release blocker
+# Label to use when marking an issue as stale
+staleLabel: stale
+# Comment to post when marking an issue as stale. Set to `false` to disable
+markComment: >
+ This issue has been automatically marked as stale because it has not been commented on for at least three months.
+
+ The resources of the Rails team are limited, and so we are asking for your help.
+
+ If you can still reproduce this error on the `5-1-stable` branch or on `master`,
+ please reply with all of the information you have about it in order to keep the issue open.
+
+ Thank you for all your contributions.
+# Comment to post when closing a stale issue. Set to `false` to disable
+closeComment: false
diff --git a/.travis.yml b/.travis.yml
index 72b077be65..ed4e0fba3b 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -15,6 +15,9 @@ services:
addons:
postgresql: "9.4"
+ apt:
+ packages:
+ - postgresql-9.4
bundler_args: --without test --jobs 3 --retry 3
before_install:
@@ -54,12 +57,12 @@ env:
rvm:
- 2.2.6
- 2.3.3
- - 2.4.0
+ - 2.4.1
- ruby-head
matrix:
include:
- - rvm: 2.4.0
+ - rvm: 2.4.1
env: "GEM=av:ujs"
- rvm: 2.2.6
env: "GEM=aj:integration"
@@ -73,7 +76,7 @@ matrix:
- memcached
- redis
- rabbitmq
- - rvm: 2.4.0
+ - rvm: 2.4.1
env: "GEM=aj:integration"
services:
- memcached
@@ -90,7 +93,7 @@ matrix:
- "GEM=ar:mysql2 MYSQL=mariadb"
addons:
mariadb: 10.0
- - rvm: 2.4.0
+ - rvm: 2.4.1
env:
- "GEM=ar:sqlite3_mem"
- rvm: jruby-9.1.8.0
@@ -101,6 +104,12 @@ matrix:
jdk: oraclejdk8
env:
- "GEM=am,amo,aj"
+ # Test with old (< 9.4.2) postgresql
+ - rvm: 2.4.0
+ env:
+ - "GEM=ar:postgresql"
+ addons:
+ postgresql: "9.4"
allow_failures:
- rvm: ruby-head
- rvm: jruby-9.1.8.0
diff --git a/Gemfile b/Gemfile
index 6f0bc534df..5077c257d9 100644
--- a/Gemfile
+++ b/Gemfile
@@ -7,6 +7,8 @@ end
gemspec
+gem "arel", github: "rails/arel"
+
# We need a newish Rake since Active Job sets its test tasks' descriptions.
gem "rake", ">= 11.1"
diff --git a/Gemfile.lock b/Gemfile.lock
index 580333f6e6..0c9337bf2a 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -23,61 +23,67 @@ GIT
event_emitter
websocket
+GIT
+ remote: https://github.com/rails/arel.git
+ revision: 437aa3a4bb8ad4f3f4eba299dbb1112852f9c7ac
+ specs:
+ arel (8.0.0)
+
PATH
remote: .
specs:
- actioncable (5.1.0.beta1)
- actionpack (= 5.1.0.beta1)
+ actioncable (5.2.0.alpha)
+ actionpack (= 5.2.0.alpha)
nio4r (~> 2.0)
websocket-driver (~> 0.6.1)
- actionmailer (5.1.0.beta1)
- actionpack (= 5.1.0.beta1)
- actionview (= 5.1.0.beta1)
- activejob (= 5.1.0.beta1)
+ actionmailer (5.2.0.alpha)
+ actionpack (= 5.2.0.alpha)
+ actionview (= 5.2.0.alpha)
+ activejob (= 5.2.0.alpha)
mail (~> 2.5, >= 2.5.4)
rails-dom-testing (~> 2.0)
- actionpack (5.1.0.beta1)
- actionview (= 5.1.0.beta1)
- activesupport (= 5.1.0.beta1)
+ actionpack (5.2.0.alpha)
+ actionview (= 5.2.0.alpha)
+ activesupport (= 5.2.0.alpha)
rack (~> 2.0)
rack-test (~> 0.6.3)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.2)
- actionview (5.1.0.beta1)
- activesupport (= 5.1.0.beta1)
+ actionview (5.2.0.alpha)
+ activesupport (= 5.2.0.alpha)
builder (~> 3.1)
erubi (~> 1.4)
rails-dom-testing (~> 2.0)
rails-html-sanitizer (~> 1.0, >= 1.0.3)
- activejob (5.1.0.beta1)
- activesupport (= 5.1.0.beta1)
+ activejob (5.2.0.alpha)
+ activesupport (= 5.2.0.alpha)
globalid (>= 0.3.6)
- activemodel (5.1.0.beta1)
- activesupport (= 5.1.0.beta1)
- activerecord (5.1.0.beta1)
- activemodel (= 5.1.0.beta1)
- activesupport (= 5.1.0.beta1)
+ activemodel (5.2.0.alpha)
+ activesupport (= 5.2.0.alpha)
+ activerecord (5.2.0.alpha)
+ activemodel (= 5.2.0.alpha)
+ activesupport (= 5.2.0.alpha)
arel (~> 8.0)
- activesupport (5.1.0.beta1)
+ activesupport (5.2.0.alpha)
concurrent-ruby (~> 1.0, >= 1.0.2)
i18n (~> 0.7)
minitest (~> 5.1)
tzinfo (~> 1.1)
- rails (5.1.0.beta1)
- actioncable (= 5.1.0.beta1)
- actionmailer (= 5.1.0.beta1)
- actionpack (= 5.1.0.beta1)
- actionview (= 5.1.0.beta1)
- activejob (= 5.1.0.beta1)
- activemodel (= 5.1.0.beta1)
- activerecord (= 5.1.0.beta1)
- activesupport (= 5.1.0.beta1)
+ rails (5.2.0.alpha)
+ actioncable (= 5.2.0.alpha)
+ actionmailer (= 5.2.0.alpha)
+ actionpack (= 5.2.0.alpha)
+ actionview (= 5.2.0.alpha)
+ activejob (= 5.2.0.alpha)
+ activemodel (= 5.2.0.alpha)
+ activerecord (= 5.2.0.alpha)
+ activesupport (= 5.2.0.alpha)
bundler (>= 1.3.0, < 2.0)
- railties (= 5.1.0.beta1)
+ railties (= 5.2.0.alpha)
sprockets-rails (>= 2.0.0)
- railties (5.1.0.beta1)
- actionpack (= 5.1.0.beta1)
- activesupport (= 5.1.0.beta1)
+ railties (5.2.0.alpha)
+ actionpack (= 5.2.0.alpha)
+ activesupport (= 5.2.0.alpha)
method_source
rake (>= 0.8.7)
thor (>= 0.18.1, < 2.0)
@@ -88,7 +94,6 @@ GEM
addressable (2.5.0)
public_suffix (~> 2.0, >= 2.0.2)
amq-protocol (2.1.0)
- arel (8.0.0)
ast (2.3.0)
backburner (1.3.1)
beaneater (~> 1.0)
@@ -159,7 +164,7 @@ GEM
http_parser.rb (>= 0.6.0)
em-socksify (0.3.1)
eventmachine (>= 1.0.0.beta.4)
- erubi (1.4.0)
+ erubi (1.6.0)
erubis (2.7.0)
event_emitter (0.2.5)
eventmachine (1.2.1)
@@ -371,6 +376,7 @@ DEPENDENCIES
activerecord-jdbcmysql-adapter (>= 1.3.0)
activerecord-jdbcpostgresql-adapter (>= 1.3.0)
activerecord-jdbcsqlite3-adapter (>= 1.3.0)
+ arel!
backburner
bcrypt (~> 3.1.11)
benchmark-ips
@@ -427,4 +433,4 @@ DEPENDENCIES
websocket-client-simple!
BUNDLED WITH
- 1.14.4
+ 1.14.5
diff --git a/RAILS_VERSION b/RAILS_VERSION
index d5d15fa148..d5ebf861d3 100644
--- a/RAILS_VERSION
+++ b/RAILS_VERSION
@@ -1 +1 @@
-5.1.0.beta1
+5.2.0.alpha
diff --git a/RELEASING_RAILS.md b/RELEASING_RAILS.md
index 10a8bca3b3..6e27d8ee5a 100644
--- a/RELEASING_RAILS.md
+++ b/RELEASING_RAILS.md
@@ -58,7 +58,7 @@ lists:
Implementors will love you and help you.
-### 3 Days before release
+## 3 Days before release
This is when you should release the release candidate. Here are your tasks
for today:
diff --git a/actioncable/CHANGELOG.md b/actioncable/CHANGELOG.md
index a0254fe323..d5bd58cfdb 100644
--- a/actioncable/CHANGELOG.md
+++ b/actioncable/CHANGELOG.md
@@ -1,45 +1 @@
-## Rails 5.1.0.beta1 (February 23, 2017) ##
-
-* Redis subscription adapters now support `channel_prefix` option in `cable.yml`
-
- Avoids channel name collisions when multiple apps use the same Redis server.
-
- *Chad Ingram*
-
-* Permit same-origin connections by default.
-
- Added new option `config.action_cable.allow_same_origin_as_host = false`
- to disable this behaviour.
-
- *Dávid Halász*, *Matthew Draper*
-
-* Prevent race where the client could receive and act upon a
- subscription confirmation before the channel's `subscribed` method
- completed.
-
- Fixes #25381.
-
- *Vladimir Dementyev*
-
-* Buffer now writes to WebSocket connections, to avoid blocking threads
- that could be doing more useful things.
-
- *Matthew Draper*, *Tinco Andringa*
-
-* Protect against concurrent writes to a WebSocket connection from
- multiple threads; the underlying OS write is not always threadsafe.
-
- *Tinco Andringa*
-
-* Add `ActiveSupport::Notifications` hook to `Broadcaster#broadcast`.
-
- *Matthew Wear*
-
-* Close hijacked socket when connection is shut down.
-
- Fixes #25613.
-
- *Tinco Andringa*
-
-
-Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/actioncable/CHANGELOG.md) for previous changes.
+Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/actioncable/CHANGELOG.md) for previous changes.
diff --git a/actioncable/README.md b/actioncable/README.md
index c55b7dc57b..e044f54b45 100644
--- a/actioncable/README.md
+++ b/actioncable/README.md
@@ -53,8 +53,8 @@ module ApplicationCable
private
def find_verified_user
- if current_user = User.find_by(id: cookies.signed[:user_id])
- current_user
+ if verified_user = User.find_by(id: cookies.signed[:user_id])
+ verified_user
else
reject_unauthorized_connection
end
diff --git a/actioncable/lib/action_cable/connection/authorization.rb b/actioncable/lib/action_cable/connection/authorization.rb
index 85df206445..989a67d6df 100644
--- a/actioncable/lib/action_cable/connection/authorization.rb
+++ b/actioncable/lib/action_cable/connection/authorization.rb
@@ -3,11 +3,11 @@ module ActionCable
module Authorization
class UnauthorizedError < StandardError; end
- private
- def reject_unauthorized_connection
- logger.error "An unauthorized connection attempt was rejected"
- raise UnauthorizedError
- end
+ # Closes the \WebSocket connection if it is open and returns a 404 "File not Found" response.
+ def reject_unauthorized_connection
+ logger.error "An unauthorized connection attempt was rejected"
+ raise UnauthorizedError
+ end
end
end
end
diff --git a/actioncable/lib/action_cable/gem_version.rb b/actioncable/lib/action_cable/gem_version.rb
index c09613a747..5d6f9af0bb 100644
--- a/actioncable/lib/action_cable/gem_version.rb
+++ b/actioncable/lib/action_cable/gem_version.rb
@@ -6,9 +6,9 @@ module ActionCable
module VERSION
MAJOR = 5
- MINOR = 1
+ MINOR = 2
TINY = 0
- PRE = "beta1"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/actioncable/package.json b/actioncable/package.json
index 69ae3519d9..acec1e2e9c 100644
--- a/actioncable/package.json
+++ b/actioncable/package.json
@@ -1,6 +1,6 @@
{
"name": "actioncable",
- "version": "5.1.0-beta1",
+ "version": "5.2.0-alpha",
"description": "WebSocket framework for Ruby on Rails.",
"main": "lib/assets/compiled/action_cable.js",
"files": [
diff --git a/actioncable/test/channel/stream_test.rb b/actioncable/test/channel/stream_test.rb
index 31dcde2e29..50fc7be30b 100644
--- a/actioncable/test/channel/stream_test.rb
+++ b/actioncable/test/channel/stream_test.rb
@@ -55,6 +55,8 @@ module ActionCable::StreamTests
channel = ChatChannel.new connection, "{id: 1}", id: 1
channel.subscribe_to_channel
+ wait_for_async
+
connection.expects(:pubsub).returns mock().tap { |m| m.expects(:unsubscribe) }
channel.unsubscribe_from_channel
end
@@ -67,6 +69,8 @@ module ActionCable::StreamTests
channel = SymbolChannel.new connection, ""
channel.subscribe_to_channel
+ wait_for_async
+
connection.expects(:pubsub).returns mock().tap { |m| m.expects(:unsubscribe) }
channel.unsubscribe_from_channel
end
diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md
index ee33450b45..e488d867de 100644
--- a/actionmailer/CHANGELOG.md
+++ b/actionmailer/CHANGELOG.md
@@ -1,33 +1 @@
-## Rails 5.1.0.beta1 (February 23, 2017) ##
-
-* Add `:args` to `process.action_mailer` event.
-
- *Yuji Yaginuma*
-
-* Add parameterized invocation of mailers as a way to share before filters and defaults between actions.
- See `ActionMailer::Parameterized` for a full example of the benefit.
-
- *DHH*
-
-* Allow lambdas to be used as lazy defaults in addition to procs.
-
- *DHH*
-
-* Mime type: allow to custom content type when setting body in headers
- and attachments.
-
- Example:
-
- def test_emails
- attachments["invoice.pdf"] = "This is test File content"
- mail(body: "Hello there", content_type: "text/html")
- end
-
- *Minh Quy*
-
-* Exception handling: use `rescue_from` to handle exceptions raised by
- mailer actions, by message delivery, and by deferred delivery jobs.
-
- *Jeremy Daer*
-
-Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/actionmailer/CHANGELOG.md) for previous changes.
+Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/actionmailer/CHANGELOG.md) for previous changes.
diff --git a/actionmailer/lib/action_mailer/gem_version.rb b/actionmailer/lib/action_mailer/gem_version.rb
index de2d71bd3e..f5594ef928 100644
--- a/actionmailer/lib/action_mailer/gem_version.rb
+++ b/actionmailer/lib/action_mailer/gem_version.rb
@@ -6,9 +6,9 @@ module ActionMailer
module VERSION
MAJOR = 5
- MINOR = 1
+ MINOR = 2
TINY = 0
- PRE = "beta1"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index d0662bdae2..c5b679207a 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,408 +1 @@
-* Fix `NameError` raised in `ActionController::Renderer#with_defaults`
-
- *Hiroyuki Ishii*
-
-* Added `#reverse_merge` and `#reverse_merge!` methods to `ActionController::Parameters`
-
- *Edouard Chin*, *Mitsutaka Mimura*
-
-* Fix malformed URLS when using `ApplicationController.renderer`
-
- The Rack environment variable `rack.url_scheme` was not being set so `scheme` was
- returning `nil`. This caused URLs to be malformed with the default settings.
- Fix this by setting `rack.url_scheme` when the environment is normalized.
-
- Fixes #28151.
-
- *George Vrettos*
-
-* Commit flash changes when using a redirect route.
-
- Fixes #27992.
-
- *Andrew White*
-
-
-## Rails 5.1.0.beta1 (February 23, 2017) ##
-
-* Prefer `remove_method` over `undef_method` when reloading routes
-
- When `undef_method` is used it prevents access to other implementations of that
- url helper in the ancestor chain so use `remove_method` instead to restore access.
-
- *Andrew White*
-
-* Add the `resolve` method to the routing DSL
-
- This new method allows customization of the polymorphic mapping of models:
-
- ``` ruby
- resource :basket
- resolve("Basket") { [:basket] }
- ```
-
- ``` erb
- <%= form_for @basket do |form| %>
- <!-- basket form -->
- <% end %>
- ```
-
- This generates the correct singular URL for the form instead of the default
- resources member url, e.g. `/basket` vs. `/basket/:id`.
-
- Fixes #1769.
-
- *Andrew White*
-
-* Add the `direct` method to the routing DSL
-
- This new method allows creation of custom url helpers, e.g:
-
- ``` ruby
- direct(:apple) { "http://www.apple.com" }
-
- >> apple_url
- => "http://www.apple.com"
- ```
-
- This has the advantage of being available everywhere url helpers are available
- unlike custom url helpers defined in helper modules, etc.
-
- *Andrew White*
-
-* Add `ActionDispatch::SystemTestCase` to Action Pack
-
- Adds Capybara integration directly into Rails through Action Pack!
-
- See PR [#26703](https://github.com/rails/rails/pull/26703)
-
- *Eileen M. Uchitelle*
-
-* Remove deprecated `.to_prepare`, `.to_cleanup`, `.prepare!` and `.cleanup!` from `ActionDispatch::Reloader`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `ActionDispatch::Callbacks.to_prepare` and `ActionDispatch::Callbacks.to_cleanup`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `ActionController::Metal.call`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `ActionController::Metal#env`.
-
- *Rafael Mendonça França*
-
-* Make `with_routing` test helper work when testing controllers inheriting from `ActionController::API`
-
- *Julia López*
-
-* Use accept header in integration tests with `as: :json`
-
- Instead of appending the `format` to the request path, Rails will figure
- out the format from the header instead.
-
- This allows devs to use `:as` on routes that don't have a format.
-
- Fixes #27144.
-
- *Kasper Timm Hansen*
-
-* Reset a new session directly after its creation in `ActionDispatch::IntegrationTest#open_session`.
-
- Fixes #22742.
-
- *Tawan Sierek*
-
-* Fixes incorrect output from `rails routes` when using singular resources.
-
- Fixes #26606.
-
- *Erick Reyna*
-
-* Fixes multiple calls to `logger.fatal` instead of a single call,
- for every line in an exception backtrace, when printing trace
- from `DebugExceptions` middleware.
-
- Fixes #26134.
-
- *Vipul A M*
-
-* Add support for arbitrary hashes in strong parameters:
-
- ```ruby
- params.permit(preferences: {})
- ```
-
- *Xavier Noria*
-
-* Add `ActionController::Parameters#merge!`, which behaves the same as `Hash#merge!`.
-
- *Yuji Yaginuma*
-
-* Allow keys not found in `RACK_KEY_TRANSLATION` for setting the environment when rendering
- arbitrary templates.
-
- *Sammy Larbi*
-
-* Remove deprecated support to non-keyword arguments in `ActionDispatch::IntegrationTest#process`,
- `#get`, `#post`, `#patch`, `#put`, `#delete`, and `#head`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `ActionDispatch::IntegrationTest#*_via_redirect`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `ActionDispatch::IntegrationTest#xml_http_request`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support for passing `:path` and route path as strings in `ActionDispatch::Routing::Mapper#match`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support for passing path as `nil` in `ActionDispatch::Routing::Mapper#match`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `cache_control` argument from `ActionDispatch::Static#initialize`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support to passing strings or symbols to the middleware stack.
-
- *Rafael Mendonça França*
-
-* Change HSTS subdomain to true.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `host` and `port` ssl options.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `const_error` argument in
- `ActionDispatch::Session::SessionRestoreError#initialize`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `#original_exception` in `ActionDispatch::Session::SessionRestoreError`.
-
- *Rafael Mendonça França*
-
-* Deprecate `ActionDispatch::ParamsParser::ParseError` in favor of
- `ActionDispatch::Http::Parameters::ParseError`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `ActionDispatch::ParamsParser`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `original_exception` and `message` arguments in
- `ActionDispatch::ParamsParser::ParseError#initialize`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `#original_exception` in `ActionDispatch::ParamsParser::ParseError`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated access to mime types through constants.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support to non-keyword arguments in `ActionController::TestCase#process`,
- `#get`, `#post`, `#patch`, `#put`, `#delete`, and `#head`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `xml_http_request` and `xhr` methods in `ActionController::TestCase`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated methods in `ActionController::Parameters`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support to comparing a `ActionController::Parameters`
- with a `Hash`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support to `:text` in `render`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support to `:nothing` in `render`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support to `:back` in `redirect_to`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support to passing status as option `head`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support to passing original exception to `ActionController::BadRequest`
- and the `ActionController::BadRequest#original_exception` method.
-
- *Rafael Mendonça França*
-
-* Remove deprecated methods `skip_action_callback`, `skip_filter`, `before_filter`,
- `prepend_before_filter`, `skip_before_filter`, `append_before_filter`, `around_filter`
- `prepend_around_filter`, `skip_around_filter`, `append_around_filter`, `after_filter`,
- `prepend_after_filter`, `skip_after_filter` and `append_after_filter`.
-
- *Rafael Mendonça França*
-
-* Show an "unmatched constraints" error when params fail to match constraints
- on a matched route, rather than a "missing keys" error.
-
- Fixes #26470.
-
- *Chris Carter*
-
-* Fix adding implicitly rendered template digests to ETags.
-
- Fixes a case when modifying an implicitly rendered template for a
- controller action using `fresh_when` or `stale?` would not result in a new
- `ETag` value.
-
- *Javan Makhmali*
-
-* Make `fixture_file_upload` work in integration tests.
-
- *Yuji Yaginuma*
-
-* Add `to_param` to `ActionController::Parameters` deprecations.
-
- In the future `ActionController::Parameters` are discouraged from being used
- in URLs without explicit whitelisting. Go through `to_h` to use `to_param`.
-
- *Kir Shatrov*
-
-* Fix nested multiple roots
-
- The PR #20940 enabled the use of multiple roots with different constraints
- at the top level but unfortunately didn't work when those roots were inside
- a namespace and also broke the use of root inside a namespace after a top
- level root was defined because the check for the existence of the named route
- used the global :root name and not the namespaced name.
-
- This is fixed by using the name_for_action method to expand the :root name to
- the full namespaced name. We can pass nil for the second argument as we're not
- dealing with resource definitions so don't need to handle the cases for edit
- and new routes.
-
- Fixes #26148.
-
- *Ryo Hashimoto*, *Andrew White*
-
-* Include the content of the flash in the auto-generated etag. This solves the following problem:
-
- 1. POST /messages
- 2. redirect_to messages_url, notice: 'Message was created'
- 3. GET /messages/1
- 4. GET /messages
-
- Step 4 would before still include the flash message, even though it's no longer relevant,
- because the etag cache was recorded with the flash in place and didn't change when it was gone.
-
- *DHH*
-
-* SSL: Changes redirect behavior for all non-GET and non-HEAD requests
- (like POST/PUT/PATCH etc) to `http://` resources to redirect to `https://`
- with a [307 status code](http://tools.ietf.org/html/rfc7231#section-6.4.7) instead of [301 status code](http://tools.ietf.org/html/rfc7231#section-6.4.2).
-
- 307 status code instructs the HTTP clients to preserve the original
- request method while redirecting. It has been part of HTTP RFC since
- 1999 and is implemented/recognized by most (if not all) user agents.
-
- # Before
- POST http://example.com/articles (i.e. ArticlesContoller#create)
- redirects to
- GET https://example.com/articles (i.e. ArticlesContoller#index)
-
- # After
- POST http://example.com/articles (i.e. ArticlesContoller#create)
- redirects to
- POST https://example.com/articles (i.e. ArticlesContoller#create)
-
- *Chirag Singhal*
-
-* Add `:as` option to `ActionController:TestCase#process` and related methods.
-
- Specifying `as: mime_type` allows the `CONTENT_TYPE` header to be specified
- in controller tests without manually doing this through `@request.headers['CONTENT_TYPE']`.
-
- *Everest Stefan Munro-Zeisberger*
-
-* Show cache hits and misses when rendering partials.
-
- Partials using the `cache` helper will show whether a render hit or missed
- the cache:
-
- ```
- Rendered messages/_message.html.erb in 1.2 ms [cache hit]
- Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss]
- ```
-
- This removes the need for the old fragment cache logging:
-
- ```
- Read fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/d0bdf2974e1ef6d31685c3b392ad0b74 (0.6ms)
- Rendered messages/_message.html.erb in 1.2 ms [cache hit]
- Write fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/3b4e249ac9d168c617e32e84b99218b5 (1.1ms)
- Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss]
- ```
-
- Though that full output can be reenabled with
- `config.action_controller.enable_fragment_cache_logging = true`.
-
- *Stan Lo*
-
-* Don't override the `Accept` header in integration tests when called with `xhr: true`.
-
- Fixes #25859.
-
- *David Chen*
-
-* Fix `defaults` option for root route.
-
- A regression from some refactoring for the 5.0 release, this change
- fixes the use of `defaults` (default parameters) in the `root` routing method.
-
- *Chris Arcand*
-
-* Check `request.path_parameters` encoding at the point they're set.
-
- Check for any non-UTF8 characters in path parameters at the point they're
- set in `env`. Previously they were checked for when used to get a controller
- class, but this meant routes that went directly to a Rack app, or skipped
- controller instantiation for some other reason, had to defend against
- non-UTF8 characters themselves.
-
- *Grey Baker*
-
-* Don't raise `ActionController::UnknownHttpMethod` from `ActionDispatch::Static`.
-
- Pass `Rack::Request` objects to `ActionDispatch::FileHandler` to avoid it
- raising `ActionController::UnknownHttpMethod`. If an unknown method is
- passed, it should pass exception higher in the stack instead, once we've had a
- chance to define exception handling behaviour.
-
- *Grey Baker*
-
-* Handle `Rack::QueryParser` errors in `ActionDispatch::ExceptionWrapper`.
-
- Updated `ActionDispatch::ExceptionWrapper` to handle the Rack 2.0 namespace
- for `ParameterTypeError` and `InvalidParameterError` errors.
-
- *Grey Baker*
-
-Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/actionpack/CHANGELOG.md) for previous changes.
+Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/actionpack/CHANGELOG.md) for previous changes.
diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb
index 7b4c7b923e..96bd548268 100644
--- a/actionpack/lib/action_controller/metal/mime_responds.rb
+++ b/actionpack/lib/action_controller/metal/mime_responds.rb
@@ -182,7 +182,7 @@ module ActionController #:nodoc:
# request.variant = [:tablet, :phone]
#
# This will work similarly to formats and MIME types negotiation. If there
- # is no +:tablet+ variant declared, +:phone+ variant will be picked:
+ # is no +:tablet+ variant declared, the +:phone+ variant will be used:
#
# respond_to do |format|
# format.html.none
diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
index c4fe3a5c09..19f89edbc1 100644
--- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb
+++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb
@@ -135,9 +135,7 @@ module ActionDispatch
}
end
- # Receives an array of mimes and return the first user sent mime that
- # matches the order array.
- #
+ # Returns the first MIME type that matches the provided array of MIME types.
def negotiate_mime(order)
formats.each do |priority|
if priority == Mime::ALL
diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb
index 1583a8f87f..0cf010f59e 100644
--- a/actionpack/lib/action_dispatch/http/mime_type.rb
+++ b/actionpack/lib/action_dispatch/http/mime_type.rb
@@ -46,7 +46,7 @@ module Mime
end
end
- # Encapsulates the notion of a mime type. Can be used at render time, for example, with:
+ # Encapsulates the notion of a MIME type. Can be used at render time, for example, with:
#
# class PostsController < ActionController::Base
# def show
@@ -64,7 +64,7 @@ module Mime
@register_callbacks = []
- # A simple helper class used in parsing the accept header
+ # A simple helper class used in parsing the accept header.
class AcceptItem #:nodoc:
attr_accessor :index, :name, :q
alias :to_s :name
@@ -72,7 +72,7 @@ module Mime
def initialize(index, name, q = nil)
@index = index
@name = name
- q ||= 0.0 if @name == "*/*".freeze # default wildcard match to end of list
+ q ||= 0.0 if @name == "*/*".freeze # Default wildcard match to end of list.
@q = ((q || 1.0).to_f * 100).to_i
end
@@ -90,22 +90,22 @@ module Mime
text_xml_idx = find_item_by_name list, "text/xml"
app_xml_idx = find_item_by_name list, Mime[:xml].to_s
- # Take care of the broken text/xml entry by renaming or deleting it
+ # Take care of the broken text/xml entry by renaming or deleting it.
if text_xml_idx && app_xml_idx
app_xml = list[app_xml_idx]
text_xml = list[text_xml_idx]
- app_xml.q = [text_xml.q, app_xml.q].max # set the q value to the max of the two
- if app_xml_idx > text_xml_idx # make sure app_xml is ahead of text_xml in the list
+ app_xml.q = [text_xml.q, app_xml.q].max # Set the q value to the max of the two.
+ if app_xml_idx > text_xml_idx # Make sure app_xml is ahead of text_xml in the list.
list[app_xml_idx], list[text_xml_idx] = text_xml, app_xml
app_xml_idx, text_xml_idx = text_xml_idx, app_xml_idx
end
- list.delete_at(text_xml_idx) # delete text_xml from the list
+ list.delete_at(text_xml_idx) # Delete text_xml from the list.
elsif text_xml_idx
list[text_xml_idx].name = Mime[:xml].to_s
end
- # Look for more specific XML-based types and sort them ahead of app/xml
+ # Look for more specific XML-based types and sort them ahead of app/xml.
if app_xml_idx
app_xml = list[app_xml_idx]
idx = app_xml_idx
@@ -147,7 +147,7 @@ module Mime
EXTENSION_LOOKUP[extension.to_s]
end
- # Registers an alias that's not used on mime type lookup, but can be referenced directly. Especially useful for
+ # Registers an alias that's not used on MIME type lookup, but can be referenced directly. Especially useful for
# rendering different HTML versions depending on the user agent, like an iPhone.
def register_alias(string, symbol, extension_synonyms = [])
register(string, symbol, [], extension_synonyms, true)
diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb
index 8f21eca440..79a2ef965b 100644
--- a/actionpack/lib/action_dispatch/http/parameters.rb
+++ b/actionpack/lib/action_dispatch/http/parameters.rb
@@ -13,7 +13,7 @@ module ActionDispatch
}
# Raised when raw data from the request cannot be parsed by the parser
- # defined for request's content mime type.
+ # defined for request's content MIME type.
class ParseError < StandardError
def initialize
super($!.message)
@@ -30,9 +30,9 @@ module ActionDispatch
end
module ClassMethods
- # Configure the parameter parser for a given mime type.
+ # Configure the parameter parser for a given MIME type.
#
- # It accepts a hash where the key is the symbol of the mime type
+ # It accepts a hash where the key is the symbol of the MIME type
# and the value is a proc.
#
# original_parsers = ActionDispatch::Request.parameter_parsers
@@ -100,7 +100,7 @@ module ActionDispatch
begin
strategy.call(raw_post)
- rescue # JSON or Ruby code block errors
+ rescue # JSON or Ruby code block errors.
my_logger = logger || ActiveSupport::Logger.new($stderr)
my_logger.debug "Error occurred while parsing request parameters.\nContents:\n\n#{raw_post}"
@@ -115,6 +115,7 @@ module ActionDispatch
end
module ParamsParser
- ParseError = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("ActionDispatch::ParamsParser::ParseError", "ActionDispatch::Http::Parameters::ParseError")
+ include ActiveSupport::Deprecation::DeprecatedConstantAccessor
+ deprecate_constant "ParseError", "ActionDispatch::Http::Parameters::ParseError"
end
end
diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb
index 19fa42ce12..6d42404a98 100644
--- a/actionpack/lib/action_dispatch/http/request.rb
+++ b/actionpack/lib/action_dispatch/http/request.rb
@@ -114,7 +114,7 @@ module ActionDispatch
HTTP_METHOD_LOOKUP = {}
- # Populate the HTTP method lookup cache
+ # Populate the HTTP method lookup cache.
HTTP_METHODS.each { |method|
HTTP_METHOD_LOOKUP[method] = method.underscore.to_sym
}
@@ -165,12 +165,12 @@ module ActionDispatch
def show_exceptions? # :nodoc:
# We're treating `nil` as "unset", and we want the default setting to be
- # `true`. This logic should be extracted to `env_config` and calculated
+ # `true`. This logic should be extracted to `env_config` and calculated
# once.
!(get_header("action_dispatch.show_exceptions".freeze) == false)
end
- # Returns a symbol form of the #request_method
+ # Returns a symbol form of the #request_method.
def request_method_symbol
HTTP_METHOD_LOOKUP[request_method]
end
@@ -182,7 +182,7 @@ module ActionDispatch
@method ||= check_method(get_header("rack.methodoverride.original_method") || get_header("REQUEST_METHOD"))
end
- # Returns a symbol form of the #method
+ # Returns a symbol form of the #method.
def method_symbol
HTTP_METHOD_LOOKUP[method]
end
@@ -267,7 +267,7 @@ module ActionDispatch
# (which sets the action_dispatch.request_id environment variable).
#
# This unique ID is useful for tracing a request from end-to-end as part of logging or debugging.
- # This relies on the rack variable set by the ActionDispatch::RequestId middleware.
+ # This relies on the Rack variable set by the ActionDispatch::RequestId middleware.
def request_id
get_header ACTION_DISPATCH_REQUEST_ID
end
@@ -339,7 +339,7 @@ module ActionDispatch
Session::Options.set self, options
end
- # Override Rack's GET method to support indifferent access
+ # Override Rack's GET method to support indifferent access.
def GET
fetch_header("action_dispatch.request.query_parameters") do |k|
rack_query_params = super || {}
@@ -352,7 +352,7 @@ module ActionDispatch
end
alias :query_parameters :GET
- # Override Rack's POST method to support indifferent access
+ # Override Rack's POST method to support indifferent access.
def POST
fetch_header("action_dispatch.request.request_parameters") do
pr = parse_formatted_parameters(params_parsers) do |params|
diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb
index dc159596c4..2ee52eeb48 100644
--- a/actionpack/lib/action_dispatch/http/response.rb
+++ b/actionpack/lib/action_dispatch/http/response.rb
@@ -85,7 +85,7 @@ module ActionDispatch # :nodoc:
cattr_accessor(:default_headers)
include Rack::Response::Helpers
- # Aliasing these off because AD::Http::Cache::Response defines them
+ # Aliasing these off because AD::Http::Cache::Response defines them.
alias :_cache_control :cache_control
alias :_cache_control= :cache_control=
@@ -142,7 +142,7 @@ module ActionDispatch # :nodoc:
private
def each_chunk(&block)
- @buf.each(&block) # extract into own method
+ @buf.each(&block)
end
end
diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb
index a6937d54ff..b6be48a48b 100644
--- a/actionpack/lib/action_dispatch/http/url.rb
+++ b/actionpack/lib/action_dispatch/http/url.rb
@@ -101,10 +101,8 @@ module ActionDispatch
end
def add_trailing_slash(path)
- # includes querysting
if path.include?("?")
path.sub!(/\?/, '/\&')
- # does not have a .format
elsif !path.include?(".")
path.sub!(/[^\/]\z|\A\z/, '\&/')
end
diff --git a/actionpack/lib/action_dispatch/journey/formatter.rb b/actionpack/lib/action_dispatch/journey/formatter.rb
index f3b8e82d32..326f4e52f9 100644
--- a/actionpack/lib/action_dispatch/journey/formatter.rb
+++ b/actionpack/lib/action_dispatch/journey/formatter.rb
@@ -15,7 +15,7 @@ module ActionDispatch
def generate(name, options, path_parameters, parameterize = nil)
constraints = path_parameters.merge(options)
- missing_keys = nil # need for variable scope
+ missing_keys = nil
match_route(name, constraints) do |route|
parameterized_parts = extract_parameterized_parts(route, options, path_parameters, parameterize)
diff --git a/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb b/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb
index beb9f1ef3b..e1ac2c873e 100644
--- a/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb
+++ b/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb
@@ -109,7 +109,6 @@ module ActionDispatch
svg = to_svg
javascripts = [states, fsm_js]
- # Annoying hack warnings
fun_routes = fun_routes
stylesheets = stylesheets
svg = svg
diff --git a/actionpack/lib/action_dispatch/journey/route.rb b/actionpack/lib/action_dispatch/journey/route.rb
index 927fd369c4..7bc15aa6b3 100644
--- a/actionpack/lib/action_dispatch/journey/route.rb
+++ b/actionpack/lib/action_dispatch/journey/route.rb
@@ -89,8 +89,15 @@ module ActionDispatch
end
end
+ # Needed for `rails routes`. Picks up succinctly defined requirements
+ # for a route, for example route
+ #
+ # get 'photo/:id', :controller => 'photos', :action => 'show',
+ # :id => /[A-Z]\d{5}/
+ #
+ # will have {:controller=>"photos", :action=>"show", :id=>/[A-Z]\d{5}/}
+ # as requirements.
def requirements
- # needed for rails `rails routes`
@defaults.merge(path.requirements).delete_if { |_, v|
/.+?/ == v
}
diff --git a/actionpack/lib/action_dispatch/journey/router/utils.rb b/actionpack/lib/action_dispatch/journey/router/utils.rb
index d641642338..ffcd875b4d 100644
--- a/actionpack/lib/action_dispatch/journey/router/utils.rb
+++ b/actionpack/lib/action_dispatch/journey/router/utils.rb
@@ -5,7 +5,7 @@ module ActionDispatch
# Normalizes URI path.
#
# Strips off trailing slash and ensures there is a leading slash.
- # Also converts downcase url encoded string to uppercase.
+ # Also converts downcase URL encoded string to uppercase.
#
# normalize_path("/foo") # => "/foo"
# normalize_path("/foo/") # => "/foo"
diff --git a/actionpack/lib/action_dispatch/journey/visitors.rb b/actionpack/lib/action_dispatch/journey/visitors.rb
index 1c50192867..335797f4b9 100644
--- a/actionpack/lib/action_dispatch/journey/visitors.rb
+++ b/actionpack/lib/action_dispatch/journey/visitors.rb
@@ -154,7 +154,7 @@ module ActionDispatch
end
end
- # Loop through the requirements AST
+ # Loop through the requirements AST.
class Each < FunctionalVisitor # :nodoc:
def visit(node, block)
block.call(node)
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index c61cb3fd68..e565c03a8a 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -160,7 +160,7 @@ module ActionDispatch
# Raised when storing more than 4K of session data.
CookieOverflow = Class.new StandardError
- # Include in a cookie jar to allow chaining, e.g. cookies.permanent.signed
+ # Include in a cookie jar to allow chaining, e.g. cookies.permanent.signed.
module ChainedCookieJars
# Returns a jar that'll automatically set the assigned cookies to have an expiration date 20 years from now. Example:
#
@@ -345,16 +345,16 @@ module ActionDispatch
options[:path] ||= "/"
if options[:domain] == :all || options[:domain] == "all"
- # if there is a provided tld length then we use it otherwise default domain regexp
+ # If there is a provided tld length then we use it otherwise default domain regexp.
domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP
- # if host is not ip and matches domain regexp
+ # If host is not ip and matches domain regexp.
# (ip confirms to domain regexp so we explicitly check for ip)
options[:domain] = if (request.host !~ /^[\d.]+$/) && (request.host =~ domain_regexp)
".#{$&}"
end
elsif options[:domain].is_a? Array
- # if host matches one of the supplied domains without a dot in front of it
+ # If host matches one of the supplied domains without a dot in front of it.
options[:domain] = options[:domain].find { |domain| request.host.include? domain.sub(/^\./, "") }
end
end
@@ -404,7 +404,7 @@ module ActionDispatch
@delete_cookies[name.to_s] == options
end
- # Removes all cookies on the client machine by calling <tt>delete</tt> for each cookie
+ # Removes all cookies on the client machine by calling <tt>delete</tt> for each cookie.
def clear(options = {})
@cookies.each_key { |k| delete(k, options) }
end
diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb
index cbe2f4be4d..6b29ce63ba 100644
--- a/actionpack/lib/action_dispatch/middleware/flash.rb
+++ b/actionpack/lib/action_dispatch/middleware/flash.rb
@@ -65,7 +65,7 @@ module ActionDispatch
self.flash = flash_hash.dup
end
- if (!session.respond_to?(:loaded?) || session.loaded?) && # (reset_session uses {}, which doesn't implement #loaded?)
+ if (!session.respond_to?(:loaded?) || session.loaded?) && # reset_session uses {}, which doesn't implement #loaded?
session.key?("flash") && session["flash"].nil?
session.delete("flash")
end
diff --git a/actionpack/lib/action_dispatch/middleware/remote_ip.rb b/actionpack/lib/action_dispatch/middleware/remote_ip.rb
index 8bae5bfeff..53d5a4918c 100644
--- a/actionpack/lib/action_dispatch/middleware/remote_ip.rb
+++ b/actionpack/lib/action_dispatch/middleware/remote_ip.rb
@@ -157,13 +157,13 @@ module ActionDispatch
def ips_from(header) # :doc:
return [] unless header
- # Split the comma-separated list into an array of strings
+ # Split the comma-separated list into an array of strings.
ips = header.strip.split(/[,\s]+/)
ips.select do |ip|
begin
- # Only return IPs that are valid according to the IPAddr#new method
+ # Only return IPs that are valid according to the IPAddr#new method.
range = IPAddr.new(ip).to_range
- # we want to make sure nobody is sneaking a netmask in
+ # We want to make sure nobody is sneaking a netmask in.
range.begin == range.end
rescue ArgumentError
nil
diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
index d9f018c8ac..21ccf5a097 100644
--- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
+++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb
@@ -53,7 +53,7 @@ module ActionDispatch
rescue ArgumentError => argument_error
if argument_error.message =~ %r{undefined class/module ([\w:]*\w)}
begin
- # Note that the regexp does not allow $1 to end with a ':'
+ # Note that the regexp does not allow $1 to end with a ':'.
$1.constantize
rescue LoadError, NameError
raise ActionDispatch::Session::SessionRestoreError
diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
index 90f26a1c33..5a99714ec2 100644
--- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
+++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb
@@ -8,7 +8,7 @@ module ActionDispatch
# The exceptions app should be passed as parameter on initialization
# of ShowExceptions. Every time there is an exception, ShowExceptions will
# store the exception in env["action_dispatch.exception"], rewrite the
- # PATH_INFO to the exception status code and call the rack app.
+ # PATH_INFO to the exception status code and call the Rack app.
#
# If the application returns a "X-Cascade" pass response, this middleware
# will send an empty response as result with the correct status code.
diff --git a/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb b/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
index 429ea7057c..2d21ae63f5 100644
--- a/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
+++ b/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb
@@ -60,7 +60,7 @@
<%= link_to "Path", "#", 'data-route-helper' => '_path',
title: "Returns a relative path (without the http or domain)" %> /
<%= link_to "Url", "#", 'data-route-helper' => '_url',
- title: "Returns an absolute url (with the http and domain)" %>
+ title: "Returns an absolute URL (with the http and domain)" %>
</th>
<th><%# HTTP Verb %>
</th>
@@ -93,7 +93,7 @@
}
}
- // get JSON from url and invoke callback with result
+ // get JSON from URL and invoke callback with result
function getJSON(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
diff --git a/actionpack/lib/action_dispatch/request/session.rb b/actionpack/lib/action_dispatch/request/session.rb
index a2a80f39fc..74ba6466cf 100644
--- a/actionpack/lib/action_dispatch/request/session.rb
+++ b/actionpack/lib/action_dispatch/request/session.rb
@@ -7,10 +7,10 @@ module ActionDispatch
ENV_SESSION_KEY = Rack::RACK_SESSION # :nodoc:
ENV_SESSION_OPTIONS_KEY = Rack::RACK_SESSION_OPTIONS # :nodoc:
- # Singleton object used to determine if an optional param wasn't specified
+ # Singleton object used to determine if an optional param wasn't specified.
Unspecified = Object.new
- # Creates a session hash, merging the properties of the previous session if any
+ # Creates a session hash, merging the properties of the previous session if any.
def self.create(store, req, default_options)
session_was = find req
session = Request::Session.new(store, req)
@@ -63,7 +63,7 @@ module ActionDispatch
@req = req
@delegate = {}
@loaded = false
- @exists = nil # we haven't checked yet
+ @exists = nil # We haven't checked yet.
end
def id
@@ -79,7 +79,7 @@ module ActionDispatch
options = self.options || {}
@by.send(:delete_session, @req, options.id(@req), options)
- # Load the new sid to be written with the response
+ # Load the new sid to be written with the response.
@loaded = false
load_for_write!
end
diff --git a/actionpack/lib/action_dispatch/request/utils.rb b/actionpack/lib/action_dispatch/request/utils.rb
index 01bc871e5f..3615e4b1d8 100644
--- a/actionpack/lib/action_dispatch/request/utils.rb
+++ b/actionpack/lib/action_dispatch/request/utils.rb
@@ -40,7 +40,6 @@ module ActionDispatch
class ParamEncoder # :nodoc:
# Convert nested Hash to HashWithIndifferentAccess.
- #
def self.normalize_encode_params(params)
case params
when Array
@@ -63,7 +62,7 @@ module ActionDispatch
end
end
- # Remove nils from the params hash
+ # Remove nils from the params hash.
class NoNilParamEncoder < ParamEncoder # :nodoc:
def self.handle_array(params)
list = super
diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb
index c554ce98bc..60d4789a63 100644
--- a/actionpack/lib/action_dispatch/routing.rb
+++ b/actionpack/lib/action_dispatch/routing.rb
@@ -120,7 +120,7 @@ module ActionDispatch
# controller :blog do
# get 'blog/show' => :list
# get 'blog/delete' => :delete
- # get 'blog/edit' => :edit
+ # get 'blog/edit' => :edit
# end
#
# # provides named routes for show, delete, and edit
diff --git a/actionpack/lib/action_dispatch/routing/inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb
index b91ffb8419..9aa4b92df2 100644
--- a/actionpack/lib/action_dispatch/routing/inspector.rb
+++ b/actionpack/lib/action_dispatch/routing/inspector.rb
@@ -196,7 +196,7 @@ module ActionDispatch
@buffer << @view.render(partial: "routes/route", collection: routes)
end
- # the header is part of the HTML page, so we don't construct it here.
+ # The header is part of the HTML page, so we don't construct it here.
def header(routes)
end
diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb
index dea6c4482e..8ad17504ae 100644
--- a/actionpack/lib/action_dispatch/routing/mapper.rb
+++ b/actionpack/lib/action_dispatch/routing/mapper.rb
@@ -17,9 +17,9 @@ module ActionDispatch
CALL = ->(app, req) { app.call req.env }
def initialize(app, constraints, strategy)
- # Unwrap Constraints objects. I don't actually think it's possible
+ # Unwrap Constraints objects. I don't actually think it's possible
# to pass a Constraints object to this constructor, but there were
- # multiple places that kept testing children of this object. I
+ # multiple places that kept testing children of this object. I
# *think* they were just being defensive, but I have no idea.
if app.is_a?(self.class)
constraints += app.constraints
@@ -218,7 +218,7 @@ module ActionDispatch
private
def add_wildcard_options(options, formatted, path_ast)
# Add a constraint for wildcard route to make it non-greedy and match the
- # optional format part of the route by default
+ # optional format part of the route by default.
if formatted != false
path_ast.grep(Journey::Nodes::Star).each_with_object({}) { |node, hash|
hash[node.name.to_sym] ||= /.+?/
@@ -396,7 +396,7 @@ module ActionDispatch
end
module Base
- # Matches a url pattern to one or more routes.
+ # Matches a URL pattern to one or more routes.
#
# You should not use the +match+ method in your router
# without specifying an HTTP method.
@@ -406,7 +406,7 @@ module ActionDispatch
# # sets :controller, :action and :id in params
# match ':controller/:action/:id', via: [:get, :post]
#
- # Note that +:controller+, +:action+ and +:id+ are interpreted as url
+ # Note that +:controller+, +:action+ and +:id+ are interpreted as URL
# query parameters and thus available through +params+ in an action.
#
# If you want to expose your action to GET, use +get+ in the router:
@@ -455,7 +455,7 @@ module ActionDispatch
#
# === Options
#
- # Any options not seen here are passed on as params with the url.
+ # Any options not seen here are passed on as params with the URL.
#
# [:controller]
# The route's controller.
@@ -660,7 +660,7 @@ module ActionDispatch
else
prefix_options = options.slice(*_route.segment_keys)
prefix_options[:relative_url_root] = "".freeze
- # we must actually delete prefix segment keys to avoid passing them to next url_for
+ # We must actually delete prefix segment keys to avoid passing them to next url_for.
_route.segment_keys.each { |k| options.delete(k) }
_routes.url_helpers.send("#{name}_path", prefix_options)
end
@@ -1238,7 +1238,7 @@ module ActionDispatch
#
# resource :profile
#
- # creates six different routes in your application, all mapping to
+ # This creates six different routes in your application, all mapping to
# the +Profiles+ controller (note that the controller is named after
# the plural):
#
@@ -1323,14 +1323,14 @@ module ActionDispatch
#
# resources :posts, path_names: { new: "brand_new" }
#
- # The above example will now change /posts/new to /posts/brand_new
+ # The above example will now change /posts/new to /posts/brand_new.
#
# [:path]
# Allows you to change the path prefix for the resource.
#
# resources :posts, path: 'postings'
#
- # The resource and all segments will now route to /postings instead of /posts
+ # The resource and all segments will now route to /postings instead of /posts.
#
# [:only]
# Only generate routes for the given actions.
@@ -1525,7 +1525,7 @@ module ActionDispatch
end
end
- # See ActionDispatch::Routing::Mapper::Scoping#namespace
+ # See ActionDispatch::Routing::Mapper::Scoping#namespace.
def namespace(path, options = {})
if resource_scope?
nested { super }
@@ -1545,7 +1545,7 @@ module ActionDispatch
!parent_resource.singleton? && @scope[:shallow]
end
- # Matches a url pattern to one or more routes.
+ # Matches a URL pattern to one or more routes.
# For more information, see match[rdoc-ref:Base#match].
#
# match 'path' => 'controller#action', via: patch
@@ -2003,7 +2003,7 @@ module ActionDispatch
# concerns :commentable
# end
#
- # concerns also work in any routes helper that you want to use:
+ # Concerns also work in any routes helper that you want to use:
#
# namespace :posts do
# concerns :commentable
@@ -2038,33 +2038,33 @@ module ActionDispatch
# end
#
# The return value from the block passed to `direct` must be a valid set of
- # arguments for `url_for` which will actually build the url string. This can
+ # arguments for `url_for` which will actually build the URL string. This can
# be one of the following:
#
- # * A string, which is treated as a generated url
+ # * A string, which is treated as a generated URL
# * A hash, e.g. { controller: "pages", action: "index" }
# * An array, which is passed to `polymorphic_url`
# * An Active Model instance
# * An Active Model class
#
- # NOTE: Other url helpers can be called in the block but be careful not to invoke
- # your custom url helper again otherwise it will result in a stack overflow error
+ # NOTE: Other URL helpers can be called in the block but be careful not to invoke
+ # your custom URL helper again otherwise it will result in a stack overflow error.
#
# You can also specify default options that will be passed through to
- # your url helper definition, e.g:
+ # your URL helper definition, e.g:
#
# direct :browse, page: 1, size: 10 do |options|
# [ :products, options.merge(params.permit(:page, :size).to_h.symbolize_keys) ]
# end
#
# In this instance the `params` object comes from the context in which the the
- # block is executed, e.g. generating a url inside a controller action or a view.
+ # block is executed, e.g. generating a URL inside a controller action or a view.
# If the block is executed where there isn't a params object such as this:
#
# Rails.application.routes.url_helpers.browse_path
#
# then it will raise a `NameError`. Because of this you need to be aware of the
- # context in which you will use your custom url helper when defining it.
+ # context in which you will use your custom URL helper when defining it.
#
# NOTE: The `direct` method can't be used inside of a scope block such as
# `namespace` or `scope` and will raise an error if it detects that it is.
@@ -2076,7 +2076,7 @@ module ActionDispatch
@set.add_url_helper(name, options, &block)
end
- # Define custom polymorphic mappings of models to urls. This alters the
+ # Define custom polymorphic mappings of models to URLs. This alters the
# behavior of `polymorphic_url` and consequently the behavior of
# `link_to` and `form_for` when passed a model instance, e.g:
#
@@ -2089,7 +2089,7 @@ module ActionDispatch
# This will now generate "/basket" when a `Basket` instance is passed to
# `link_to` or `form_for` instead of the standard "/baskets/:id".
#
- # NOTE: This custom behavior only applies to simple polymorphic urls where
+ # NOTE: This custom behavior only applies to simple polymorphic URLs where
# a single model instance is passed and not more complicated forms, e.g:
#
# # config/routes.rb
@@ -2105,7 +2105,7 @@ module ActionDispatch
# link_to "Profile", [:admin, @current_user]
#
# The first `link_to` will generate "/profile" but the second will generate
- # the standard polymorphic url of "/admin/users/1".
+ # the standard polymorphic URL of "/admin/users/1".
#
# You can pass options to a polymorphic mapping - the arity for the block
# needs to be two as the instance is passed as the first argument, e.g:
@@ -2114,9 +2114,9 @@ module ActionDispatch
# [:basket, options]
# end
#
- # This generates the url "/basket#items" because when the last item in an
+ # This generates the URL "/basket#items" because when the last item in an
# array passed to `polymorphic_url` is a hash then it's treated as options
- # to the url helper that gets called.
+ # to the URL helper that gets called.
#
# NOTE: The `resolve` method can't be used inside of a scope block such as
# `namespace` or `scope` and will raise an error if it detects that it is.
diff --git a/actionpack/lib/action_dispatch/routing/redirection.rb b/actionpack/lib/action_dispatch/routing/redirection.rb
index e8f47b8640..3bcb341758 100644
--- a/actionpack/lib/action_dispatch/routing/redirection.rb
+++ b/actionpack/lib/action_dispatch/routing/redirection.rb
@@ -146,7 +146,7 @@ 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
+ # 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.
#
@@ -165,7 +165,7 @@ module ActionDispatch
# Note that the +do end+ syntax for the redirect block wouldn't work, as Ruby would pass
# the block to +get+ instead of +redirect+. Use <tt>{ ... }</tt> instead.
#
- # The options version of redirect allows you to supply only the parts of the url which need
+ # The options version of redirect allows you to supply only the parts of the URL which need
# to change, it also supports interpolation of the path similar to the first example.
#
# get 'stores/:name', to: redirect(subdomain: 'stores', path: '/%{name}')
diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb
index 7034eff36d..129e90037e 100644
--- a/actionpack/lib/action_dispatch/routing/route_set.rb
+++ b/actionpack/lib/action_dispatch/routing/route_set.rb
@@ -295,7 +295,7 @@ module ActionDispatch
end
private
- # Create a url helper allowing ordered parameters to be associated
+ # Create a URL helper allowing ordered parameters to be associated
# with corresponding dynamic segments, so you can do:
#
# foo_url(bar, baz, bang)
diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb
index 4a23e1c8b6..008216cc80 100644
--- a/actionpack/lib/action_dispatch/routing/url_for.rb
+++ b/actionpack/lib/action_dispatch/routing/url_for.rb
@@ -113,10 +113,10 @@ module ActionDispatch
default_url_options
end
- # Generate a url based on the options provided, default_url_options and the
+ # Generate a URL based on the options provided, default_url_options and the
# routes defined in routes.rb. The following options are supported:
#
- # * <tt>:only_path</tt> - If true, the relative url is returned. Defaults to +false+.
+ # * <tt>:only_path</tt> - If true, the relative URL is returned. Defaults to +false+.
# * <tt>:protocol</tt> - The protocol to connect to. Defaults to 'http'.
# * <tt>:host</tt> - Specifies the host the link should be targeted at.
# If <tt>:only_path</tt> is false, this option must be
diff --git a/actionpack/lib/action_dispatch/system_test_case.rb b/actionpack/lib/action_dispatch/system_test_case.rb
index f908607e50..9cc3d0757f 100644
--- a/actionpack/lib/action_dispatch/system_test_case.rb
+++ b/actionpack/lib/action_dispatch/system_test_case.rb
@@ -49,7 +49,7 @@ module ActionDispatch
# By default, <tt>ActionDispatch::SystemTestCase</tt> is driven by the
# Selenium driver, with the Chrome browser, and a browser size of 1400x1400.
#
- # Changing the driver configuration options are easy. Let's say you want to use
+ # Changing the driver configuration options is easy. Let's say you want to use
# the Firefox browser instead of Chrome. In your +application_system_test_case.rb+
# file add the following:
#
diff --git a/actionpack/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb b/actionpack/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb
index 3078e035a3..859d68e475 100644
--- a/actionpack/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb
+++ b/actionpack/lib/action_dispatch/system_testing/test_helpers/screenshot_helper.rb
@@ -1,7 +1,7 @@
module ActionDispatch
module SystemTesting
module TestHelpers
- # Screenshot helper for system testing
+ # Screenshot helper for system testing.
module ScreenshotHelper
# Takes a screenshot of the current page in the browser.
#
diff --git a/actionpack/lib/action_dispatch/testing/assertions/response.rb b/actionpack/lib/action_dispatch/testing/assertions/response.rb
index 817737341c..1baf979ac9 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/response.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/response.rb
@@ -45,7 +45,7 @@ module ActionDispatch
# # Asserts that the redirection was to the named route login_url
# assert_redirected_to login_url
#
- # # Asserts that the redirection was to the url for @customer
+ # # Asserts that the redirection was to the URL for @customer
# assert_redirected_to @customer
#
# # Asserts that the redirection matches the regular expression
diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
index 37c1ca02b6..8645df4370 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb
@@ -18,8 +18,8 @@ module ActionDispatch
# assert_recognizes({controller: 'items', action: 'create'}, {path: 'items', method: :post})
#
# You can also pass in +extras+ with a hash containing URL parameters that would normally be in the query string. This can be used
- # to assert that values in the query string will end up in the params hash correctly. To test query strings you must use the
- # extras argument, appending the query string on the path directly will not work. For example:
+ # to assert that values in the query string will end up in the params hash correctly. To test query strings you must use the extras
+ # argument because appending the query string on the path directly will not work. For example:
#
# # Asserts that a path of '/items/list/1?view=print' returns the correct options
# assert_recognizes({controller: 'items', action: 'list', id: '1', view: 'print'}, 'items/list/1', { view: "print" })
@@ -132,8 +132,7 @@ module ActionDispatch
end
# A helper to make it easier to test different route configurations.
- # This method temporarily replaces @routes
- # with a new RouteSet instance.
+ # This method temporarily replaces @routes with a new RouteSet instance.
#
# The new instance is yielded to the passed block. Typically the block
# will create some routes using <tt>set.draw { match ... }</tt>:
@@ -186,7 +185,6 @@ module ActionDispatch
method = :get
end
- # Assume given controller
request = ActionController::TestRequest.create @controller.class
if path =~ %r{://}
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index b46a97413a..2e2db98ad6 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -246,7 +246,7 @@ module ActionDispatch
wrapped_headers["HTTP_ACCEPT"] ||= [Mime[:js], Mime[:html], Mime[:xml], "text/xml", "*/*"].join(", ")
end
- # this modifies the passed request_env directly
+ # This modifies the passed request_env directly.
if wrapped_headers.present?
Http::Headers.from_hash(request_env).merge!(wrapped_headers)
end
@@ -257,7 +257,7 @@ module ActionDispatch
session = Rack::Test::Session.new(_mock_session)
# NOTE: rack-test v0.5 doesn't build a default uri correctly
- # Make sure requested path is always a full uri
+ # Make sure requested path is always a full URI.
session.request(build_full_uri(path, request_env), request_env)
@request_count += 1
@@ -324,8 +324,8 @@ module ActionDispatch
def create_session(app)
klass = APP_SESSIONS[app] ||= Class.new(Integration::Session) {
- # If the app is a Rails app, make url_helpers available on the session
- # This makes app.url_for and app.foo_path available in the console
+ # If the app is a Rails app, make url_helpers available on the session.
+ # This makes app.url_for and app.foo_path available in the console.
if app.respond_to?(:routes)
include app.routes.url_helpers
include app.routes.mounted_helpers
diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb
index 91b25ec155..ec949c869b 100644
--- a/actionpack/lib/action_dispatch/testing/test_request.rb
+++ b/actionpack/lib/action_dispatch/testing/test_request.rb
@@ -9,7 +9,7 @@ module ActionDispatch
"HTTP_USER_AGENT" => "Rails Testing",
)
- # Create a new test request with default `env` values
+ # Create a new test request with default `env` values.
def self.create(env = {})
env = Rails.application.env_config.merge(env) if defined?(Rails.application) && Rails.application
env["rack.request.cookie_hash"] ||= {}.with_indifferent_access
diff --git a/actionpack/lib/action_pack/gem_version.rb b/actionpack/lib/action_pack/gem_version.rb
index d6a91a0569..fddc3033d5 100644
--- a/actionpack/lib/action_pack/gem_version.rb
+++ b/actionpack/lib/action_pack/gem_version.rb
@@ -6,9 +6,9 @@ module ActionPack
module VERSION
MAJOR = 5
- MINOR = 1
+ MINOR = 2
TINY = 0
- PRE = "beta1"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/actionpack/test/controller/api/with_helpers_test.rb b/actionpack/test/controller/api/with_helpers_test.rb
new file mode 100644
index 0000000000..9882a25ae1
--- /dev/null
+++ b/actionpack/test/controller/api/with_helpers_test.rb
@@ -0,0 +1,26 @@
+require "abstract_unit"
+
+module ApiWithHelper
+ def my_helper
+ "helper"
+ end
+end
+
+class WithHelpersController < ActionController::API
+ include ActionController::Helpers
+ helper ApiWithHelper
+
+ def with_helpers
+ render plain: self.class.helpers.my_helper
+ end
+end
+
+class WithHelpersTest < ActionController::TestCase
+ tests WithHelpersController
+
+ def test_with_helpers
+ get :with_helpers
+
+ assert_equal "helper", response.body
+ end
+end
diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md
index 6e71809385..c514e757c8 100644
--- a/actionview/CHANGELOG.md
+++ b/actionview/CHANGELOG.md
@@ -1,216 +1 @@
-* Remove the option `encode_special_chars` misnomer from `strip_tags`
-
- As of rails-html-sanitizer v1.0.3, the sanitizer will ignore the
- `encode_special_chars` option.
-
- Fixes #28060.
-
- *Andrew Hood*
-
-## Rails 5.1.0.beta1 (February 23, 2017) ##
-
-* Change the ERB handler from Erubis to Erubi.
-
- Erubi is an Erubis fork that's svelte, simple, and currently maintained.
- Plus it supports `--enable-frozen-string-literal` in Ruby 2.3+.
-
- Compatibility: Drops support for `<%===` tags for debug output.
- These were an unused, undocumented side effect of the Erubis
- implementation.
-
- Deprecation: The Erubis handler will be removed in Rails 5.2, for the
- handful of folks using it directly.
-
- *Jeremy Evans*
-
-* Allow render locals to be assigned to instance variables in a view.
-
- Fixes #27480.
-
- *Andrew White*
-
-* Add `check_parameters` option to `current_page?` which makes it more strict.
-
- *Maksym Pugach*
-
-* Return correct object name in form helper method after `fields_for`.
-
- Fixes #26931.
-
- *Yuji Yaginuma*
-
-* Use `ActionView::Resolver.caching?` (`config.action_view.cache_template_loading`)
- to enable template recompilation.
-
- Before it was enabled by `consider_all_requests_local`, which caused
- recompilation in tests.
-
- *Max Melentiev*
-
-* Add `form_with` to unify `form_tag` and `form_for` usage.
-
- Used like `form_tag` (where just the open tag is output):
-
- ```erb
- <%= form_with scope: :post, url: super_special_posts_path %>
- ```
-
- Used like `form_for`:
-
- ```erb
- <%= form_with model: @post do |form| %>
- <%= form.text_field :title %>
- <% end %>
- ```
-
- *Kasper Timm Hansen*, *Marek Kirejczyk*
-
-* Add `fields` form helper method.
-
- ```erb
- <%= fields :comment, model: @comment do |fields| %>
- <%= fields.text_field :title %>
- <% end %>
- ```
-
- Can also be used within form helpers such as `form_with`.
-
- *Kasper Timm Hansen*
-
-* Removed deprecated `#original_exception` in `ActionView::Template::Error`.
-
- *Rafael Mendonça França*
-
-* Render now accepts any keys for locals, including reserved keywords.
-
- Only locals with valid variable names get set directly. Others
- will still be available in `local_assigns`.
-
- Example of render with reserved keywords:
-
- ```erb
- <%= render "example", class: "text-center", message: "Hello world!" %>
-
- <!-- _example.html.erb: -->
- <%= tag.div class: local_assigns[:class] do %>
- <p><%= message %></p>
- <% end %>
- ```
-
- *Peter Schilling*, *Matthew Draper*
-
-* Add `:skip_pipeline` option to several asset tag helpers
-
- `javascript_include_tag`, `stylesheet_link_tag`, `favicon_link_tag`,
- `image_tag` and `audio_tag` now accept a `:skip_pipeline` option which can
- be set to true to bypass the asset pipeline and serve the assets from the
- public folder.
-
- *Richard Schneeman*
-
-* Add `:poster_skip_pipeline` option to the `video_tag` helper
-
- `video_tag` now accepts a `:poster_skip_pipeline` option which can be used
- in combination with the `:poster` option to bypass the asset pipeline and
- serve the poster image for the video from the public folder.
-
- *Richard Schneeman*
-
-* Show cache hits and misses when rendering partials.
-
- Partials using the `cache` helper will show whether a render hit or missed
- the cache:
-
- ```
- Rendered messages/_message.html.erb in 1.2 ms [cache hit]
- Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss]
- ```
-
- This removes the need for the old fragment cache logging:
-
- ```
- Read fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/d0bdf2974e1ef6d31685c3b392ad0b74 (0.6ms)
- Rendered messages/_message.html.erb in 1.2 ms [cache hit]
- Write fragment views/v1/2914079/v1/2914079/recordings/70182313-20160225015037000000/3b4e249ac9d168c617e32e84b99218b5 (1.1ms)
- Rendered recordings/threads/_thread.html.erb in 1.5 ms [cache miss]
- ```
-
- Though that full output can be reenabled with
- `config.action_controller.enable_fragment_cache_logging = true`.
-
- *Stan Lo*
-
-* Changed partial rendering with a collection to allow collections which
- implement `to_a`.
-
- Extracting the collection option had an optimization to avoid unnecessary
- queries of ActiveRecord Relations by calling `#to_ary` on the given
- collection. Instances of `Enumerator` or `Enumerable` are valid
- collections, but they do not implement `#to_ary`. By changing this to
- `#to_a`, they will now be extracted and rendered as expected.
-
- *Steven Harman*
-
-* New syntax for tag helpers. Avoid positional parameters and support HTML5 by default.
- Example usage of tag helpers before:
-
- ```ruby
- tag(:br, nil, true)
- content_tag(:div, content_tag(:p, "Hello world!"), class: "strong")
-
- <%= content_tag :div, class: "strong" do -%>
- Hello world!
- <% end -%>
- ```
-
- Example usage of tag helpers after:
-
- ```ruby
- tag.br
- tag.div tag.p("Hello world!"), class: "strong"
-
- <%= tag.div class: "strong" do %>
- Hello world!
- <% end %>
- ```
-
- *Marek Kirejczyk*, *Kasper Timm Hansen*
-
-* Change `datetime_field` and `datetime_field_tag` to generate `datetime-local` fields.
-
- As a new specification of the HTML 5 the text field type `datetime` will no longer exist
- and it is recommended to use `datetime-local`.
- Ref: https://html.spec.whatwg.org/multipage/forms.html#local-date-and-time-state-(type=datetime-local)
-
- *Herminio Torres*
-
-* Raw template handler (which is also the default template handler in Rails 5) now outputs
- HTML-safe strings.
-
- In Rails 5 the default template handler was changed to the raw template handler. Because
- the ERB template handler escaped strings by default this broke some applications that
- expected plain JS or HTML files to be rendered unescaped. This fixes the issue caused
- by changing the default handler by changing the Raw template handler to output HTML-safe
- strings.
-
- *Eileen M. Uchitelle*
-
-* `select_tag`'s `include_blank` option for generation for blank option tag, now adds an empty space label,
- when the value as well as content for option tag are empty, so that we conform with html specification.
- Ref: https://www.w3.org/TR/html5/forms.html#the-option-element.
-
- Generation of option before:
-
- ```html
- <option value=""></option>
- ```
-
- Generation of option after:
-
- ```html
- <option value="" label=" "></option>
- ```
-
- *Vipul A M*
-
-Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/actionview/CHANGELOG.md) for previous changes.
+Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/actionview/CHANGELOG.md) for previous changes.
diff --git a/actionview/app/assets/javascripts/features/disable.coffee b/actionview/app/assets/javascripts/features/disable.coffee
index e8cce7da40..90aa3bdf0e 100644
--- a/actionview/app/assets/javascripts/features/disable.coffee
+++ b/actionview/app/assets/javascripts/features/disable.coffee
@@ -2,6 +2,10 @@
{ matches, getData, setData, stopEverything, formElements } = Rails
+Rails.handleDisabledElement = (e) ->
+ element = this
+ stopEverything(e) if element.disabled
+
# Unified function to enable an element (link, button and form)
Rails.enableElement = (e) ->
element = if e instanceof Event then e.target else e
diff --git a/actionview/app/assets/javascripts/rails-ujs.coffee b/actionview/app/assets/javascripts/rails-ujs.coffee
index df889ce067..afe7d6f7a3 100644
--- a/actionview/app/assets/javascripts/rails-ujs.coffee
+++ b/actionview/app/assets/javascripts/rails-ujs.coffee
@@ -12,7 +12,7 @@
fire, delegate
getData, $
refreshCSRFTokens, CSRFProtection
- enableElement, disableElement
+ enableElement, disableElement, handleDisabledElement
handleConfirm
handleRemote, formSubmitButtonClick, handleMetaClick
handleMethod
@@ -44,19 +44,23 @@ Rails.start = ->
delegate document, Rails.buttonDisableSelector, 'ajax:complete', enableElement
delegate document, Rails.buttonDisableSelector, 'ajax:stopped', enableElement
+ delegate document, Rails.linkClickSelector, 'click', handleDisabledElement
delegate document, Rails.linkClickSelector, 'click', handleConfirm
delegate document, Rails.linkClickSelector, 'click', handleMetaClick
delegate document, Rails.linkClickSelector, 'click', disableElement
delegate document, Rails.linkClickSelector, 'click', handleRemote
delegate document, Rails.linkClickSelector, 'click', handleMethod
+ delegate document, Rails.buttonClickSelector, 'click', handleDisabledElement
delegate document, Rails.buttonClickSelector, 'click', handleConfirm
delegate document, Rails.buttonClickSelector, 'click', disableElement
delegate document, Rails.buttonClickSelector, 'click', handleRemote
+ delegate document, Rails.inputChangeSelector, 'change', handleDisabledElement
delegate document, Rails.inputChangeSelector, 'change', handleConfirm
delegate document, Rails.inputChangeSelector, 'change', handleRemote
+ delegate document, Rails.formSubmitSelector, 'submit', handleDisabledElement
delegate document, Rails.formSubmitSelector, 'submit', handleConfirm
delegate document, Rails.formSubmitSelector, 'submit', handleRemote
# Normal mode submit
@@ -65,6 +69,7 @@ Rails.start = ->
delegate document, Rails.formSubmitSelector, 'ajax:send', disableElement
delegate document, Rails.formSubmitSelector, 'ajax:complete', enableElement
+ delegate document, Rails.formInputClickSelector, 'click', handleDisabledElement
delegate document, Rails.formInputClickSelector, 'click', handleConfirm
delegate document, Rails.formInputClickSelector, 'click', formSubmitButtonClick
diff --git a/actionview/lib/action_view/digestor.rb b/actionview/lib/action_view/digestor.rb
index 0658d8601d..ba189e23fe 100644
--- a/actionview/lib/action_view/digestor.rb
+++ b/actionview/lib/action_view/digestor.rb
@@ -62,8 +62,10 @@ module ActionView
node
end
else
- logger.error " '#{name}' file doesn't exist, so no dependencies"
- logger.error " Couldn't find template for digesting: #{name}"
+ unless name.include?('#') # Dynamic template partial names can never be tracked
+ logger.error " Couldn't find template for digesting: #{name}"
+ end
+
seen[name] ||= Missing.new(name, logical_name, nil)
end
end
diff --git a/actionview/lib/action_view/gem_version.rb b/actionview/lib/action_view/gem_version.rb
index 662a85f191..92e21d7a4f 100644
--- a/actionview/lib/action_view/gem_version.rb
+++ b/actionview/lib/action_view/gem_version.rb
@@ -6,9 +6,9 @@ module ActionView
module VERSION
MAJOR = 5
- MINOR = 1
+ MINOR = 2
TINY = 0
- PRE = "beta1"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/actionview/package.json b/actionview/package.json
index a1da13315e..690749a051 100644
--- a/actionview/package.json
+++ b/actionview/package.json
@@ -1,6 +1,6 @@
{
"name": "rails-ujs",
- "version": "5.1.0-beta1",
+ "version": "5.2.0-alpha",
"description": "Ruby on Rails unobtrusive scripting adapter",
"main": "lib/assets/compiled/rails-ujs.js",
"files": [
diff --git a/actionview/test/template/digestor_test.rb b/actionview/test/template/digestor_test.rb
index a814cab686..e225c3de09 100644
--- a/actionview/test/template/digestor_test.rb
+++ b/actionview/test/template/digestor_test.rb
@@ -122,13 +122,13 @@ class TemplateDigestorTest < ActionView::TestCase
end
def test_logging_of_missing_template_for_dependencies
- assert_logged "'messages/something_missing' file doesn't exist, so no dependencies" do
+ assert_logged "Couldn't find template for digesting: messages/something_missing" do
dependencies("messages/something_missing")
end
end
def test_logging_of_missing_template_for_nested_dependencies
- assert_logged "'messages/something_missing' file doesn't exist, so no dependencies" do
+ assert_logged "Couldn't find template for digesting: messages/something_missing" do
nested_dependencies("messages/something_missing")
end
end
diff --git a/actionview/test/ujs/public/test/data-confirm.js b/actionview/test/ujs/public/test/data-confirm.js
index 28190c2250..229b9e1466 100644
--- a/actionview/test/ujs/public/test/data-confirm.js
+++ b/actionview/test/ujs/public/test/data-confirm.js
@@ -26,6 +26,13 @@ module('data-confirm', {
'data-confirm': 'Are you absolutely sure?'
}))
+ $('#qunit-fixture').append($('<button />', {
+ type: 'submit',
+ form: 'confirm',
+ disabled: 'disabled',
+ 'data-confirm': 'Are you absolutely sure?'
+ }))
+
this.windowConfirm = window.confirm
},
teardown: function() {
@@ -286,3 +293,24 @@ asyncTest('clicking on the children of a link should also trigger a confirm', 6,
.find('strong')
.triggerNative('click')
})
+
+asyncTest('clicking on the children of a disabled button should not trigger a confirm.', 1, function() {
+ var message
+ // auto-decline:
+ window.confirm = function(msg) { message = msg; return false }
+
+ $('button[data-confirm][disabled]')
+ .html("<strong>Click me</strong>")
+ .bindNative('confirm', function() {
+ App.assertCallbackNotInvoked('confirm')
+ })
+ .find('strong')
+ .bindNative('click', function() {
+ App.assertCallbackInvoked('click')
+ })
+ .triggerNative('click')
+
+ setTimeout(function() {
+ start()
+ }, 50)
+})
diff --git a/activejob/CHANGELOG.md b/activejob/CHANGELOG.md
index 41505fbf83..6b4f93df8b 100644
--- a/activejob/CHANGELOG.md
+++ b/activejob/CHANGELOG.md
@@ -1,49 +1 @@
-## Rails 5.1.0.beta1 (February 23, 2017) ##
-
-* Correctly set test adapter when configure the queue adapter on a per job.
-
- Fixes #26360.
-
- *Yuji Yaginuma*
-
-* Removed deprecated support to passing the adapter class to `.queue_adapter`.
-
- *Rafael Mendonça França*
-
-* Removed deprecated `#original_exception` in `ActiveJob::DeserializationError`.
-
- *Rafael Mendonça França*
-
-* Added instance variable `@queue` to JobWrapper.
-
- This will fix issues in [resque-scheduler](https://github.com/resque/resque-scheduler) `#job_to_hash` method,
- so we can use `#enqueue_delayed_selection`, `#remove_delayed` method in resque-scheduler smoothly.
-
- *mu29*
-
-* Yield the job instance so you have access to things like `job.arguments` on the custom logic after retries fail.
-
- *DHH*
-
-* Added declarative exception handling via `ActiveJob::Base.retry_on` and `ActiveJob::Base.discard_on`.
-
- Examples:
-
- class RemoteServiceJob < ActiveJob::Base
- retry_on CustomAppException # defaults to 3s wait, 5 attempts
- retry_on AnotherCustomAppException, wait: ->(executions) { executions * 2 }
- retry_on ActiveRecord::Deadlocked, wait: 5.seconds, attempts: 3
- retry_on Net::OpenTimeout, wait: :exponentially_longer, attempts: 10
- discard_on ActiveJob::DeserializationError
-
- def perform(*args)
- # Might raise CustomAppException or AnotherCustomAppException for something domain specific
- # Might raise ActiveRecord::Deadlocked when a local db deadlock is detected
- # Might raise Net::OpenTimeout when the remote service is down
- end
- end
-
- *DHH*
-
-
-Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/activejob/CHANGELOG.md) for previous changes.
+Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/activejob/CHANGELOG.md) for previous changes.
diff --git a/activejob/lib/active_job/gem_version.rb b/activejob/lib/active_job/gem_version.rb
index 2b608b9a65..bf81f37e81 100644
--- a/activejob/lib/active_job/gem_version.rb
+++ b/activejob/lib/active_job/gem_version.rb
@@ -6,9 +6,9 @@ module ActiveJob
module VERSION
MAJOR = 5
- MINOR = 1
+ MINOR = 2
TINY = 0
- PRE = "beta1"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
index 1503b6a3e4..6b9b3dd7ff 100644
--- a/activemodel/CHANGELOG.md
+++ b/activemodel/CHANGELOG.md
@@ -1,32 +1,6 @@
-## Rails 5.1.0.beta1 (February 23, 2017) ##
+* Avoid converting integer as a string into float.
-* Remove deprecated behavior that halts callbacks when the return is false.
+ *namusyaka*
- *Rafael Mendonça França*
-* Remove unused `ActiveModel::TestCase` class.
-
- *Yuji Yaginuma*
-
-* Moved DecimalWithoutScale, Text, and UnsignedInteger from Active Model to Active Record
-
- *Iain Beeston*
-
-* Allow indifferent access in `ActiveModel::Errors`.
-
- `#include?`, `#has_key?`, `#key?`, `#delete` and `#full_messages_for`.
-
- *Kenichi Kamiya*
-
-* Removed deprecated `:tokenizer` in the length validator.
-
- *Rafael Mendonça França*
-
-* Removed deprecated methods in `ActiveModel::Errors`.
-
- `#get`, `#set`, `[]=`, `add_on_empty` and `add_on_blank`.
-
- *Rafael Mendonça França*
-
-
-Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/activemodel/CHANGELOG.md) for previous changes.
+Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/activemodel/CHANGELOG.md) for previous changes.
diff --git a/activemodel/lib/active_model/gem_version.rb b/activemodel/lib/active_model/gem_version.rb
index 6a2ab2a8e5..67bdfaa643 100644
--- a/activemodel/lib/active_model/gem_version.rb
+++ b/activemodel/lib/active_model/gem_version.rb
@@ -6,9 +6,9 @@ module ActiveModel
module VERSION
MAJOR = 5
- MINOR = 1
+ MINOR = 2
TINY = 0
- PRE = "beta1"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb
index 30a9ef472d..995b331245 100644
--- a/activemodel/lib/active_model/validations/numericality.rb
+++ b/activemodel/lib/active_model/validations/numericality.rb
@@ -70,6 +70,7 @@ module ActiveModel
end
def parse_raw_value_as_a_number(raw_value)
+ return raw_value.to_i if is_integer?(raw_value)
Kernel.Float(raw_value) if raw_value !~ /\A0[xX]/
end
diff --git a/activemodel/test/cases/validations/numericality_validation_test.rb b/activemodel/test/cases/validations/numericality_validation_test.rb
index a1be2de578..c0158e075f 100644
--- a/activemodel/test/cases/validations/numericality_validation_test.rb
+++ b/activemodel/test/cases/validations/numericality_validation_test.rb
@@ -260,6 +260,15 @@ class NumericalityValidationTest < ActiveModel::TestCase
Person.clear_validators!
end
+ def test_validates_numericality_with_exponent_number
+ base = 10_000_000_000_000_000
+ Topic.validates_numericality_of :approved, less_than_or_equal_to: base
+ topic = Topic.new
+ topic.approved = (base + 1).to_s
+
+ assert topic.invalid?
+ end
+
def test_validates_numericality_with_invalid_args
assert_raise(ArgumentError) { Topic.validates_numericality_of :approved, greater_than_or_equal_to: "foo" }
assert_raise(ArgumentError) { Topic.validates_numericality_of :approved, less_than_or_equal_to: "foo" }
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index 4488524c4e..30d580b9e3 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,771 +1 @@
-* Remove comments from structure.sql when using postgresql adapter to avoid
- version-specific parts of the file.
-
- Fixes #28153.
-
- *Ari Pollak*
-
-* Add `:default` option to `belongs_to`.
-
- Use it to specify that an association should be initialized with a particular
- record before validation. For example:
-
- # Before
- belongs_to :account
- before_validation -> { self.account ||= Current.account }
-
- # After
- belongs_to :account, default: -> { Current.account }
-
- *George Claghorn*
-
-* Deprecate `Migrator.schema_migrations_table_name`.
-
- *Ryuta Kamizono*
-
-* Fix select with block doesn't return newly built records in has_many association.
-
- Fixes #28348.
-
- *Ryuta Kamizono*
-
-* Check whether `Rails.application` defined before calling it
-
- In #27674 we changed the migration generator to generate migrations at the
- path defined in `Rails.application.config.paths` however the code checked
- for the presence of the `Rails` constant but not the `Rails.application`
- method which caused problems when using Active Record and generators outside
- of the context of a Rails application.
-
- Fixes #28325.
-
- *Andrew White*
-
-* Fix `deserialize` with JSON array.
-
- Fixes #28285.
-
- *Ryuta Kamizono*
-
-* Fix `rake db:schema:load` with subdirectories.
-
- *Ryuta Kamizono*
-
-* Fix `rake db:migrate:status` with subdirectories.
-
- *Ryuta Kamizono*
-
-* Don't share options between reference id and type columns
-
- When using a polymorphic reference column in a migration, sharing options
- between the two columns doesn't make sense since they are different types.
- The `reference_id` column is usually an integer and the `reference_type`
- column a string so options like `unsigned: true` will result in an invalid
- table definition.
-
- *Ryuta Kamizono*
-
-* Use `max_identifier_length` for `index_name_length` in PostgreSQL adapter.
-
- *Ryuta Kamizono*
-
-* Deprecate `supports_migrations?` on connection adapters.
-
- *Ryuta Kamizono*
-
-* Fix regression of #1969 with SELECT aliases in HAVING clause.
-
- *Eugene Kenny*
-
-* Deprecate using `#quoted_id` in quoting.
-
- *Ryuta Kamizono*
-
-* Fix `wait_timeout` to configurable for mysql2 adapter.
-
- Fixes #26556.
-
- *Ryuta Kamizono*
-
-
-## Rails 5.1.0.beta1 (February 23, 2017) ##
-
-* Correctly dump native timestamp types for MySQL.
-
- The native timestamp type in MySQL is different from datetime type.
- Internal representation of the timestamp type is UNIX time, This means
- that timestamp columns are affected by time zone.
-
- > SET time_zone = '+00:00';
- Query OK, 0 rows affected (0.00 sec)
-
- > INSERT INTO time_with_zone(ts,dt) VALUES (NOW(),NOW());
- Query OK, 1 row affected (0.02 sec)
-
- > SELECT * FROM time_with_zone;
- +---------------------+---------------------+
- | ts | dt |
- +---------------------+---------------------+
- | 2016-02-07 22:11:44 | 2016-02-07 22:11:44 |
- +---------------------+---------------------+
- 1 row in set (0.00 sec)
-
- > SET time_zone = '-08:00';
- Query OK, 0 rows affected (0.00 sec)
-
- > SELECT * FROM time_with_zone;
- +---------------------+---------------------+
- | ts | dt |
- +---------------------+---------------------+
- | 2016-02-07 14:11:44 | 2016-02-07 22:11:44 |
- +---------------------+---------------------+
- 1 row in set (0.00 sec)
-
- *Ryuta Kamizono*
-
-* All integer-like PKs are autoincrement unless they have an explicit default.
-
- *Matthew Draper*
-
-* Omit redundant `using: :btree` for schema dumping.
-
- *Ryuta Kamizono*
-
-* Deprecate passing `default` to `index_name_exists?`.
-
- *Ryuta Kamizono*
-
-* PostgreSQL: schema dumping support for interval and OID columns.
-
- *Ryuta Kamizono*
-
-* Deprecate `supports_primary_key?` on connection adapters since it's
- been long unused and unsupported.
-
- *Ryuta Kamizono*
-
-* Make `table_name=` reset current statement cache,
- so queries are not run against the previous table name.
-
- *namusyaka*
-
-* Allow `ActiveRecord::Base#as_json` to be passed a frozen Hash.
-
- *Isaac Betesh*
-
-* Fix inspection behavior when the :id column is not primary key.
-
- *namusyaka*
-
-* Deprecate locking records with unpersisted changes.
-
- *Marc Schütz*
-
-* Remove deprecated behavior that halts callbacks when the return is false.
-
- *Rafael Mendonça França*
-
-* Deprecate `ColumnDumper#migration_keys`.
-
- *Ryuta Kamizono*
-
-* Fix `association_primary_key_type` for reflections with symbol primary key.
-
- Fixes #27864.
-
- *Daniel Colson*
-
-* Virtual/generated column support for MySQL 5.7.5+ and MariaDB 5.2.0+.
-
- MySQL generated columns: https://dev.mysql.com/doc/refman/5.7/en/create-table-generated-columns.html
- MariaDB virtual columns: https://mariadb.com/kb/en/mariadb/virtual-computed-columns/
-
- Declare virtual columns with `t.virtual name, type: …, as: "expression"`.
- Pass `stored: true` to persist the generated value (false by default).
-
- Example:
-
- create_table :generated_columns do |t|
- t.string :name
- t.virtual :upper_name, type: :string, as: "UPPER(name)"
- t.virtual :name_length, type: :integer, as: "LENGTH(name)", stored: true
- t.index :name_length # May be indexed, too!
- end
-
- *Ryuta Kamizono*
-
-* Deprecate `initialize_schema_migrations_table` and `initialize_internal_metadata_table`.
-
- *Ryuta Kamizono*
-
-* Support foreign key creation for SQLite3.
-
- *Ryuta Kamizono*
-
-* Place generated migrations into the path set by `config.paths["db/migrate"]`.
-
- *Kevin Glowacz*
-
-* Raise `ActiveRecord::InvalidForeignKey` when a foreign key constraint fails on SQLite3.
-
- *Ryuta Kamizono*
-
-* Add the touch option to `#increment!` and `#decrement!`.
-
- *Hiroaki Izu*
-
-* Deprecate passing a class to the `class_name` because it eagerloads more classes than
- necessary and potentially creates circular dependencies.
-
- *Kir Shatrov*
-
-* Raise error when has_many through is defined before through association.
-
- Fixes #26834.
-
- *Chris Holmes*
-
-* Deprecate passing `name` to `indexes`.
-
- *Ryuta Kamizono*
-
-* Remove deprecated tasks: `db:test:clone`, `db:test:clone_schema`, `db:test:clone_structure`.
-
- *Rafel Mendonça França*
-
-* Compare deserialized values for `PostgreSQL::OID::Hstore` types when
- calling `ActiveRecord::Dirty#changed_in_place?`.
-
- Fixes #27502.
-
- *Jon Moss*
-
-* Raise `ArgumentError` when passing an `ActiveRecord::Base` instance to `.find`,
- `.exists?` and `.update`.
-
- *Rafael Mendonça França*
-
-* Respect precision option for arrays of timestamps.
-
- Fixes #27514.
-
- *Sean Griffin*
-
-* Optimize slow model instantiation when using STI and `store_full_sti_class = false` option.
-
- *Konstantin Lazarev*
-
-* Add `touch` option to counter cache modifying methods.
-
- Works when updating, resetting, incrementing and decrementing counters:
-
- # Touches `updated_at`/`updated_on`.
- Topic.increment_counter(:messages_count, 1, touch: true)
- Topic.decrement_counter(:messages_count, 1, touch: true)
-
- # Touches `last_discussed_at`.
- Topic.reset_counters(18, :messages, touch: :last_discussed_at)
-
- # Touches `updated_at` and `last_discussed_at`.
- Topic.update_counters(18, messages_count: 5, touch: %i( updated_at last_discussed_at ))
-
- Fixes #26724.
-
- *Jarred Trost*
-
-* Remove deprecated `#uniq`, `#uniq!`, and `#uniq_value`.
-
- *Ryuta Kamizono*
-
-* Remove deprecated `#insert_sql`, `#update_sql`, and `#delete_sql`.
-
- *Ryuta Kamizono*
-
-* Remove deprecated `#use_transactional_fixtures` configuration.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `#raise_in_transactional_callbacks` configuration.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `#load_schema_for`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated conditions parameter from `#destroy_all` and `#delete_all`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support to passing arguments to `#select` when a block is provided.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support to query using commas on LIMIT.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support to passing a class as a value in a query.
-
- *Rafael Mendonça França*
-
-* Raise `ActiveRecord::IrreversibleOrderError` when using `last` with an irreversible
- order.
-
- *Rafael Mendonça França*
-
-* Raise when a `has_many :through` association has an ambiguous reflection name.
-
- *Rafael Mendonça França*
-
-* Raise when `ActiveRecord::Migration` is inherited from directly.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `original_exception` argument in `ActiveRecord::StatementInvalid#initialize`
- and `ActiveRecord::StatementInvalid#original_exception`.
-
- *Rafael Mendonça França*
-
-* `#tables` and `#table_exists?` return only tables and not views.
-
- All the deprecations on those methods were removed.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `name` argument from `#tables`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated support to passing a column to `#quote`.
-
- *Rafael Mendonça França*
-
-* Set `:time` as a timezone aware type and remove deprecation when
- `config.active_record.time_zone_aware_types` is not explicitly set.
-
- *Rafael Mendonça França*
-
-* Remove deprecated force reload argument in singular and collection association readers.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `activerecord.errors.messages.restrict_dependent_destroy.one` and
- `activerecord.errors.messages.restrict_dependent_destroy.many` i18n scopes.
-
- *Rafael Mendonça França*
-
-* Allow passing extra flags to `db:structure:load` and `db:structure:dump`
-
- Introduces `ActiveRecord::Tasks::DatabaseTasks.structure_(load|dump)_flags` to customize the
- eventual commands run against the database, e.g. mysqldump/pg_dump.
-
- *Kir Shatrov*
-
-* Notifications see frozen SQL string.
-
- Fixes #23774.
-
- *Richard Monette*
-
-* RuntimeErrors are no longer translated to `ActiveRecord::StatementInvalid`.
-
- *Richard Monette*
-
-* Change the schema cache format to use YAML instead of Marshal.
-
- *Kir Shatrov*
-
-* Support index length and order options using both string and symbol
- column names.
-
- Fixes #27243.
-
- *Ryuta Kamizono*
-
-* Raise `ActiveRecord::RangeError` when values that executed are out of range.
-
- *Ryuta Kamizono*
-
-* Raise `ActiveRecord::NotNullViolation` when a record cannot be inserted
- or updated because it would violate a not null constraint.
-
- *Ryuta Kamizono*
-
-* Emulate db trigger behaviour for after_commit :destroy, :update.
-
- Race conditions can occur when an ActiveRecord is destroyed
- twice or destroyed and updated. The callbacks should only be
- triggered once, similar to a SQL database trigger.
-
- *Stefan Budeanu*
-
-* Moved `DecimalWithoutScale`, `Text`, and `UnsignedInteger` from Active Model to Active Record.
-
- *Iain Beeston*
-
-* Fix `write_attribute` method to check whether an attribute is aliased or not, and
- use the aliased attribute name if needed.
-
- *Prathamesh Sonpatki*
-
-* Fix `read_attribute` method to check whether an attribute is aliased or not, and
- use the aliased attribute name if needed.
-
- Fixes #26417.
-
- *Prathamesh Sonpatki*
-
-* PostgreSQL & MySQL: Use big integer as primary key type for new tables.
-
- *Jon McCartie*, *Pavel Pravosud*
-
-* Change the type argument of `ActiveRecord::Base#attribute` to be optional.
- The default is now `ActiveRecord::Type::Value.new`, which provides no type
- casting behavior.
-
- *Sean Griffin*
-
-* Don't treat unsigned integers with zerofill as signed.
-
- Fixes #27125.
-
- *Ryuta Kamizono*
-
-* Fix the uniqueness validation scope with a polymorphic association.
-
- *Sergey Alekseev*
-
-* Raise `ActiveRecord::RecordNotFound` from collection `*_ids` setters
- for unknown IDs with a better error message.
-
- Changes the collection `*_ids` setters to cast provided IDs the data
- type of the primary key set in the association, not the model
- primary key.
-
- *Dominic Cleal*
-
-* For PostgreSQL >= 9.4 use `pgcrypto`'s `gen_random_uuid()` instead of
- `uuid-ossp`'s UUID generation function.
-
- *Yuji Yaginuma*, *Yaw Boakye*
-
-* Introduce `Model#reload_<association>` to bring back the behavior
- of `Article.category(true)` where `category` is a singular
- association.
-
- The force reloading of the association reader was deprecated
- in #20888. Unfortunately the suggested alternative of
- `article.reload.category` does not expose the same behavior.
-
- This patch adds a reader method with the prefix `reload_` for
- singular associations. This method has the same semantics as
- passing true to the association reader used to have.
-
- *Yves Senn*
-
-* Make sure eager loading `ActiveRecord::Associations` also loads
- constants defined in `ActiveRecord::Associations::Preloader`.
-
- *Yves Senn*
-
-* Allow `ActionController::Parameters`-like objects to be passed as
- values for Postgres HStore columns.
-
- Fixes #26904.
-
- *Jon Moss*
-
-* Added `stat` method to `ActiveRecord::ConnectionAdapters::ConnectionPool`.
-
- Example:
-
- ActiveRecord::Base.connection_pool.stat # =>
- { size: 15, connections: 1, busy: 1, dead: 0, idle: 0, waiting: 0, checkout_timeout: 5 }
-
- *Pavel Evstigneev*
-
-* Avoid `unscope(:order)` when `limit_value` is presented for `count`
- and `exists?`.
-
- If `limit_value` is presented, records fetching order is very important
- for performance. We should not unscope the order in the case.
-
- *Ryuta Kamizono*
-
-* Fix an Active Record `DateTime` field `NoMethodError` caused by incomplete
- datetime.
-
- Fixes #24195.
-
- *Sen Zhang*
-
-* Allow `slice` to take an array of methods(without the need for splatting).
-
- *Cohen Carlisle*
-
-* Improved partial writes with HABTM and has many through associations
- to fire database query only if relation has been changed.
-
- Fixes #19663.
-
- *Mehmet Emin İNAÇ*
-
-* Deprecate passing arguments and block at the same time to
- `ActiveRecord::QueryMethods#select`.
-
- *Prathamesh Sonpatki*
-
-* Fixed: Optimistic locking does not work well with `null` in the database.
-
- Fixes #26024.
-
- *bogdanvlviv*
-
-* Fixed support for case insensitive comparisons of `text` columns in
- PostgreSQL.
-
- *Edho Arief*
-
-* Serialize JSON attribute value `nil` as SQL `NULL`, not JSON `null`.
-
- *Trung Duc Tran*
-
-* Return `true` from `update_attribute` when the value of the attribute
- to be updated is unchanged.
-
- Fixes #26593.
-
- *Prathamesh Sonpatki*
-
-* Always store errors details information with symbols.
-
- When the association is autosaved we were storing the details with
- string keys. This was creating inconsistency with other details that are
- added using the `Errors#add` method. It was also inconsistent with the
- `Errors#messages` storage.
-
- To fix this inconsistency we are always storing with symbols. This will
- cause a small breaking change because in those cases the details could
- be accessed as strings keys but now it can not.
-
- Fix #26499.
-
- *Rafael Mendonça França*, *Marcus Vieira*
-
-* Calling `touch` on a model using optimistic locking will now leave the model
- in a non-dirty state with no attribute changes.
-
- Fixes #26496.
-
- *Jakob Skjerning*
-
-* Using a mysql2 connection after it fails to reconnect will now have an error message
- saying the connection is closed rather than an undefined method error message.
-
- *Dylan Thacker-Smith*
-
-* PostgreSQL array columns will now respect the encoding of strings contained
- in the array.
-
- Fixes #26326.
-
- *Sean Griffin*
-
-* Inverse association instances will now be set before `after_find` or
- `after_initialize` callbacks are run.
-
- Fixes #26320.
-
- *Sean Griffin*
-
-* Remove unnecessarily association load when a `belongs_to` association has already been
- loaded then the foreign key is changed directly and the record saved.
-
- *James Coleman*
-
-* Remove standardized column types/arguments spaces in schema dump.
-
- *Tim Petricola*
-
-* Avoid loading records from database when they are already loaded using
- the `pluck` method on a collection.
-
- Fixes #25921.
-
- *Ryuta Kamizono*
-
-* Remove text default treated as an empty string in non-strict mode for
- consistency with other types.
-
- Strict mode controls how MySQL handles invalid or missing values in
- data-change statements such as INSERT or UPDATE. If strict mode is not
- in effect, MySQL inserts adjusted values for invalid or missing values
- and produces warnings.
-
- def test_mysql_not_null_defaults_non_strict
- using_strict(false) do
- with_mysql_not_null_table do |klass|
- record = klass.new
- assert_nil record.non_null_integer
- assert_nil record.non_null_string
- assert_nil record.non_null_text
- assert_nil record.non_null_blob
-
- record.save!
- record.reload
-
- assert_equal 0, record.non_null_integer
- assert_equal "", record.non_null_string
- assert_equal "", record.non_null_text
- assert_equal "", record.non_null_blob
- end
- end
- end
-
- https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sql-mode-strict
-
- *Ryuta Kamizono*
-
-* SQLite3 migrations to add a column to an existing table can now be
- successfully rolled back when the column was given and invalid column
- type.
-
- Fixes #26087.
-
- *Travis O'Neill*
-
-* Deprecate `sanitize_conditions`. Use `sanitize_sql` instead.
-
- *Ryuta Kamizono*
-
-* Doing count on relations that contain LEFT OUTER JOIN Arel node no longer
- force a DISTINCT. This solves issues when using count after a left_joins.
-
- *Maxime Handfield Lapointe*
-
-* RecordNotFound raised by association.find exposes `id`, `primary_key` and
- `model` methods to be consistent with RecordNotFound raised by Record.find.
-
- *Michel Pigassou*
-
-* Hashes can once again be passed to setters of `composed_of`, if all of the
- mapping methods are methods implemented on `Hash`.
-
- Fixes #25978.
-
- *Sean Griffin*
-
-* Fix the SELECT statement in `#table_comment` for MySQL.
-
- *Takeshi Akima*
-
-* Virtual attributes will no longer raise when read on models loaded from the
- database.
-
- *Sean Griffin*
-
-* Support calling the method `merge` in `scope`'s lambda.
-
- *Yasuhiro Sugino*
-
-* Fixes multi-parameter attributes conversion with invalid params.
-
- *Hiroyuki Ishii*
-
-* Add newline between each migration in `structure.sql`.
-
- Keeps schema migration inserts as a single commit, but allows for easier
- git diffing.
-
- Fixes #25504.
-
- *Grey Baker*, *Norberto Lopes*
-
-* The flag `error_on_ignored_order_or_limit` has been deprecated in favor of
- the current `error_on_ignored_order`.
-
- *Xavier Noria*
-
-* Batch processing methods support `limit`:
-
- Post.limit(10_000).find_each do |post|
- # ...
- end
-
- It also works in `find_in_batches` and `in_batches`.
-
- *Xavier Noria*
-
-* Using `group` with an attribute that has a custom type will properly cast
- the hash keys after calling a calculation method like `count`.
-
- Fixes #25595.
-
- *Sean Griffin*
-
-* Fix the generated `#to_param` method to use `omission: ''` so that
- the resulting output is actually up to 20 characters, not
- effectively 17 to leave room for the default "...".
- Also call `#parameterize` before `#truncate` and make the
- `separator: /-/` to maximize the information included in the
- output.
-
- Fixes #23635.
-
- *Rob Biedenharn*
-
-* Ensure concurrent invocations of the connection reaper cannot allocate the
- same connection to two threads.
-
- Fixes #25585.
-
- *Matthew Draper*
-
-* Inspecting an object with an associated array of over 10 elements no longer
- truncates the array, preventing `inspect` from looping infinitely in some
- cases.
-
- *Kevin McPhillips*
-
-* Removed the unused methods `ActiveRecord::Base.connection_id` and
- `ActiveRecord::Base.connection_id=`.
-
- *Sean Griffin*
-
-* Ensure hashes can be assigned to attributes created using `composed_of`.
-
- Fixes #25210.
-
- *Sean Griffin*
-
-* Fix logging edge case where if an attribute was of the binary type and
- was provided as a Hash.
-
- *Jon Moss*
-
-* Handle JSON deserialization correctly if the column default from database
- adapter returns `''` instead of `nil`.
-
- *Johannes Opper*
-
-* Introduce new Active Record transaction error classes for catching
- transaction serialization failures or deadlocks.
-
- *Erol Fornoles*
-
-* PostgreSQL: Fix `db:structure:load` silent failure on SQL error.
-
- The command line flag `-v ON_ERROR_STOP=1` should be used
- when invoking `psql` to make sure errors are not suppressed.
-
- Example:
-
- psql -v ON_ERROR_STOP=1 -q -f awesome-file.sql my-app-db
-
- Fixes #23818.
-
- *Ralin Chimev*
-
-
-Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/activerecord/CHANGELOG.md) for previous changes.
+Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/activerecord/CHANGELOG.md) for previous changes.
diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb
index 3c44296d8c..5d6676f0df 100644
--- a/activerecord/lib/active_record/associations/collection_proxy.rb
+++ b/activerecord/lib/active_record/associations/collection_proxy.rb
@@ -743,10 +743,6 @@ module ActiveRecord
# # ]
#--
- def uniq
- load_target.uniq
- end
-
def calculate(operation, column_name)
null_scope? ? scope.calculate(operation, column_name) : super
end
diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
index 6019e05c4c..cce8883076 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
@@ -152,16 +152,15 @@ module ActiveRecord
"'#{quote_string(value.to_s)}'"
end
- private
-
- def type_casted_binds(binds)
- if binds.first.is_a?(Array)
- binds.map { |column, value| type_cast(value, column) }
- else
- binds.map { |attr| type_cast(attr.value_for_database) }
- end
+ def type_casted_binds(binds) # :nodoc:
+ if binds.first.is_a?(Array)
+ binds.map { |column, value| type_cast(value, column) }
+ else
+ binds.map { |attr| type_cast(attr.value_for_database) }
end
+ end
+ private
def id_value_for_database(value)
if primary_key = value.class.primary_key
value.instance_variable_get(:@attributes)[primary_key].value_for_database
diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
index b9fbcd05c7..550b4cc86b 100644
--- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
@@ -439,7 +439,7 @@ module ActiveRecord
# Provides access to the underlying database driver for this adapter. For
# example, this method returns a Mysql2::Client object in case of Mysql2Adapter,
- # and a PGconn object in case of PostgreSQLAdapter.
+ # and a PG::Connection object in case of PostgreSQLAdapter.
#
# This is useful for when you need to call a proprietary method such as
# PostgreSQL's lo_* methods.
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/bytea.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/bytea.rb
index 8f9d6e7f9b..702fa8175c 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/bytea.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/bytea.rb
@@ -6,7 +6,7 @@ module ActiveRecord
def deserialize(value)
return if value.nil?
return value.to_s if value.is_a?(Type::Binary::Data)
- PGconn.unescape_bytea(super)
+ PG::Connection.unescape_bytea(super)
end
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
index 6663448a99..e399b6e499 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
@@ -33,7 +33,7 @@ module ActiveRecord
# Quotes schema names for use in SQL queries.
def quote_schema_name(name)
- PGconn.quote_ident(name)
+ PG::Connection.quote_ident(name)
end
def quote_table_name_for_assignment(table, attr)
@@ -42,7 +42,7 @@ module ActiveRecord
# Quotes column names for use in SQL queries.
def quote_column_name(name) # :nodoc:
- @quoted_column_names[name] ||= PGconn.quote_ident(super).freeze
+ @quoted_column_names[name] ||= PG::Connection.quote_ident(super).freeze
end
# Quote date/time values for use in SQL input.
@@ -105,7 +105,7 @@ module ActiveRecord
case value
when Type::Binary::Data
# Return a bind param hash with format as binary.
- # See http://deveiate.org/code/pg/PGconn.html#method-i-exec_prepared-doc
+ # See https://deveiate.org/code/pg/PG/Connection.html#method-i-exec_prepared-doc
# for more information
{ value: value.to_s, format: 1 }
when OID::Xml::Data, OID::Bit::Data
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb b/activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb
index 44a7338bf5..730e7c7137 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/referential_integrity.rb
@@ -6,8 +6,50 @@ module ActiveRecord
true
end
- def disable_referential_integrity # :nodoc:
+ def disable_referential_integrity(&block) # :nodoc:
if supports_disable_referential_integrity?
+ if supports_alter_constraint?
+ disable_referential_integrity_with_alter_constraint(&block)
+ else
+ disable_referential_integrity_with_disable_trigger(&block)
+ end
+ else
+ yield
+ end
+ end
+
+ private
+
+ def disable_referential_integrity_with_alter_constraint
+ tables_constraints = execute(<<-SQL).values
+ SELECT table_name, constraint_name
+ FROM information_schema.table_constraints
+ WHERE constraint_type = 'FOREIGN KEY'
+ AND is_deferrable = 'NO'
+ SQL
+
+ execute(
+ tables_constraints.collect { |table, constraint|
+ "ALTER TABLE #{quote_table_name(table)} ALTER CONSTRAINT #{constraint} DEFERRABLE"
+ }.join(";")
+ )
+
+ begin
+ transaction do
+ execute("SET CONSTRAINTS ALL DEFERRED")
+
+ yield
+ end
+ ensure
+ execute(
+ tables_constraints.collect { |table, constraint|
+ "ALTER TABLE #{quote_table_name(table)} ALTER CONSTRAINT #{constraint} NOT DEFERRABLE"
+ }.join(";")
+ )
+ end
+ end
+
+ def disable_referential_integrity_with_disable_trigger
original_exception = nil
begin
@@ -39,10 +81,7 @@ Rails needs superuser privileges to disable referential integrity.
end
rescue ActiveRecord::ActiveRecordError
end
- else
- yield
end
- end
end
end
end
diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb b/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb
index a3f9ce6d64..aa7940188a 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb
@@ -19,9 +19,9 @@ module ActiveRecord
def quoted
if schema
- PGconn.quote_ident(schema) << SEPARATOR << PGconn.quote_ident(identifier)
+ PG::Connection.quote_ident(schema) << SEPARATOR << PG::Connection.quote_ident(identifier)
else
- PGconn.quote_ident(identifier)
+ PG::Connection.quote_ident(identifier)
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 22c37abb78..6273614f0c 100644
--- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
+++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
@@ -29,11 +29,11 @@ module ActiveRecord
conn_params[:user] = conn_params.delete(:username) if conn_params[:username]
conn_params[:dbname] = conn_params.delete(:database) if conn_params[:database]
- # Forward only valid config params to PGconn.connect.
- valid_conn_param_keys = PGconn.conndefaults_hash.keys + [:requiressl]
+ # Forward only valid config params to PG::Connection.connect.
+ valid_conn_param_keys = PG::Connection.conndefaults_hash.keys + [:requiressl]
conn_params.slice!(*valid_conn_param_keys)
- # The postgres drivers don't allow the creation of an unconnected PGconn object,
+ # The postgres drivers don't allow the creation of an unconnected PG::Connection object,
# so just pass a nil connection object for the time being.
ConnectionAdapters::PostgreSQLAdapter.new(nil, logger, conn_params, config)
end
@@ -201,8 +201,8 @@ module ActiveRecord
end
def connection_active?
- @connection.status == PGconn::CONNECTION_OK
- rescue PGError
+ @connection.status == PG::CONNECTION_OK
+ rescue PG::Error
false
end
end
@@ -249,7 +249,7 @@ module ActiveRecord
def active?
@connection.query "SELECT 1"
true
- rescue PGError
+ rescue PG::Error
false
end
@@ -301,8 +301,8 @@ module ActiveRecord
true
end
- # Range datatypes weren't introduced until PostgreSQL 9.2
def supports_ranges?
+ # Range datatypes weren't introduced until PostgreSQL 9.2
postgresql_version >= 90200
end
@@ -314,6 +314,12 @@ module ActiveRecord
postgresql_version >= 90400
end
+ def supports_alter_constraint?
+ # PostgreSQL 9.4 introduces ALTER TABLE ... ALTER CONSTRAINT but it has a bug and fixed in 9.4.2
+ # https://www.postgresql.org/docs/9.4/static/release-9-4-2.html
+ postgresql_version >= 90402
+ end
+
def get_advisory_lock(lock_id) # :nodoc:
unless lock_id.is_a?(Integer) && lock_id.bit_length <= 63
raise(ArgumentError, "Postgres requires advisory lock ids to be a signed 64 bit integer")
@@ -414,7 +420,7 @@ module ActiveRecord
def translate_exception(exception, message)
return exception unless exception.respond_to?(:result)
- case exception.result.try(:error_field, PGresult::PG_DIAG_SQLSTATE)
+ case exception.result.try(:error_field, PG::PG_DIAG_SQLSTATE)
when UNIQUE_VIOLATION
RecordNotUnique.new(message)
when FOREIGN_KEY_VIOLATION
@@ -651,7 +657,7 @@ module ActiveRecord
CACHED_PLAN_HEURISTIC = "cached plan must not change result type".freeze
def is_cached_plan_failure?(e)
pgerror = e.cause
- code = pgerror.result.result_error_field(PGresult::PG_DIAG_SQLSTATE)
+ code = pgerror.result.result_error_field(PG::PG_DIAG_SQLSTATE)
code == FEATURE_NOT_SUPPORTED && pgerror.message.include?(CACHED_PLAN_HEURISTIC)
rescue
false
@@ -690,7 +696,7 @@ module ActiveRecord
# Connects to a PostgreSQL server and sets up the adapter depending on the
# connected server's characteristics.
def connect
- @connection = PGconn.connect(@connection_parameters)
+ @connection = PG.connect(@connection_parameters)
configure_connection
rescue ::PG::Error => error
if error.message.include?("does not exist")
diff --git a/activerecord/lib/active_record/gem_version.rb b/activerecord/lib/active_record/gem_version.rb
index 174f716152..1a937dbcf7 100644
--- a/activerecord/lib/active_record/gem_version.rb
+++ b/activerecord/lib/active_record/gem_version.rb
@@ -6,9 +6,9 @@ module ActiveRecord
module VERSION
MAJOR = 5
- MINOR = 1
+ MINOR = 2
TINY = 0
- PRE = "beta1"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/activerecord/lib/active_record/log_subscriber.rb b/activerecord/lib/active_record/log_subscriber.rb
index ea101946f4..2297c77835 100644
--- a/activerecord/lib/active_record/log_subscriber.rb
+++ b/activerecord/lib/active_record/log_subscriber.rb
@@ -44,17 +44,17 @@ module ActiveRecord
private
def type_casted_binds(binds, casted_binds)
- casted_binds || binds.map { |attr| type_cast attr.value_for_database }
+ casted_binds || ActiveRecord::Base.connection.type_casted_binds(binds)
end
- def render_bind(attr, type_casted_value)
- value = if attr.type.binary? && attr.value
- "<#{attr.value_for_database.to_s.bytesize} bytes of binary data>"
- else
- type_casted_value
+ def render_bind(attr, value)
+ if attr.is_a?(Array)
+ attr = attr.first
+ elsif attr.type.binary? && attr.value
+ value = "<#{attr.value_for_database.to_s.bytesize} bytes of binary data>"
end
- [attr.name, value]
+ [attr && attr.name, value]
end
def colorize_payload_name(name, payload_name)
@@ -89,10 +89,6 @@ module ActiveRecord
def logger
ActiveRecord::Base.logger
end
-
- def type_cast(value)
- ActiveRecord::Base.connection.type_cast(value)
- end
end
end
diff --git a/activerecord/lib/active_record/migration/compatibility.rb b/activerecord/lib/active_record/migration/compatibility.rb
index 85032ce470..188dd0acef 100644
--- a/activerecord/lib/active_record/migration/compatibility.rb
+++ b/activerecord/lib/active_record/migration/compatibility.rb
@@ -11,7 +11,10 @@ module ActiveRecord
const_get(name)
end
- V5_1 = Current
+ V5_2 = Current
+
+ class V5_1 < V5_2
+ end
class V5_0 < V5_1
module TableDefinition
diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake
index 1c7206aca4..f3e2df8786 100644
--- a/activerecord/lib/active_record/railties/databases.rake
+++ b/activerecord/lib/active_record/railties/databases.rake
@@ -77,6 +77,8 @@ db_namespace = namespace :db do
namespace :migrate do
# desc 'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).'
task redo: [:environment, :load_config] do
+ raise "Empty VERSION provided" if ENV["VERSION"] && ENV["VERSION"].empty?
+
if ENV["VERSION"]
db_namespace["migrate:down"].invoke
db_namespace["migrate:up"].invoke
@@ -91,16 +93,17 @@ db_namespace = namespace :db do
# desc 'Runs the "up" for a given migration VERSION.'
task up: [:environment, :load_config] do
+ raise "VERSION is required" if ENV["VERSION"] && ENV["VERSION"].empty?
+
version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
- raise "VERSION is required" unless version
ActiveRecord::Migrator.run(:up, ActiveRecord::Tasks::DatabaseTasks.migrations_paths, version)
db_namespace["_dump"].invoke
end
# desc 'Runs the "down" for a given migration VERSION.'
task down: [:environment, :load_config] do
+ raise "VERSION is required - To go down one migration, use db:rollback" if ENV["VERSION"] && ENV["VERSION"].empty?
version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
- raise "VERSION is required - To go down one migration, run db:rollback" unless version
ActiveRecord::Migrator.run(:down, ActiveRecord::Tasks::DatabaseTasks.migrations_paths, version)
db_namespace["_dump"].invoke
end
diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb
index 18ae10a652..fca914aedd 100644
--- a/activerecord/lib/active_record/relation/predicate_builder.rb
+++ b/activerecord/lib/active_record/relation/predicate_builder.rb
@@ -87,14 +87,19 @@ module ActiveRecord
binds = []
attributes.each do |column_name, value|
+ binds.concat(value.bound_attributes) if value.is_a?(Relation)
case
when value.is_a?(Hash) && !table.has_column?(column_name)
attrs, bvs = associated_predicate_builder(column_name).create_binds_for_hash(value)
result[column_name] = attrs
binds += bvs
- next
- when value.is_a?(Relation)
- binds += value.bound_attributes
+ when table.associated_with?(column_name)
+ # Find the foreign key when using queries such as:
+ # Post.where(author: author)
+ #
+ # For polymorphic relationships, find the foreign key and type:
+ # PriceEstimate.where(estimate_of: treasure)
+ result[column_name] = AssociationQueryHandler.value_for(table, column_name, value)
when value.is_a?(Range) && !table.type(column_name).respond_to?(:subtype)
first = value.begin
last = value.end
@@ -114,15 +119,6 @@ module ActiveRecord
binds << build_bind_param(column_name, value)
end
end
-
- # Find the foreign key when using queries such as:
- # Post.where(author: author)
- #
- # For polymorphic relationships, find the foreign key and type:
- # PriceEstimate.where(estimate_of: treasure)
- if table.associated_with?(column_name)
- result[column_name] = AssociationQueryHandler.value_for(table, column_name, value)
- end
end
[result, binds]
@@ -155,7 +151,6 @@ module ActiveRecord
end
def can_be_bound?(column_name, value)
- return if table.associated_with?(column_name)
case value
when Array, Range
table.type(column_name).respond_to?(:subtype)
diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb
index 82604a915f..46fa8a70a3 100644
--- a/activerecord/lib/active_record/tasks/database_tasks.rb
+++ b/activerecord/lib/active_record/tasks/database_tasks.rb
@@ -162,9 +162,11 @@ module ActiveRecord
end
def migrate
+ raise "Empty VERSION provided" if ENV["VERSION"] && ENV["VERSION"].empty?
+
verbose = ENV["VERBOSE"] ? ENV["VERBOSE"] == "true" : true
version = ENV["VERSION"] ? ENV["VERSION"].to_i : nil
- scope = ENV["SCOPE"]
+ scope = ENV["SCOPE"]
verbose_was, Migration.verbose = Migration.verbose, verbose
Migrator.migrate(migrations_paths, version) do |migration|
scope.blank? || scope == migration.scope
diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb
index 690deee508..45795fa287 100644
--- a/activerecord/lib/active_record/transactions.rb
+++ b/activerecord/lib/active_record/transactions.rb
@@ -123,7 +123,7 @@ module ActiveRecord
# # statement will cause a PostgreSQL error, even though the unique
# # constraint is no longer violated:
# Number.create(i: 1)
- # # => "PGError: ERROR: current transaction is aborted, commands
+ # # => "PG::Error: ERROR: current transaction is aborted, commands
# # ignored until end of transaction block"
# end
#
diff --git a/activerecord/test/cases/adapters/postgresql/bytea_test.rb b/activerecord/test/cases/adapters/postgresql/bytea_test.rb
index 505c297cd4..99175e8091 100644
--- a/activerecord/test/cases/adapters/postgresql/bytea_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/bytea_test.rb
@@ -89,6 +89,7 @@ class PostgresqlByteaTest < ActiveRecord::PostgreSQLTestCase
Thread.new do
other_conn = ActiveRecord::Base.connection
other_conn.execute("SET standard_conforming_strings = off")
+ other_conn.execute("SET escape_string_warning = off")
end.join
test_via_to_sql
diff --git a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb
index 0ff04bfa27..c5c540cebc 100644
--- a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb
@@ -1,111 +1,150 @@
require "cases/helper"
require "support/connection_helper"
-class PostgreSQLReferentialIntegrityTest < ActiveRecord::PostgreSQLTestCase
- self.use_transactional_tests = false
+if ActiveRecord::Base.connection.respond_to?(:supports_alter_constraint?) &&
+ ActiveRecord::Base.connection.supports_alter_constraint?
+ class PostgreSQLReferentialIntegrityWithAlterConstraintTest < ActiveRecord::PostgreSQLTestCase
+ self.use_transactional_tests = false
- include ConnectionHelper
+ include ConnectionHelper
- IS_REFERENTIAL_INTEGRITY_SQL = lambda do |sql|
- sql.match(/DISABLE TRIGGER ALL/) || sql.match(/ENABLE TRIGGER ALL/)
- end
+ IS_REFERENTIAL_INTEGRITY_SQL = lambda do |sql|
+ sql.match(/SET CONSTRAINTS ALL DEFERRED/)
+ end
- module MissingSuperuserPrivileges
- def execute(sql)
- if IS_REFERENTIAL_INTEGRITY_SQL.call(sql)
- super "BROKEN;" rescue nil # put transaction in broken state
- raise ActiveRecord::StatementInvalid, "PG::InsufficientPrivilege"
- else
- super
+ module ProgrammerMistake
+ def execute(sql)
+ if IS_REFERENTIAL_INTEGRITY_SQL.call(sql)
+ raise ArgumentError, "something is not right."
+ else
+ super
+ end
end
end
- end
- module ProgrammerMistake
- def execute(sql)
- if IS_REFERENTIAL_INTEGRITY_SQL.call(sql)
- raise ArgumentError, "something is not right."
- else
- super
+ def setup
+ @connection = ActiveRecord::Base.connection
+ end
+
+ def teardown
+ reset_connection
+ end
+
+ def test_errors_bubble_up
+ @connection.extend ProgrammerMistake
+
+ assert_raises ArgumentError do
+ @connection.disable_referential_integrity {}
end
end
end
+else
+ class PostgreSQLReferentialIntegrityWithDisableTriggerTest < ActiveRecord::PostgreSQLTestCase
+ self.use_transactional_tests = false
- def setup
- @connection = ActiveRecord::Base.connection
- end
+ include ConnectionHelper
- def teardown
- reset_connection
- if ActiveRecord::Base.connection.is_a?(MissingSuperuserPrivileges)
- raise "MissingSuperuserPrivileges patch was not removed"
+ IS_REFERENTIAL_INTEGRITY_SQL = lambda do |sql|
+ sql.match(/DISABLE TRIGGER ALL/) || sql.match(/ENABLE TRIGGER ALL/)
end
- end
- def test_should_reraise_invalid_foreign_key_exception_and_show_warning
- @connection.extend MissingSuperuserPrivileges
+ module MissingSuperuserPrivileges
+ def execute(sql)
+ if IS_REFERENTIAL_INTEGRITY_SQL.call(sql)
+ super "BROKEN;" rescue nil # put transaction in broken state
+ raise ActiveRecord::StatementInvalid, "PG::InsufficientPrivilege"
+ else
+ super
+ end
+ end
+ end
- warning = capture(:stderr) do
- e = assert_raises(ActiveRecord::InvalidForeignKey) do
- @connection.disable_referential_integrity do
- raise ActiveRecord::InvalidForeignKey, "Should be re-raised"
+ module ProgrammerMistake
+ def execute(sql)
+ if IS_REFERENTIAL_INTEGRITY_SQL.call(sql)
+ raise ArgumentError, "something is not right."
+ else
+ super
end
end
- assert_equal "Should be re-raised", e.message
end
- assert_match (/WARNING: Rails was not able to disable referential integrity/), warning
- assert_match (/cause: PG::InsufficientPrivilege/), warning
- end
- def test_does_not_print_warning_if_no_invalid_foreign_key_exception_was_raised
- @connection.extend MissingSuperuserPrivileges
+ def setup
+ @connection = ActiveRecord::Base.connection
+ end
- warning = capture(:stderr) do
- e = assert_raises(ActiveRecord::StatementInvalid) do
- @connection.disable_referential_integrity do
- raise ActiveRecord::StatementInvalid, "Should be re-raised"
+ def teardown
+ reset_connection
+ if ActiveRecord::Base.connection.is_a?(MissingSuperuserPrivileges)
+ raise "MissingSuperuserPrivileges patch was not removed"
+ end
+ end
+
+ def test_should_reraise_invalid_foreign_key_exception_and_show_warning
+ @connection.extend MissingSuperuserPrivileges
+
+ warning = capture(:stderr) do
+ e = assert_raises(ActiveRecord::InvalidForeignKey) do
+ @connection.disable_referential_integrity do
+ raise ActiveRecord::InvalidForeignKey, "Should be re-raised"
+ end
end
+ assert_equal "Should be re-raised", e.message
end
- assert_equal "Should be re-raised", e.message
+ assert_match (/WARNING: Rails was not able to disable referential integrity/), warning
+ assert_match (/cause: PG::InsufficientPrivilege/), warning
end
- assert warning.blank?, "expected no warnings but got:\n#{warning}"
- end
- def test_does_not_break_transactions
- @connection.extend MissingSuperuserPrivileges
+ def test_does_not_print_warning_if_no_invalid_foreign_key_exception_was_raised
+ @connection.extend MissingSuperuserPrivileges
- @connection.transaction do
- @connection.disable_referential_integrity do
- assert_transaction_is_not_broken
+ warning = capture(:stderr) do
+ e = assert_raises(ActiveRecord::StatementInvalid) do
+ @connection.disable_referential_integrity do
+ raise ActiveRecord::StatementInvalid, "Should be re-raised"
+ end
+ end
+ assert_equal "Should be re-raised", e.message
end
- assert_transaction_is_not_broken
+ assert warning.blank?, "expected no warnings but got:\n#{warning}"
end
- end
- def test_does_not_break_nested_transactions
- @connection.extend MissingSuperuserPrivileges
+ def test_does_not_break_transactions
+ @connection.extend MissingSuperuserPrivileges
- @connection.transaction do
- @connection.transaction(requires_new: true) do
+ @connection.transaction do
@connection.disable_referential_integrity do
assert_transaction_is_not_broken
end
+ assert_transaction_is_not_broken
end
- assert_transaction_is_not_broken
end
- end
- def test_only_catch_active_record_errors_others_bubble_up
- @connection.extend ProgrammerMistake
+ def test_does_not_break_nested_transactions
+ @connection.extend MissingSuperuserPrivileges
- assert_raises ArgumentError do
- @connection.disable_referential_integrity {}
+ @connection.transaction do
+ @connection.transaction(requires_new: true) do
+ @connection.disable_referential_integrity do
+ assert_transaction_is_not_broken
+ end
+ end
+ assert_transaction_is_not_broken
+ end
end
- end
- private
+ def test_only_catch_active_record_errors_others_bubble_up
+ @connection.extend ProgrammerMistake
- def assert_transaction_is_not_broken
- assert_equal 1, @connection.select_value("SELECT 1")
+ assert_raises ArgumentError do
+ @connection.disable_referential_integrity {}
+ end
end
+
+ private
+
+ def assert_transaction_is_not_broken
+ assert_equal 1, @connection.select_value("SELECT 1")
+ end
+ end
end
diff --git a/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb b/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb
index eb9978a898..146b619a4b 100644
--- a/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb
+++ b/activerecord/test/cases/adapters/postgresql/statement_pool_test.rb
@@ -3,13 +3,13 @@ require "cases/helper"
module ActiveRecord
module ConnectionAdapters
class PostgreSQLAdapter < AbstractAdapter
- class InactivePGconn
+ class InactivePgConnection
def query(*args)
- raise PGError
+ raise PG::Error
end
def status
- PGconn::CONNECTION_BAD
+ PG::CONNECTION_BAD
end
end
@@ -31,7 +31,7 @@ module ActiveRecord
end
def test_dealloc_does_not_raise_on_inactive_connection
- cache = StatementPool.new InactivePGconn.new, 10
+ cache = StatementPool.new InactivePgConnection.new, 10
cache["foo"] = "bar"
assert_nothing_raised { cache.clear }
end
diff --git a/activerecord/test/cases/associations/callbacks_test.rb b/activerecord/test/cases/associations/callbacks_test.rb
index 5fd2411f6f..7721bd5cd9 100644
--- a/activerecord/test/cases/associations/callbacks_test.rb
+++ b/activerecord/test/cases/associations/callbacks_test.rb
@@ -7,7 +7,7 @@ require "models/computer"
require "models/company"
class AssociationCallbacksTest < ActiveRecord::TestCase
- fixtures :posts, :authors, :projects, :developers
+ fixtures :posts, :authors, :author_addresses, :projects, :developers
def setup
@david = authors(:david)
diff --git a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
index ddb5c7a4aa..3638c87968 100644
--- a/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
+++ b/activerecord/test/cases/associations/cascaded_eager_loading_test.rb
@@ -12,7 +12,7 @@ require "models/vertex"
require "models/edge"
class CascadedEagerLoadingTest < ActiveRecord::TestCase
- fixtures :authors, :mixins, :companies, :posts, :topics, :accounts, :comments,
+ fixtures :authors, :author_addresses, :mixins, :companies, :posts, :topics, :accounts, :comments,
:categorizations, :people, :categories, :edges, :vertices
def test_eager_association_loading_with_cascaded_two_levels
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index 173063e068..e2f044c139 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -40,7 +40,7 @@ require "models/zine"
require "models/interest"
class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCase
- fixtures :authors, :posts, :comments
+ fixtures :authors, :author_addresses, :posts, :comments
def test_should_generate_valid_sql
author = authors(:david)
@@ -51,7 +51,7 @@ class HasManyAssociationsTestForReorderWithJoinDependency < ActiveRecord::TestCa
end
class HasManyAssociationsTestPrimaryKeys < ActiveRecord::TestCase
- fixtures :authors, :essays, :subscribers, :subscriptions, :people
+ fixtures :authors, :author_addresses, :essays, :subscribers, :subscriptions, :people
def test_custom_primary_key_on_new_record_should_fetch_with_query
subscriber = Subscriber.new(nick: "webster132")
@@ -100,7 +100,7 @@ end
class HasManyAssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :categories, :companies, :developers, :projects,
- :developers_projects, :topics, :authors, :comments,
+ :developers_projects, :topics, :authors, :author_addresses, :comments,
:posts, :readers, :taggings, :cars, :jobs, :tags,
:categorizations, :zines, :interests
diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb
index 38a729d2d4..28b883586d 100644
--- a/activerecord/test/cases/associations/has_one_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb
@@ -23,7 +23,7 @@ require "models/customer_carrier"
class HasOneThroughAssociationsTest < ActiveRecord::TestCase
fixtures :member_types, :members, :clubs, :memberships, :sponsors, :organizations, :minivans,
- :dashboards, :speedometers, :authors, :posts, :comments, :categories, :essays, :owners
+ :dashboards, :speedometers, :authors, :author_addresses, :posts, :comments, :categories, :essays, :owners
def setup
@member = members(:groucho)
diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb
index 7414869c8f..ddf5bc6f0b 100644
--- a/activerecord/test/cases/associations/inner_join_association_test.rb
+++ b/activerecord/test/cases/associations/inner_join_association_test.rb
@@ -10,7 +10,7 @@ require "models/tagging"
require "models/tag"
class InnerJoinAssociationTest < ActiveRecord::TestCase
- fixtures :authors, :essays, :posts, :comments, :categories, :categories_posts, :categorizations,
+ fixtures :authors, :author_addresses, :essays, :posts, :comments, :categories, :categories_posts, :categorizations,
:taggings, :tags
def test_construct_finder_sql_applies_aliases_tables_on_association_conditions
diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb
index a4345f3857..c078cef064 100644
--- a/activerecord/test/cases/associations/join_model_test.rb
+++ b/activerecord/test/cases/associations/join_model_test.rb
@@ -19,7 +19,7 @@ require "models/car"
class AssociationsJoinModelTest < ActiveRecord::TestCase
self.use_transactional_tests = false unless supports_savepoints?
- fixtures :posts, :authors, :categories, :categorizations, :comments, :tags, :taggings, :author_favorites, :vertices, :items, :books,
+ fixtures :posts, :authors, :author_addresses, :categories, :categorizations, :comments, :tags, :taggings, :author_favorites, :vertices, :items, :books,
# Reload edges table from fixtures as otherwise repeated test was failing
:edges
diff --git a/activerecord/test/cases/associations/left_outer_join_association_test.rb b/activerecord/test/cases/associations/left_outer_join_association_test.rb
index 42dbbad1c8..2aca3523c4 100644
--- a/activerecord/test/cases/associations/left_outer_join_association_test.rb
+++ b/activerecord/test/cases/associations/left_outer_join_association_test.rb
@@ -7,7 +7,7 @@ require "models/categorization"
require "models/person"
class LeftOuterJoinAssociationTest < ActiveRecord::TestCase
- fixtures :authors, :essays, :posts, :comments, :categorizations, :people
+ fixtures :authors, :essays, :posts, :comments, :categorizations, :people, :author_addresses
def test_construct_finder_sql_applies_aliases_tables_on_association_conditions
result = Author.left_outer_joins(:thinking_posts, :welcome_posts).to_a
diff --git a/activerecord/test/cases/associations/nested_through_associations_test.rb b/activerecord/test/cases/associations/nested_through_associations_test.rb
index dc26f6a383..67ff7355b3 100644
--- a/activerecord/test/cases/associations/nested_through_associations_test.rb
+++ b/activerecord/test/cases/associations/nested_through_associations_test.rb
@@ -24,7 +24,7 @@ require "models/membership"
require "models/essay"
class NestedThroughAssociationsTest < ActiveRecord::TestCase
- fixtures :authors, :books, :posts, :subscriptions, :subscribers, :tags, :taggings,
+ fixtures :authors, :author_addresses, :books, :posts, :subscriptions, :subscribers, :tags, :taggings,
:people, :readers, :references, :jobs, :ratings, :comments, :members, :member_details,
:member_types, :sponsors, :clubs, :organizations, :categories, :categories_posts,
:categorizations, :memberships, :essays
diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb
index 26056f6f63..4ab690bfc6 100644
--- a/activerecord/test/cases/associations_test.rb
+++ b/activerecord/test/cases/associations_test.rb
@@ -22,7 +22,7 @@ require "models/interest"
class AssociationsTest < ActiveRecord::TestCase
fixtures :accounts, :companies, :developers, :projects, :developers_projects,
- :computers, :people, :readers, :authors, :author_favorites
+ :computers, :people, :readers, :authors, :author_addresses, :author_favorites
def test_eager_loading_should_not_change_count_of_children
liquid = Liquid.create(name: "salty")
@@ -111,7 +111,7 @@ class AssociationsTest < ActiveRecord::TestCase
end
class AssociationProxyTest < ActiveRecord::TestCase
- fixtures :authors, :posts, :categorizations, :categories, :developers, :projects, :developers_projects
+ fixtures :authors, :author_addresses, :posts, :categorizations, :categories, :developers, :projects, :developers_projects
def test_push_does_not_load_target
david = authors(:david)
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index 979a59f566..ee1be09358 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -64,7 +64,7 @@ class LintTest < ActiveRecord::TestCase
end
class BasicsTest < ActiveRecord::TestCase
- fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, "warehouse-things", :authors, :categorizations, :categories, :posts
+ fixtures :topics, :companies, :developers, :projects, :computers, :accounts, :minimalistics, "warehouse-things", :authors, :author_addresses, :categorizations, :categories, :posts
def test_column_names_are_escaped
conn = ActiveRecord::Base.connection
diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb
index 98d202dd79..6032aa9250 100644
--- a/activerecord/test/cases/bind_parameter_test.rb
+++ b/activerecord/test/cases/bind_parameter_test.rb
@@ -3,36 +3,36 @@ require "models/topic"
require "models/author"
require "models/post"
-module ActiveRecord
- class BindParameterTest < ActiveRecord::TestCase
- fixtures :topics, :authors, :posts
-
- class LogListener
- attr_accessor :calls
-
- def initialize
- @calls = []
+if ActiveRecord::Base.connection.supports_statement_cache? &&
+ ActiveRecord::Base.connection.prepared_statements
+ module ActiveRecord
+ class BindParameterTest < ActiveRecord::TestCase
+ fixtures :topics, :authors, :author_addresses, :posts
+
+ class LogListener
+ attr_accessor :calls
+
+ def initialize
+ @calls = []
+ end
+
+ def call(*args)
+ calls << args
+ end
end
- def call(*args)
- calls << args
+ def setup
+ super
+ @connection = ActiveRecord::Base.connection
+ @subscriber = LogListener.new
+ @pk = Topic.columns_hash[Topic.primary_key]
+ @subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber)
end
- end
- def setup
- super
- @connection = ActiveRecord::Base.connection
- @subscriber = LogListener.new
- @pk = Topic.columns_hash[Topic.primary_key]
- @subscription = ActiveSupport::Notifications.subscribe("sql.active_record", @subscriber)
- end
-
- teardown do
- ActiveSupport::Notifications.unsubscribe(@subscription)
- end
+ def teardown
+ ActiveSupport::Notifications.unsubscribe(@subscription)
+ end
- if ActiveRecord::Base.connection.supports_statement_cache? &&
- ActiveRecord::Base.connection.prepared_statements
def test_bind_from_join_in_subquery
subquery = Author.joins(:thinking_posts).where(name: "David")
scope = Author.from(subquery, "authors").where(id: 1)
@@ -56,43 +56,48 @@ module ActiveRecord
assert message, "expected a message with binds"
end
- def test_logs_bind_vars_after_type_cast
+ def test_logs_binds_after_type_cast
binds = [Relation::QueryAttribute.new("id", "10", Type::Integer.new)]
- type_casted_binds = binds.map { |attr| type_cast(attr.value_for_database) }
- payload = {
- name: "SQL",
- sql: "select * from topics where id = ?",
- binds: binds,
- type_casted_binds: type_casted_binds
- }
- event = ActiveSupport::Notifications::Event.new(
- "foo",
- Time.now,
- Time.now,
- 123,
- payload)
-
- logger = Class.new(ActiveRecord::LogSubscriber) {
- attr_reader :debugs
- def initialize
- super
- @debugs = []
- end
-
- def debug(str)
- @debugs << str
- end
- }.new
-
- logger.sql event
- assert_match([[@pk.name, 10]].inspect, logger.debugs.first)
+ assert_logs_binds(binds)
end
- private
-
- def type_cast(value)
- ActiveRecord::Base.connection.type_cast(value)
+ def test_logs_legacy_binds_after_type_cast
+ binds = [[@pk, "10"]]
+ assert_logs_binds(binds)
end
+
+ private
+ def assert_logs_binds(binds)
+ payload = {
+ name: "SQL",
+ sql: "select * from topics where id = ?",
+ binds: binds,
+ type_casted_binds: @connection.type_casted_binds(binds)
+ }
+
+ event = ActiveSupport::Notifications::Event.new(
+ "foo",
+ Time.now,
+ Time.now,
+ 123,
+ payload)
+
+ logger = Class.new(ActiveRecord::LogSubscriber) {
+ attr_reader :debugs
+
+ def initialize
+ super
+ @debugs = []
+ end
+
+ def debug(str)
+ @debugs << str
+ end
+ }.new
+
+ logger.sql(event)
+ assert_match([[@pk.name, 10]].inspect, logger.debugs.first)
+ end
end
end
end
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index 51133e9495..3720b0cc1a 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -766,7 +766,7 @@ end
class FasterFixturesTest < ActiveRecord::TestCase
self.use_transactional_tests = false
- fixtures :categories, :authors
+ fixtures :categories, :authors, :author_addresses
def load_extra_fixture(name)
fixture = create_fixtures(name).first
diff --git a/activerecord/test/cases/json_serialization_test.rb b/activerecord/test/cases/json_serialization_test.rb
index 5a1d066aef..9b4b61b16e 100644
--- a/activerecord/test/cases/json_serialization_test.rb
+++ b/activerecord/test/cases/json_serialization_test.rb
@@ -168,7 +168,7 @@ class JsonSerializationTest < ActiveRecord::TestCase
end
class DatabaseConnectedJsonEncodingTest < ActiveRecord::TestCase
- fixtures :authors, :posts, :comments, :tags, :taggings
+ fixtures :authors, :author_addresses, :posts, :comments, :tags, :taggings
include JsonSerializationHelpers
diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb
index a93061b516..24b678310d 100644
--- a/activerecord/test/cases/readonly_test.rb
+++ b/activerecord/test/cases/readonly_test.rb
@@ -10,7 +10,7 @@ require "models/person"
require "models/ship"
class ReadOnlyTest < ActiveRecord::TestCase
- fixtures :authors, :posts, :comments, :developers, :projects, :developers_projects, :people, :readers
+ fixtures :authors, :author_addresses, :posts, :comments, :developers, :projects, :developers_projects, :people, :readers
def test_cant_save_readonly_record
dev = Developer.find(1)
diff --git a/activerecord/test/cases/relation/merging_test.rb b/activerecord/test/cases/relation/merging_test.rb
index 278dac8171..9e95149ede 100644
--- a/activerecord/test/cases/relation/merging_test.rb
+++ b/activerecord/test/cases/relation/merging_test.rb
@@ -8,7 +8,7 @@ require "models/project"
require "models/rating"
class RelationMergingTest < ActiveRecord::TestCase
- fixtures :developers, :comments, :authors, :posts
+ fixtures :developers, :comments, :authors, :author_addresses, :posts
def test_relation_merging
devs = Developer.where("salary >= 80000").merge(Developer.limit(2)).merge(Developer.order("id ASC").where("id < 3"))
@@ -114,7 +114,7 @@ class RelationMergingTest < ActiveRecord::TestCase
end
class MergingDifferentRelationsTest < ActiveRecord::TestCase
- fixtures :posts, :authors, :developers
+ fixtures :posts, :authors, :author_addresses, :developers
test "merging where relations" do
hello_by_bob = Post.where(body: "hello").joins(:author).
diff --git a/activerecord/test/cases/relation/where_test.rb b/activerecord/test/cases/relation/where_test.rb
index ed8ffddcf5..c7b2ac90fb 100644
--- a/activerecord/test/cases/relation/where_test.rb
+++ b/activerecord/test/cases/relation/where_test.rb
@@ -15,7 +15,7 @@ require "models/vertex"
module ActiveRecord
class WhereTest < ActiveRecord::TestCase
- fixtures :posts, :edges, :authors, :binaries, :essays, :cars, :treasures, :price_estimates
+ fixtures :posts, :edges, :authors, :author_addresses, :binaries, :essays, :cars, :treasures, :price_estimates
def test_where_copies_bind_params
author = authors(:david)
diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb
index 1241bb54a4..5fb32270b7 100644
--- a/activerecord/test/cases/relation_test.rb
+++ b/activerecord/test/cases/relation_test.rb
@@ -6,7 +6,7 @@ require "models/rating"
module ActiveRecord
class RelationTest < ActiveRecord::TestCase
- fixtures :posts, :comments, :authors
+ fixtures :posts, :comments, :authors, :author_addresses
FakeKlass = Struct.new(:table_name, :name) do
extend ActiveRecord::Delegation::DelegateCache
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index e17cb1795e..8c06b1537a 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -22,7 +22,7 @@ require "models/categorization"
require "models/edge"
class RelationTest < ActiveRecord::TestCase
- fixtures :authors, :topics, :entrants, :developers, :companies, :developers_projects, :accounts, :categories, :categorizations, :posts, :comments,
+ fixtures :authors, :author_addresses, :topics, :entrants, :developers, :companies, :developers_projects, :accounts, :categories, :categorizations, :posts, :comments,
:tags, :taggings, :cars, :minivans
class TopicWithCallbacks < ActiveRecord::Base
diff --git a/activerecord/test/cases/scoping/relation_scoping_test.rb b/activerecord/test/cases/scoping/relation_scoping_test.rb
index a1ae57fdbb..3fbff7664b 100644
--- a/activerecord/test/cases/scoping/relation_scoping_test.rb
+++ b/activerecord/test/cases/scoping/relation_scoping_test.rb
@@ -10,7 +10,7 @@ require "models/person"
require "models/reference"
class RelationScopingTest < ActiveRecord::TestCase
- fixtures :authors, :developers, :projects, :comments, :posts, :developers_projects
+ fixtures :authors, :author_addresses, :developers, :projects, :comments, :posts, :developers_projects
setup do
developers(:david)
@@ -238,7 +238,7 @@ class RelationScopingTest < ActiveRecord::TestCase
end
class NestedRelationScopingTest < ActiveRecord::TestCase
- fixtures :authors, :developers, :projects, :comments, :posts
+ fixtures :authors, :author_addresses, :developers, :projects, :comments, :posts
def test_merge_options
Developer.where("salary = 80000").scoping do
diff --git a/activerecord/test/cases/tasks/database_tasks_test.rb b/activerecord/test/cases/tasks/database_tasks_test.rb
index 5653fd83fd..baa41a3a47 100644
--- a/activerecord/test/cases/tasks/database_tasks_test.rb
+++ b/activerecord/test/cases/tasks/database_tasks_test.rb
@@ -350,6 +350,14 @@ module ActiveRecord
ENV["VERBOSE"], ENV["VERSION"] = verbose, version
end
+ def test_migrate_raise_error_on_empty_version
+ version = ENV["VERSION"]
+ ENV["VERSION"] = ""
+ assert_raise(RuntimeError, "Empty VERSION provided") { ActiveRecord::Tasks::DatabaseTasks.migrate }
+ ensure
+ ENV["VERSION"] = version
+ end
+
def test_migrate_clears_schema_cache_afterward
ActiveRecord::Base.expects(:clear_cache!)
ActiveRecord::Tasks::DatabaseTasks.migrate
diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb
index 111495c481..5c6d78b574 100644
--- a/activerecord/test/cases/transactions_test.rb
+++ b/activerecord/test/cases/transactions_test.rb
@@ -10,7 +10,7 @@ require "models/movie"
class TransactionTest < ActiveRecord::TestCase
self.use_transactional_tests = false
- fixtures :topics, :developers, :authors, :posts
+ fixtures :topics, :developers, :authors, :author_addresses, :posts
def setup
@first, @second = Topic.find(1, 2).sort_by(&:id)
diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb
index 1571b31329..ab0e67cd9d 100644
--- a/activerecord/test/cases/yaml_serialization_test.rb
+++ b/activerecord/test/cases/yaml_serialization_test.rb
@@ -5,7 +5,7 @@ require "models/post"
require "models/author"
class YamlSerializationTest < ActiveRecord::TestCase
- fixtures :topics, :authors, :posts
+ fixtures :topics, :authors, :author_addresses, :posts
def test_to_yaml_with_time_with_zone_should_not_raise_exception
with_timezone_config aware_attributes: true, zone: "Pacific Time (US & Canada)" do
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index d12cbc34dd..6f99155199 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,628 +1 @@
-* Fixed bug in `DateAndTime::Compatibility#to_time` that caused it to
- raise `RuntimeError: can't modify frozen Time` when called on any frozen `Time`.
- Properly pass through the frozen `Time` or `ActiveSupport::TimeWithZone` object
- when calling `#to_time`.
-
- *Kevin McPhillips* & *Andrew White*
-
-* Remove implicit coercion deprecation of durations
-
- In #28204 we deprecated implicit conversion of durations to a numeric which
- represented the number of seconds in the duration because of unwanted side
- effects with calculations on durations and dates. This unfortunately had
- the side effect of forcing a explicit cast when configuring third-party
- libraries like expiration in Redis, e.g:
-
- redis.expire("foo", 5.minutes)
-
- To work around this we've removed the deprecation and added a private class
- that wraps the numeric and can perform calculation involving durations and
- ensure that they remain a duration irrespective of the order of operations.
-
- *Andrew White*
-
-* Update `titleize` regex to allow apostrophes
-
- In 4b685aa the regex in `titleize` was updated to not match apostrophes to
- better reflect the nature of the transformation. Unfortunately, this had the
- side effect of breaking capitalization on the first word of a sub-string, e.g:
-
- >> "This was 'fake news'".titleize
- => "This Was 'fake News'"
-
- This is fixed by extending the look-behind to also check for a word
- character on the other side of the apostrophe.
-
- Fixes #28312.
-
- *Andrew White*
-
-* Add `rfc3339` aliases to `xmlschema` for `Time` and `ActiveSupport::TimeWithZone`
-
- For naming consistency when using the RFC 3339 profile of ISO 8601 in applications.
-
- *Andrew White*
-
-* Add `Time.rfc3339` parsing method
-
- `Time.xmlschema` and consequently its alias `iso8601` accepts timestamps
- without a offset in contravention of the RFC 3339 standard. This method
- enforces that constraint and raises an `ArgumentError` if it doesn't.
-
- *Andrew White*
-
-* Add `ActiveSupport::TimeZone.rfc3339` parsing method
-
- Previously, there was no way to get a RFC 3339 timestamp into a specific
- timezone without either using `parse` or chaining methods. The new method
- allows parsing directly into the timezone, e.g:
-
- >> Time.zone = "Hawaii"
- => "Hawaii"
- >> Time.zone.rfc3339("1999-12-31T14:00:00Z")
- => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
- This new method has stricter semantics than the current `parse` method,
- and will raise an `ArgumentError` instead of returning nil, e.g:
-
- >> Time.zone = "Hawaii"
- => "Hawaii"
- >> Time.zone.rfc3339("foobar")
- ArgumentError: invalid date
- >> Time.zone.parse("foobar")
- => nil
-
- It will also raise an `ArgumentError` when either the time or offset
- components are missing, e.g:
-
- >> Time.zone = "Hawaii"
- => "Hawaii"
- >> Time.zone.rfc3339("1999-12-31")
- ArgumentError: invalid date
- >> Time.zone.rfc3339("1999-12-31T14:00:00")
- ArgumentError: invalid date
-
- *Andrew White*
-
-* Add `ActiveSupport::TimeZone.iso8601` parsing method
-
- Previously, there was no way to get a ISO 8601 timestamp into a specific
- timezone without either using `parse` or chaining methods. The new method
- allows parsing directly into the timezone, e.g:
-
- >> Time.zone = "Hawaii"
- => "Hawaii"
- >> Time.zone.iso8601("1999-12-31T14:00:00Z")
- => Fri, 31 Dec 1999 14:00:00 HST -10:00
-
- If the timestamp is a ISO 8601 date (YYYY-MM-DD), then the time is set
- to midnight, e.g:
-
- >> Time.zone = "Hawaii"
- => "Hawaii"
- >> Time.zone.iso8601("1999-12-31")
- => Fri, 31 Dec 1999 00:00:00 HST -10:00
-
- This new method has stricter semantics than the current `parse` method,
- and will raise an `ArgumentError` instead of returning nil, e.g:
-
- >> Time.zone = "Hawaii"
- => "Hawaii"
- >> Time.zone.iso8601("foobar")
- ArgumentError: invalid date
- >> Time.zone.parse("foobar")
- => nil
-
- *Andrew White*
-
-* Deprecate implicit coercion of `ActiveSupport::Duration`
-
- Currently `ActiveSupport::Duration` implicitly converts to a seconds
- value when used in a calculation except for the explicit examples of
- addition and subtraction where the duration is the receiver, e.g:
-
- >> 2 * 1.day
- => 172800
-
- This results in lots of confusion especially when using durations
- with dates because adding/subtracting a value from a date treats
- integers as a day and not a second, e.g:
-
- >> Date.today
- => Wed, 01 Mar 2017
- >> Date.today + 2 * 1.day
- => Mon, 10 Apr 2490
-
- To fix this we're implementing `coerce` so that we can provide a
- deprecation warning with the intent of removing the implicit coercion
- in Rails 5.2, e.g:
-
- >> 2 * 1.day
- DEPRECATION WARNING: Implicit coercion of ActiveSupport::Duration
- to a Numeric is deprecated and will raise a TypeError in Rails 5.2.
- => 172800
-
- In Rails 5.2 it will raise `TypeError`, e.g:
-
- >> 2 * 1.day
- TypeError: ActiveSupport::Duration can't be coerced into Integer
-
- This is the same behavior as with other types in Ruby, e.g:
-
- >> 2 * "foo"
- TypeError: String can't be coerced into Integer
- >> "foo" * 2
- => "foofoo"
-
- As part of this deprecation add `*` and `/` methods to `AS::Duration`
- so that calculations that keep the duration as the receiver work
- correctly whether the final receiver is a `Date` or `Time`, e.g:
-
- >> Date.today
- => Wed, 01 Mar 2017
- >> Date.today + 1.day * 2
- => Fri, 03 Mar 2017
-
- Fixes #27457.
-
- *Andrew White*
-
-* Update `DateTime#change` to support `:usec` and `:nsec` options.
-
- Adding support for these options now allows us to update the `DateTime#end_of`
- methods to match the equivalent `Time#end_of` methods, e.g:
-
- datetime = DateTime.now.end_of_day
- datetime.nsec == 999999999 # => true
-
- Fixes #21424.
-
- *Dan Moore*, *Andrew White*
-
-* Add `ActiveSupport::Duration#before` and `#after` as aliases for `#until` and `#since`
-
- These read more like English and require less mental gymnastics to read and write.
-
- Before:
-
- 2.weeks.since(customer_start_date)
- 5.days.until(today)
-
- After:
-
- 2.weeks.after(customer_start_date)
- 5.days.before(today)
-
- *Nick Johnstone*
-
-* Soft-deprecated the top-level `HashWithIndifferentAccess` constant.
- `ActiveSupport::HashWithIndifferentAccess` should be used instead.
-
- Fixes #28157.
-
- *Robin Dupret*
-
-* In Core Extensions, make `MarshalWithAutoloading#load` pass through the second, optional
- argument for `Marshal#load( source [, proc] )`. This way we don't have to do
- `Marshal.method(:load).super_method.call(source, proc)` just to be able to pass a proc.
-
- *Jeff Latz*
-
-* `ActiveSupport::Gzip.decompress` now checks checksum and length in footer.
-
- *Dylan Thacker-Smith*
-
-
-## Rails 5.1.0.beta1 (February 23, 2017) ##
-
-* Cache `ActiveSupport::TimeWithZone#to_datetime` before freezing.
-
- *Adam Rice*
-
-* Deprecate `ActiveSupport.halt_callback_chains_on_return_false`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated behavior that halts callbacks when the return is false.
-
- *Rafael Mendonça França*
-
-* Deprecate passing string to `:if` and `:unless` conditional options
- on `set_callback` and `skip_callback`.
-
- *Ryuta Kamizono*
-
-* Raise `ArgumentError` when passing string to define callback.
-
- *Ryuta Kamizono*
-
-* Updated Unicode version to 9.0.0
-
- Now we can handle new emojis such like "👩‍👩‍👧‍👦" ("\u{1F469}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}").
-
- version 8.0.0
-
- "👩‍👩‍👧‍👦".mb_chars.grapheme_length # => 4
- "👩‍👩‍👧‍👦".mb_chars.reverse # => "👦👧‍👩‍👩‍"
-
- version 9.0.0
-
- "👩‍👩‍👧‍👦".mb_chars.grapheme_length # => 1
- "👩‍👩‍👧‍👦".mb_chars.reverse # => "👩‍👩‍👧‍👦"
-
- *Fumiaki MATSUSHIMA*
-
-* Changed `ActiveSupport::Inflector#transliterate` to raise `ArgumentError` when it receives
- anything except a string.
-
- *Kevin McPhillips*
-
-* Fixed bugs that `StringInquirer#respond_to_missing?` and
- `ArrayInquirer#respond_to_missing?` do not fallback to `super`.
-
- *Akira Matsuda*
-
-* Fix inconsistent results when parsing large durations and constructing durations from code
-
- ActiveSupport::Duration.parse('P3Y') == 3.years # It should be true
-
- Duration parsing made independent from any moment of time:
- Fixed length in seconds is assigned to each duration part during parsing.
-
- Changed duration of months and years in seconds to more accurate and logical:
-
- 1. The value of 365.2425 days in Gregorian year is more accurate
- as it accounts for every 400th non-leap year.
-
- 2. Month's length is bound to year's duration, which makes
- sensible comparisons like `12.months == 1.year` to be `true`
- and nonsensical ones like `30.days == 1.month` to be `false`.
-
- Calculations on times and dates with durations shouldn't be affected as
- duration's numeric value isn't used in calculations, only parts are used.
-
- Methods on `Numeric` like `2.days` now use these predefined durations
- to avoid duplication of duration constants through the codebase and
- eliminate creation of intermediate durations.
-
- *Andrey Novikov*, *Andrew White*
-
-* Change return value of `Rational#duplicable?`, `ComplexClass#duplicable?`
- to false.
-
- *utilum*
-
-* Change return value of `NilClass#duplicable?`, `FalseClass#duplicable?`,
- `TrueClass#duplicable?`, `Symbol#duplicable?` and `Numeric#duplicable?`
- to true with Ruby 2.4+. These classes can dup with Ruby 2.4+.
-
- *Yuji Yaginuma*
-
-* Remove deprecated class `ActiveSupport::Concurrency::Latch`.
-
- *Andrew White*
-
-* Remove deprecated separator argument from `parameterize`.
-
- *Andrew White*
-
-* Remove deprecated method `Numeric#to_formatted_s`.
-
- *Andrew White*
-
-* Remove deprecated method `alias_method_chain`.
-
- *Andrew White*
-
-* Remove deprecated constant `MissingSourceFile`.
-
- *Andrew White*
-
-* Remove deprecated methods `Module.qualified_const_defined?`,
- `Module.qualified_const_get` and `Module.qualified_const_set`.
-
- *Andrew White*
-
-* Remove deprecated `:prefix` option from `number_to_human_size`.
-
- *Andrew White*
-
-* Remove deprecated method `ActiveSupport::HashWithIndifferentAccess.new_from_hash_copying_default`.
-
- *Andrew White*
-
-* Remove deprecated file `active_support/core_ext/time/marshal.rb`.
-
- *Andrew White*
-
-* Remove deprecated file `active_support/core_ext/struct.rb`.
-
- *Andrew White*
-
-* Remove deprecated file `active_support/core_ext/module/method_transplanting.rb`.
-
- *Andrew White*
-
-* Remove deprecated method `Module.local_constants`.
-
- *Andrew White*
-
-* Remove deprecated file `active_support/core_ext/kernel/debugger.rb`.
-
- *Andrew White*
-
-* Remove deprecated method `ActiveSupport::Cache::Store#namespaced_key`.
-
- *Andrew White*
-
-* Remove deprecated method `ActiveSupport::Cache::Strategy::LocalCache::LocalStore#set_cache_value`.
-
- *Andrew White*
-
-* Remove deprecated method `ActiveSupport::Cache::MemCacheStore#escape_key`.
-
- *Andrew White*
-
-* Remove deprecated method `ActiveSupport::Cache::FileStore#key_file_path`.
-
- *Andrew White*
-
-* Ensure duration parsing is consistent across DST changes.
-
- Previously `ActiveSupport::Duration.parse` used `Time.current` and
- `Time#advance` to calculate the number of seconds in the duration
- from an arbitrary collection of parts. However as `advance` tries to
- be consistent across DST boundaries this meant that either the
- duration was shorter or longer depending on the time of year.
-
- This was fixed by using an absolute reference point in UTC which
- isn't subject to DST transitions. An arbitrary date of Jan 1st, 2000
- was chosen for no other reason that it seemed appropriate.
-
- Additionally, duration parsing should now be marginally faster as we
- are no longer creating instances of `ActiveSupport::TimeWithZone`
- every time we parse a duration string.
-
- Fixes #26941.
-
- *Andrew White*
-
-* Use `Hash#compact` and `Hash#compact!` from Ruby 2.4. Old Ruby versions
- will continue to get these methods from Active Support as before.
-
- *Prathamesh Sonpatki*
-
-* Fix `ActiveSupport::TimeZone#strptime`.
- Support for timestamps in format of seconds (%s) and milliseconds (%Q).
-
- Fixes #26840.
-
- *Lev Denisov*
-
-* Fix `DateAndTime::Calculations#copy_time_to`. Copy `nsec` instead of `usec`.
-
- Jumping forward or backward between weeks now preserves nanosecond digits.
-
- *Josua Schmid*
-
-* Fix `ActiveSupport::TimeWithZone#in` across DST boundaries.
-
- Previously calls to `in` were being sent to the non-DST aware
- method `Time#since` via `method_missing`. It is now aliased to
- the DST aware `ActiveSupport::TimeWithZone#+` which handles
- transitions across DST boundaries, e.g:
-
- Time.zone = "US/Eastern"
-
- t = Time.zone.local(2016,11,6,1)
- # => Sun, 06 Nov 2016 01:00:00 EDT -05:00
-
- t.in(1.hour)
- # => Sun, 06 Nov 2016 01:00:00 EST -05:00
-
- Fixes #26580.
-
- *Thomas Balthazar*
-
-* Remove unused parameter `options = nil` for `#clear` of
- `ActiveSupport::Cache::Strategy::LocalCache::LocalStore` and
- `ActiveSupport::Cache::Strategy::LocalCache`.
-
- *Yosuke Kabuto*
-
-* Fix `thread_mattr_accessor` subclass no longer overwrites parent.
-
- Assigning a value to a subclass using `thread_mattr_accessor` no
- longer changes the value of the parent class. This brings the
- behavior inline with the documentation.
-
- Given:
-
- class Account
- thread_mattr_accessor :user
- end
-
- class Customer < Account
- end
-
- Account.user = "DHH"
- Customer.user = "Rafael"
-
- Before:
-
- Account.user # => "Rafael"
-
- After:
-
- Account.user # => "DHH"
-
- *Shinichi Maeshima*
-
-* Since weeks are no longer converted to days, add `:weeks` to the list of
- parts that `ActiveSupport::TimeWithZone` will recognize as possibly being
- of variable duration to take account of DST transitions.
-
- Fixes #26039.
-
- *Andrew White*
-
-* Defines `Regexp.match?` for Ruby versions prior to 2.4. The predicate
- has the same interface, but it does not have the performance boost. Its
- purpose is to be able to write 2.4 compatible code.
-
- *Xavier Noria*
-
-* Allow `MessageEncryptor` to take advantage of authenticated encryption modes.
-
- AEAD modes like `aes-256-gcm` provide both confidentiality and data
- authenticity, eliminating the need to use `MessageVerifier` to check if the
- encrypted data has been tampered with. This speeds up encryption/decryption
- and results in shorter cipher text.
-
- *Bart de Water*
-
-* Introduce `assert_changes` and `assert_no_changes`.
-
- `assert_changes` is a more general `assert_difference` that works with any
- value.
-
- assert_changes 'Error.current', from: nil, to: 'ERR' do
- expected_bad_operation
- end
-
- Can be called with strings, to be evaluated in the binding (context) of
- the block given to the assertion, or a lambda.
-
- assert_changes -> { Error.current }, from: nil, to: 'ERR' do
- expected_bad_operation
- end
-
- The `from` and `to` arguments are compared with the case operator (`===`).
-
- assert_changes 'Error.current', from: nil, to: Error do
- expected_bad_operation
- end
-
- This is pretty useful, if you need to loosely compare a value. For example,
- you need to test a token has been generated and it has that many random
- characters.
-
- user = User.start_registration
- assert_changes 'user.token', to: /\w{32}/ do
- user.finish_registration
- end
-
- *Genadi Samokovarov*
-
-* Fix `ActiveSupport::TimeZone#strptime`. Now raises `ArgumentError` when the
- given time doesn't match the format. The error is the same as the one given
- by Ruby's `Date.strptime`. Previously it raised
- `NoMethodError: undefined method empty? for nil:NilClass.` due to a bug.
-
- Fixes #25701.
-
- *John Gesimondo*
-
-* `travel/travel_to` travel time helpers, now raise on nested calls,
- as this can lead to confusing time stubbing.
-
- Instead of:
-
- travel_to 2.days.from_now do
- # 2 days from today
- travel_to 3.days.from_now do
- # 5 days from today
- end
- end
-
- preferred way to achieve above is:
-
- travel 2.days do
- # 2 days from today
- end
-
- travel 5.days do
- # 5 days from today
- end
-
- *Vipul A M*
-
-* Support parsing JSON time in ISO8601 local time strings in
- `ActiveSupport::JSON.decode` when `parse_json_times` is enabled.
- Strings in the format of `YYYY-MM-DD hh:mm:ss` (without a `Z` at
- the end) will be parsed in the local timezone (`Time.zone`). In
- addition, date strings (`YYYY-MM-DD`) are now parsed into `Date`
- objects.
-
- *Grzegorz Witek*
-
-* Fixed `ActiveSupport::Logger.broadcast` so that calls to `#silence` now
- properly delegate to all loggers. Silencing now properly suppresses logging
- to both the log and the console.
-
- *Kevin McPhillips*
-
-* Remove deprecated arguments in `assert_nothing_raised`.
-
- *Rafel Mendonça França*
-
-* `Date.to_s` doesn't produce too many spaces. For example, `to_s(:short)`
- will now produce `01 Feb` instead of ` 1 Feb`.
-
- Fixes #25251.
-
- *Sean Griffin*
-
-* Introduce `Module#delegate_missing_to`.
-
- When building a decorator, a common pattern emerges:
-
- class Partition
- def initialize(first_event)
- @events = [ first_event ]
- end
-
- def people
- if @events.first.detail.people.any?
- @events.collect { |e| Array(e.detail.people) }.flatten.uniq
- else
- @events.collect(&:creator).uniq
- end
- end
-
- private
- def respond_to_missing?(name, include_private = false)
- @events.respond_to?(name, include_private)
- end
-
- def method_missing(method, *args, &block)
- @events.send(method, *args, &block)
- end
- end
-
- With `Module#delegate_missing_to`, the above is condensed to:
-
- class Partition
- delegate_missing_to :@events
-
- def initialize(first_event)
- @events = [ first_event ]
- end
-
- def people
- if @events.first.detail.people.any?
- @events.collect { |e| Array(e.detail.people) }.flatten.uniq
- else
- @events.collect(&:creator).uniq
- end
- end
- end
-
- *Genadi Samokovarov*, *DHH*
-
-* Rescuable: If a handler doesn't match the exception, check for handlers
- matching the exception's cause.
-
- *Jeremy Daer*
-
-Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/activesupport/CHANGELOG.md) for previous changes.
+Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/activesupport/CHANGELOG.md) for previous changes.
diff --git a/activesupport/lib/active_support/core_ext/object/duplicable.rb b/activesupport/lib/active_support/core_ext/object/duplicable.rb
index ea81df2bd8..b028df97ee 100644
--- a/activesupport/lib/active_support/core_ext/object/duplicable.rb
+++ b/activesupport/lib/active_support/core_ext/object/duplicable.rb
@@ -106,8 +106,8 @@ require "bigdecimal"
class BigDecimal
# BigDecimals are duplicable:
#
- # BigDecimal.new("1.2").duplicable? # => true
- # BigDecimal.new("1.2").dup # => #<BigDecimal:...,'0.12E1',18(18)>
+ # BigDecimal.new("1.2").duplicable? # => true
+ # BigDecimal.new("1.2").dup # => #<BigDecimal:...,'0.12E1',18(18)>
def duplicable?
true
end
@@ -124,21 +124,31 @@ class Method
end
class Complex
- # Complexes are not duplicable:
- #
- # Complex(1).duplicable? # => false
- # Complex(1).dup # => TypeError: can't copy Complex
- def duplicable?
- false
+ begin
+ Complex(1).dup
+ rescue TypeError
+
+ # Complexes are not duplicable:
+ #
+ # Complex(1).duplicable? # => false
+ # Complex(1).dup # => TypeError: can't copy Complex
+ def duplicable?
+ false
+ end
end
end
class Rational
- # Rationals are not duplicable:
- #
- # Rational(1).duplicable? # => false
- # Rational(1).dup # => TypeError: can't copy Rational
- def duplicable?
- false
+ begin
+ Rational(1).dup
+ rescue TypeError
+
+ # Rationals are not duplicable:
+ #
+ # Rational(1).duplicable? # => false
+ # Rational(1).dup # => TypeError: can't copy Rational
+ def duplicable?
+ false
+ end
end
end
diff --git a/activesupport/lib/active_support/deprecation.rb b/activesupport/lib/active_support/deprecation.rb
index 191e582de8..72c74e966a 100644
--- a/activesupport/lib/active_support/deprecation.rb
+++ b/activesupport/lib/active_support/deprecation.rb
@@ -15,6 +15,7 @@ module ActiveSupport
require "active_support/deprecation/instance_delegator"
require "active_support/deprecation/behaviors"
require "active_support/deprecation/reporting"
+ require "active_support/deprecation/constant_accessor"
require "active_support/deprecation/method_wrappers"
require "active_support/deprecation/proxy_wrappers"
require "active_support/core_ext/module/deprecation"
@@ -32,7 +33,7 @@ module ActiveSupport
# and the second is a library name
#
# ActiveSupport::Deprecation.new('2.0', 'MyLibrary')
- def initialize(deprecation_horizon = "5.2", gem_name = "Rails")
+ def initialize(deprecation_horizon = "5.3", gem_name = "Rails")
self.gem_name = gem_name
self.deprecation_horizon = deprecation_horizon
# By default, warnings are not silenced and debugging is off.
diff --git a/activesupport/lib/active_support/deprecation/constant_accessor.rb b/activesupport/lib/active_support/deprecation/constant_accessor.rb
new file mode 100644
index 0000000000..2b19de365f
--- /dev/null
+++ b/activesupport/lib/active_support/deprecation/constant_accessor.rb
@@ -0,0 +1,50 @@
+require "active_support/inflector/methods"
+
+module ActiveSupport
+ class Deprecation
+ # DeprecatedConstantAccessor transforms a constant into a deprecated one by
+ # hooking +const_missing+.
+ #
+ # It takes the names of an old (deprecated) constant and of a new constant
+ # (both in string form) and optionally a deprecator. The deprecator defaults
+ # to +ActiveSupport::Deprecator+ if none is specified.
+ #
+ # The deprecated constant now returns the same object as the new one rather
+ # than a proxy object, so it can be used transparently in +rescue+ blocks
+ # etc.
+ #
+ # PLANETS = %w(mercury venus earth mars jupiter saturn uranus neptune pluto)
+ #
+ # (In a later update, the original implementation of `PLANETS` has been removed.)
+ #
+ # PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune)
+ # include ActiveSupport::Deprecation::DeprecatedConstantAccessor
+ # deprecate_constant 'PLANETS', 'PLANETS_POST_2006'
+ #
+ # PLANETS.map { |planet| planet.capitalize }
+ # # => DEPRECATION WARNING: PLANETS is deprecated! Use PLANETS_POST_2006 instead.
+ # (Backtrace information…)
+ # ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"]
+ module DeprecatedConstantAccessor
+ def self.included(base)
+ extension = Module.new do
+ def const_missing(missing_const_name)
+ if class_variable_defined?(:@@_deprecated_constants)
+ if (replacement = class_variable_get(:@@_deprecated_constants)[missing_const_name.to_s])
+ replacement[:deprecator].warn(replacement[:message] || "#{name}::#{missing_const_name} is deprecated! Use #{replacement[:new]} instead.", caller_locations)
+ return ActiveSupport::Inflector.constantize(replacement[:new].to_s)
+ end
+ end
+ super
+ end
+
+ def deprecate_constant(const_name, new_constant, message: nil, deprecator: ActiveSupport::Deprecation.instance)
+ class_variable_set(:@@_deprecated_constants, {}) unless class_variable_defined?(:@@_deprecated_constants)
+ class_variable_get(:@@_deprecated_constants)[const_name.to_s] = { new: new_constant, message: message, deprecator: deprecator }
+ end
+ end
+ base.singleton_class.prepend extension
+ end
+ end
+ end
+end
diff --git a/activesupport/lib/active_support/gem_version.rb b/activesupport/lib/active_support/gem_version.rb
index a641b96c57..371a39a5e6 100644
--- a/activesupport/lib/active_support/gem_version.rb
+++ b/activesupport/lib/active_support/gem_version.rb
@@ -6,9 +6,9 @@ module ActiveSupport
module VERSION
MAJOR = 5
- MINOR = 1
+ MINOR = 2
TINY = 0
- PRE = "beta1"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
index 18477b9f6b..ce5207546d 100644
--- a/activesupport/lib/active_support/values/time_zone.rb
+++ b/activesupport/lib/active_support/values/time_zone.rb
@@ -250,14 +250,21 @@ module ActiveSupport
# for time zones in the country specified by its ISO 3166-1 Alpha2 code.
def country_zones(country_code)
code = country_code.to_s.upcase
- @country_zones[code] ||=
- TZInfo::Country.get(code).zone_identifiers.map do |tz_id|
- name = MAPPING.key(tz_id)
- name && self[name]
- end.compact.sort!
+ @country_zones[code] ||= load_country_zones(code)
end
private
+ def load_country_zones(code)
+ country = TZInfo::Country.get(code)
+ country.zone_identifiers.map do |tz_id|
+ if MAPPING.value?(tz_id)
+ self[MAPPING.key(tz_id)]
+ else
+ create(tz_id, nil, TZInfo::Timezone.new(tz_id))
+ end
+ end.sort!
+ end
+
def zones_map
@zones_map ||= begin
MAPPING.each_key { |place| self[place] } # load all the zones
diff --git a/activesupport/test/core_ext/object/duplicable_test.rb b/activesupport/test/core_ext/object/duplicable_test.rb
index e6f3c8aef2..68b0129980 100644
--- a/activesupport/test/core_ext/object/duplicable_test.rb
+++ b/activesupport/test/core_ext/object/duplicable_test.rb
@@ -4,7 +4,10 @@ require "active_support/core_ext/object/duplicable"
require "active_support/core_ext/numeric/time"
class DuplicableTest < ActiveSupport::TestCase
- if RUBY_VERSION >= "2.4.1"
+ if RUBY_VERSION >= "2.5.0"
+ RAISE_DUP = [method(:puts)]
+ ALLOW_DUP = ["1", "symbol_from_string".to_sym, Object.new, /foo/, [], {}, Time.now, Class.new, Module.new, BigDecimal.new("4.56"), nil, false, true, 1, 2.3, Complex(1), Rational(1)]
+ elsif RUBY_VERSION >= "2.4.1"
RAISE_DUP = [method(:puts), Complex(1), Rational(1)]
ALLOW_DUP = ["1", "symbol_from_string".to_sym, Object.new, /foo/, [], {}, Time.now, Class.new, Module.new, BigDecimal.new("4.56"), nil, false, true, 1, 2.3]
elsif RUBY_VERSION >= "2.4.0" # Due to 2.4.0 bug. This elsif cannot be removed unless we drop 2.4.0 support...
diff --git a/activesupport/test/deprecation_test.rb b/activesupport/test/deprecation_test.rb
index 5f72fbf662..36d1ef0849 100644
--- a/activesupport/test/deprecation_test.rb
+++ b/activesupport/test/deprecation_test.rb
@@ -35,6 +35,18 @@ class Deprecatee
A = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("Deprecatee::A", "Deprecatee::B::C")
end
+class DeprecateeWithAccessor
+ include ActiveSupport::Deprecation::DeprecatedConstantAccessor
+
+ module B
+ C = 1
+ end
+ deprecate_constant "A", "DeprecateeWithAccessor::B::C"
+
+ class NewException < StandardError; end
+ deprecate_constant "OldException", "DeprecateeWithAccessor::NewException"
+end
+
class DeprecationTest < ActiveSupport::TestCase
include ActiveSupport::Testing::Stream
@@ -162,6 +174,17 @@ class DeprecationTest < ActiveSupport::TestCase
assert_not_deprecated { assert_equal Deprecatee::B::C.class, Deprecatee::A.class }
end
+ def test_deprecated_constant_accessor
+ assert_not_deprecated { DeprecateeWithAccessor::B::C }
+ assert_deprecated("DeprecateeWithAccessor::A") { assert_equal DeprecateeWithAccessor::B::C, DeprecateeWithAccessor::A }
+ end
+
+ def test_deprecated_constant_accessor_exception
+ raise DeprecateeWithAccessor::NewException.new("Test")
+ rescue DeprecateeWithAccessor::OldException => e
+ assert_kind_of DeprecateeWithAccessor::NewException, e
+ end
+
def test_assert_deprecated_raises_when_method_not_deprecated
assert_raises(Minitest::Assertion) { assert_deprecated { @dtc.not } }
end
diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb
index 1615d8fdb2..de111cc40e 100644
--- a/activesupport/test/time_zone_test.rb
+++ b/activesupport/test/time_zone_test.rb
@@ -714,6 +714,10 @@ class TimeZoneTest < ActiveSupport::TestCase
assert_not_includes ActiveSupport::TimeZone.country_zones(:ru), ActiveSupport::TimeZone["Kuala Lumpur"]
end
+ def test_country_zones_without_mappings
+ assert_includes ActiveSupport::TimeZone.country_zones(:sv), ActiveSupport::TimeZone["America/El_Salvador"]
+ end
+
def test_to_yaml
assert_equal("--- !ruby/object:ActiveSupport::TimeZone\nname: Pacific/Honolulu\n", ActiveSupport::TimeZone["Hawaii"].to_yaml)
assert_equal("--- !ruby/object:ActiveSupport::TimeZone\nname: Europe/London\n", ActiveSupport::TimeZone["Europe/London"].to_yaml)
diff --git a/ci/travis.rb b/ci/travis.rb
index eb2890ca70..bb87c8f4ad 100755
--- a/ci/travis.rb
+++ b/ci/travis.rb
@@ -152,6 +152,7 @@ results = {}
ENV["GEM"].split(",").each do |gem|
[false, true].each do |isolated|
next if ENV["TRAVIS_PULL_REQUEST"] && ENV["TRAVIS_PULL_REQUEST"] != "false" && isolated
+ next if RUBY_VERSION < "2.4" && isolated
next if gem == "railties" && isolated
next if gem == "ac" && isolated
next if gem == "ac:integration" && isolated
diff --git a/guides/CHANGELOG.md b/guides/CHANGELOG.md
index 3a602efb3d..d8b122d264 100644
--- a/guides/CHANGELOG.md
+++ b/guides/CHANGELOG.md
@@ -1,6 +1 @@
-## Rails 5.1.0.beta1 (February 23, 2017) ##
-
-* No changes.
-
-
-Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/guides/CHANGELOG.md) for previous changes.
+Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/guides/CHANGELOG.md) for previous changes.
diff --git a/guides/bug_report_templates/action_controller_gem.rb b/guides/bug_report_templates/action_controller_gem.rb
index 85d698f81b..46fabca3e8 100644
--- a/guides/bug_report_templates/action_controller_gem.rb
+++ b/guides/bug_report_templates/action_controller_gem.rb
@@ -8,7 +8,7 @@ end
gemfile(true) do
source "https://rubygems.org"
# Activate the gem you are reporting the issue against.
- gem "rails", "5.0.1"
+ gem "rails", "5.1.0.rc1"
end
require "rack/test"
diff --git a/guides/bug_report_templates/action_controller_master.rb b/guides/bug_report_templates/action_controller_master.rb
index 486c7243ad..7644f6fe4a 100644
--- a/guides/bug_report_templates/action_controller_master.rb
+++ b/guides/bug_report_templates/action_controller_master.rb
@@ -8,6 +8,7 @@ end
gemfile(true) do
source "https://rubygems.org"
gem "rails", github: "rails/rails"
+ gem "arel", github: "rails/arel"
end
require "action_controller/railtie"
diff --git a/guides/bug_report_templates/active_job_gem.rb b/guides/bug_report_templates/active_job_gem.rb
index f715caec95..71fe356ea0 100644
--- a/guides/bug_report_templates/active_job_gem.rb
+++ b/guides/bug_report_templates/active_job_gem.rb
@@ -8,7 +8,7 @@ end
gemfile(true) do
source "https://rubygems.org"
# Activate the gem you are reporting the issue against.
- gem "activejob", "5.0.1"
+ gem "activejob", "5.1.0.rc1"
end
require "minitest/autorun"
diff --git a/guides/bug_report_templates/active_job_master.rb b/guides/bug_report_templates/active_job_master.rb
index f61518713f..7591470440 100644
--- a/guides/bug_report_templates/active_job_master.rb
+++ b/guides/bug_report_templates/active_job_master.rb
@@ -8,6 +8,7 @@ end
gemfile(true) do
source "https://rubygems.org"
gem "rails", github: "rails/rails"
+ gem "arel", github: "rails/arel"
end
require "active_job"
diff --git a/guides/bug_report_templates/active_record_gem.rb b/guides/bug_report_templates/active_record_gem.rb
index 98edcb76b1..a685c257ea 100644
--- a/guides/bug_report_templates/active_record_gem.rb
+++ b/guides/bug_report_templates/active_record_gem.rb
@@ -8,7 +8,7 @@ end
gemfile(true) do
source "https://rubygems.org"
# Activate the gem you are reporting the issue against.
- gem "activerecord", "5.0.1"
+ gem "activerecord", "5.1.0.rc1"
gem "sqlite3"
end
diff --git a/guides/bug_report_templates/active_record_master.rb b/guides/bug_report_templates/active_record_master.rb
index 7265a671b0..8bbc1ef19e 100644
--- a/guides/bug_report_templates/active_record_master.rb
+++ b/guides/bug_report_templates/active_record_master.rb
@@ -8,6 +8,7 @@ end
gemfile(true) do
source "https://rubygems.org"
gem "rails", github: "rails/rails"
+ gem "arel", github: "rails/arel"
gem "sqlite3"
end
diff --git a/guides/bug_report_templates/active_record_migrations_gem.rb b/guides/bug_report_templates/active_record_migrations_gem.rb
index ece6ae4f12..b4e822dfe0 100644
--- a/guides/bug_report_templates/active_record_migrations_gem.rb
+++ b/guides/bug_report_templates/active_record_migrations_gem.rb
@@ -8,7 +8,7 @@ end
gemfile(true) do
source "https://rubygems.org"
# Activate the gem you are reporting the issue against.
- gem "activerecord", "5.0.1"
+ gem "activerecord", "5.1.0.rc1"
gem "sqlite3"
end
diff --git a/guides/bug_report_templates/active_record_migrations_master.rb b/guides/bug_report_templates/active_record_migrations_master.rb
index 13a375d1ba..84a4b71909 100644
--- a/guides/bug_report_templates/active_record_migrations_master.rb
+++ b/guides/bug_report_templates/active_record_migrations_master.rb
@@ -8,6 +8,7 @@ end
gemfile(true) do
source "https://rubygems.org"
gem "rails", github: "rails/rails"
+ gem "arel", github: "rails/arel"
gem "sqlite3"
end
diff --git a/guides/bug_report_templates/generic_gem.rb b/guides/bug_report_templates/generic_gem.rb
index fa9f94eea0..e1b705bea4 100644
--- a/guides/bug_report_templates/generic_gem.rb
+++ b/guides/bug_report_templates/generic_gem.rb
@@ -8,7 +8,7 @@ end
gemfile(true) do
source "https://rubygems.org"
# Activate the gem you are reporting the issue against.
- gem "activesupport", "5.0.1"
+ gem "activesupport", "5.1.0.rc1"
end
require "active_support/core_ext/object/blank"
diff --git a/guides/bug_report_templates/generic_master.rb b/guides/bug_report_templates/generic_master.rb
index d3a7ae4ac4..ed45726e92 100644
--- a/guides/bug_report_templates/generic_master.rb
+++ b/guides/bug_report_templates/generic_master.rb
@@ -8,6 +8,7 @@ end
gemfile(true) do
source "https://rubygems.org"
gem "rails", github: "rails/rails"
+ gem "arel", github: "rails/arel"
end
require "active_support"
diff --git a/guides/source/_welcome.html.erb b/guides/source/_welcome.html.erb
index 5bd1ea4d22..8afec00018 100644
--- a/guides/source/_welcome.html.erb
+++ b/guides/source/_welcome.html.erb
@@ -10,12 +10,13 @@
</p>
<% else %>
<p>
- These are the new guides for Rails 5.0 based on <a href="https://github.com/rails/rails/tree/<%= @version %>"><%= @version %></a>.
+ These are the new guides for Rails 5.1 based on <a href="https://github.com/rails/rails/tree/<%= @version %>"><%= @version %></a>.
These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together.
</p>
<% end %>
<p>
The guides for earlier releases:
+<a href="http://guides.rubyonrails.org/v5.0/">Rails 5.0</a>,
<a href="http://guides.rubyonrails.org/v4.2/">Rails 4.2</a>,
<a href="http://guides.rubyonrails.org/v4.1/">Rails 4.1</a>,
<a href="http://guides.rubyonrails.org/v4.0/">Rails 4.0</a>,
diff --git a/guides/source/action_cable_overview.md b/guides/source/action_cable_overview.md
index e929945dd0..50a28571b4 100644
--- a/guides/source/action_cable_overview.md
+++ b/guides/source/action_cable_overview.md
@@ -6,7 +6,7 @@ incorporate real-time features into your Rails application.
After reading this guide, you will know:
-* What Action Cable is and its integration on backend and frontend
+* What Action Cable is and its integration on backend and frontend
* How to setup Action Cable
* How to setup channels
* Deployment and Architecture setup for running Action Cable
@@ -64,8 +64,8 @@ module ApplicationCable
private
def find_verified_user
- if current_user = User.find_by(id: cookies.signed[:user_id])
- current_user
+ if verified_user = User.find_by(id: cookies.signed[:user_id])
+ verified_user
else
reject_unauthorized_connection
end
diff --git a/guides/source/caching_with_rails.md b/guides/source/caching_with_rails.md
index aa79f59e4f..6cdce5c2f4 100644
--- a/guides/source/caching_with_rails.md
+++ b/guides/source/caching_with_rails.md
@@ -387,6 +387,11 @@ store is not appropriate for large application deployments. However, it can
work well for small, low traffic sites with only a couple of server processes,
as well as development and test environments.
+New Rails projects are configured to use this implementation in development environment by default.
+
+NOTE: Since processes will not share cache data when using `:memory_store`,
+it will not be possible to manually read, write or expire the cache via the Rails console.
+
### ActiveSupport::Cache::FileStore
This cache store uses the file system to store entries. The path to the directory where the store files will be stored must be specified when initializing the cache.
@@ -403,7 +408,8 @@ share a cache by using a shared file system, but that setup is not recommended.
As the cache will grow until the disk is full, it is recommended to
periodically clear out old entries.
-This is the default cache store implementation.
+This is the default cache store implementation (at `"#{root}/tmp/cache/"`) if
+no explicit `config.cache_store` is supplied.
### ActiveSupport::Cache::MemCacheStore
diff --git a/guides/source/command_line.md b/guides/source/command_line.md
index c8d559745e..3360496c08 100644
--- a/guides/source/command_line.md
+++ b/guides/source/command_line.md
@@ -63,7 +63,7 @@ With no further work, `rails server` will run our new shiny Rails app:
$ cd commandsapp
$ bin/rails server
=> Booting Puma
-=> Rails 5.0.0 application starting in development on http://0.0.0.0:3000
+=> Rails 5.1.0 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.0.2 (ruby 2.3.0-p0), codename: Plethora of Penguin Pinatas
@@ -294,7 +294,7 @@ If you wish to test out some code without changing any data, you can do that by
```bash
$ bin/rails console --sandbox
-Loading development environment in sandbox (Rails 5.0.0)
+Loading development environment in sandbox (Rails 5.1.0)
Any modifications you make will be rolled back on exit
irb(main):001:0>
```
@@ -428,12 +428,12 @@ INFO: You can also use `bin/rails -T` to get the list of tasks.
```bash
$ bin/rails about
About your application's environment
-Rails version 5.0.0
+Rails version 5.1.0
Ruby version 2.2.2 (x86_64-linux)
RubyGems version 2.4.6
-Rack version 1.6
+Rack version 2.0.1
JavaScript Runtime Node.js (V8)
-Middleware Rack::Sendfile, ActionDispatch::Static, ActionDispatch::Executor, #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007ffd131a7c88>, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, Rack::Head, Rack::ConditionalGet, Rack::ETag
+Middleware: Rack::Sendfile, ActionDispatch::Static, ActionDispatch::Executor, ActiveSupport::Cache::Strategy::LocalCache::Middleware, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, ActionDispatch::RemoteIp, Sprockets::Rails::QuietAssets, Rails::Rack::Logger, ActionDispatch::ShowExceptions, WebConsole::Middleware, ActionDispatch::DebugExceptions, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, Rack::Head, Rack::ConditionalGet, Rack::ETag
Application root /home/foobar/commandsapp
Environment development
Database adapter sqlite3
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index a4f3882124..ae70b06996 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -32,7 +32,7 @@ Configuring Rails Components
In general, the work of configuring Rails means configuring the components of Rails, as well as configuring Rails itself. The configuration file `config/application.rb` and environment-specific configuration files (such as `config/environments/production.rb`) allow you to specify the various settings that you want to pass down to all of the components.
-For example, the `config/application.rb` file includes this setting:
+For example, you could add this setting to `config/application.rb` file:
```ruby
config.time_zone = 'Central Time (US & Canada)'
diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md
index fe5437ae5d..3b19b0dff1 100644
--- a/guides/source/contributing_to_ruby_on_rails.md
+++ b/guides/source/contributing_to_ruby_on_rails.md
@@ -15,7 +15,7 @@ After reading this guide, you will know:
Ruby on Rails is not "someone else's framework." Over the years, hundreds of people have contributed to Ruby on Rails ranging from a single character to massive architectural changes or significant documentation - all with the goal of making Ruby on Rails better for everyone. Even if you don't feel up to writing code or documentation yet, there are a variety of other ways that you can contribute, from reporting issues to testing patches.
-As mentioned in [Rails
+As mentioned in [Rails'
README](https://github.com/rails/rails/blob/master/README.md), everyone interacting in Rails and its sub-projects' codebases, issue trackers, chat rooms, and mailing lists is expected to follow the Rails [code of conduct](http://rubyonrails.org/conduct/).
--------------------------------------------------------------------------------
@@ -98,13 +98,13 @@ Anything you can do to make bug reports more succinct or easier to reproduce hel
### Testing Patches
-You can also help out by examining pull requests that have been submitted to Ruby on Rails via GitHub. To apply someone's changes you need first to create a dedicated branch:
+You can also help out by examining pull requests that have been submitted to Ruby on Rails via GitHub. In order to apply someone's changes, you need to first create a dedicated branch:
```bash
$ git checkout -b testing_branch
```
-Then you can use their remote branch to update your codebase. For example, let's say the GitHub user JohnSmith has forked and pushed to a topic branch "orange" located at https://github.com/JohnSmith/rails.
+Then, you can use their remote branch to update your codebase. For example, let's say the GitHub user JohnSmith has forked and pushed to a topic branch "orange" located at https://github.com/JohnSmith/rails.
```bash
$ git remote add JohnSmith https://github.com/JohnSmith/rails.git
diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md
index 33dee6a868..58aab774b3 100644
--- a/guides/source/debugging_rails_applications.md
+++ b/guides/source/debugging_rails_applications.md
@@ -313,7 +313,7 @@ For example:
```bash
=> Booting Puma
-=> Rails 5.0.0 application starting in development on http://0.0.0.0:3000
+=> Rails 5.1.0 application starting in development on http://0.0.0.0:3000
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.4.0 (ruby 2.3.1-p112), codename: Owl Bowl Brawl
@@ -445,11 +445,11 @@ then `backtrace` will supply the answer.
--> #0 ArticlesController.index
at /PathToProject/app/controllers/articles_controller.rb:8
#1 ActionController::BasicImplicitRender.send_action(method#String, *args#Array)
- at /PathToGems/actionpack-5.0.0/lib/action_controller/metal/basic_implicit_render.rb:4
+ at /PathToGems/actionpack-5.1.0/lib/action_controller/metal/basic_implicit_render.rb:4
#2 AbstractController::Base.process_action(action#NilClass, *args#Array)
- at /PathToGems/actionpack-5.0.0/lib/abstract_controller/base.rb:181
+ at /PathToGems/actionpack-5.1.0/lib/abstract_controller/base.rb:181
#3 ActionController::Rendering.process_action(action, *args)
- at /PathToGems/actionpack-5.0.0/lib/action_controller/metal/rendering.rb:30
+ at /PathToGems/actionpack-5.1.0/lib/action_controller/metal/rendering.rb:30
...
```
@@ -461,7 +461,7 @@ context.
```
(byebug) frame 2
-[176, 185] in /PathToGems/actionpack-5.0.0/lib/abstract_controller/base.rb
+[176, 185] in /PathToGems/actionpack-5.1.0/lib/abstract_controller/base.rb
176: # is the intended way to override action dispatching.
177: #
178: # Notice that the first argument is the method to be dispatched
@@ -676,7 +676,7 @@ Ruby instruction to be executed -- in this case, Active Support's `week` method.
```
(byebug) step
-[49, 58] in /PathToGems/activesupport-5.0.0/lib/active_support/core_ext/numeric/time.rb
+[49, 58] in /PathToGems/activesupport-5.1.0/lib/active_support/core_ext/numeric/time.rb
49:
50: # Returns a Duration instance matching the number of weeks provided.
51: #
diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml
index 2925fb4b58..5fccdcccec 100644
--- a/guides/source/documents.yaml
+++ b/guides/source/documents.yaml
@@ -194,6 +194,11 @@
url: upgrading_ruby_on_rails.html
description: This guide helps in upgrading applications to latest Ruby on Rails versions.
-
+ name: Ruby on Rails 5.1 Release Notes
+ url: 5_1_release_notes.html
+ description: Release notes for Rails 5.1.
+ work_in_progress: true
+ -
name: Ruby on Rails 5.0 Release Notes
url: 5_0_release_notes.html
description: Release notes for Rails 5.0.
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
index 57b8472462..068114898d 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -127,7 +127,7 @@ run the following:
$ rails --version
```
-If it says something like "Rails 5.0.0", you are ready to continue.
+If it says something like "Rails 5.1.0", you are ready to continue.
### Creating the Blog Application
diff --git a/guides/source/security.md b/guides/source/security.md
index a14134f8c1..7e27e6f37d 100644
--- a/guides/source/security.md
+++ b/guides/source/security.md
@@ -212,7 +212,7 @@ CSRF appears very rarely in CVE (Common Vulnerabilities and Exposures) - less th
NOTE: _First, as is required by the W3C, use GET and POST appropriately. Secondly, a security token in non-GET requests will protect your application from CSRF._
-The HTTP protocol basically provides two main types of requests - GET and POST (and more, but they are not supported by most browsers). The World Wide Web Consortium (W3C) provides a checklist for choosing HTTP GET or POST:
+The HTTP protocol basically provides two main types of requests - GET and POST (DELETE, PUT, and PATCH should be used like POST). The World Wide Web Consortium (W3C) provides a checklist for choosing HTTP GET or POST:
**Use GET if:**
@@ -224,7 +224,7 @@ The HTTP protocol basically provides two main types of requests - GET and POST (
* The interaction _changes the state_ of the resource in a way that the user would perceive (e.g., a subscription to a service), or
* The user is _held accountable for the results_ of the interaction.
-If your web application is RESTful, you might be used to additional HTTP verbs, such as PATCH, PUT or DELETE. Most of today's web browsers, however, do not support them - only GET and POST. Rails uses a hidden `_method` field to handle this barrier.
+If your web application is RESTful, you might be used to additional HTTP verbs, such as PATCH, PUT or DELETE. Some legacy web browsers, however, do not support them - only GET and POST. Rails uses a hidden `_method` field to handle these cases.
_POST requests can be sent automatically, too_. In this example, the link www.harmless.com is shown as the destination in the browser's status bar. But it has actually dynamically created a new form that sends a POST request.
diff --git a/guides/source/testing.md b/guides/source/testing.md
index 27f5b5e916..7741834153 100644
--- a/guides/source/testing.md
+++ b/guides/source/testing.md
@@ -644,7 +644,7 @@ system tests should live.
If you want to change the default settings you can simply change what the system
tests are "driven by". Say you want to change the driver from Selenium to
-Poltergeist. First add the Poltergeist gem to your Gemfile. Then in your
+Poltergeist. First add the `poltergeist` gem to your Gemfile. Then in your
`application_system_test_case.rb` file do the following:
```ruby
@@ -722,7 +722,7 @@ class ArticlesTest < ApplicationSystemTestCase
end
```
-The test should see that there is an h1 on the articles index and pass.
+The test should see that there is an `h1` on the articles index page and pass.
Run the system tests.
@@ -763,7 +763,7 @@ text. Once the fields are filled in, "Create Article" is clicked on which will
send a POST request to create the new article in the database.
We will be redirected back to the the articles index page and there we assert
-that the text from the article title is on the articles index page.
+that the text from the new article's title is on the articles index page.
#### Taking it further
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index fedac90fc8..6032d2e1a1 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,199 +1 @@
-* Add `app:update` task to engines.
-
- *Yuji Yaginuma*
-
-* Avoid running system tests by default with the `bin/rails test`
- and `bin/rake test` commands since they may be expensive.
-
- Fixes #28286.
-
- *Robin Dupret*
-
-* Improve encryption for encrypted secrets.
-
- Switch to aes-128-gcm authenticated encryption. Also generate a random
- initialization vector for each encryption so the same input and key can
- generate different encrypted data.
-
- Double the encryption key entropy by properly extracting the underlying
- bytes from the hexadecimal seed key.
-
- NOTE: Since the encryption mechanism has been switched, you need to run
- this script to upgrade:
-
- https://gist.github.com/kaspth/bc37989c2f39a5642112f28b1d93f343
-
- *Stephen Touset*
-
-## Rails 5.1.0.beta1 (February 23, 2017) ##
-
-* Add encrypted secrets in `config/secrets.yml.enc`.
-
- Allow storing production secrets straight in the revision control system by
- encrypting them.
-
- Use `bin/rails secrets:setup` to opt-in by generating `config/secrets.yml.enc`
- for the secrets themselves and `config/secrets.yml.key` for the encryption key.
-
- Edit secrets with `bin/rails secrets:edit`.
-
- See `bin/rails secrets:setup --help` for more.
-
- *Kasper Timm Hansen*
-
-* Fix running multiple tests in one `rake` command
-
- e.g. `bin/rake test:models test:controllers`
-
- *Dominic Cleal*
-
-* Add option to configure Ruby's warning behaviour to test runner.
-
- *Yuji Yaginuma*
-
-* Initialize git repo when generating new app, if option `--skip-git`
- is not provided.
-
- *Dino Maric*
-
-* Install Byebug gem as default in Windows (mingw and x64_mingw) platform.
-
- *Junichi Ito*
-
-* Make every Rails command work within engines.
-
- *Sean Collins*, *Yuji Yaginuma*
-
-* Don't generate HTML/ERB templates for scaffold controller with `--api` flag.
-
- Fixes #27591.
-
- *Prathamesh Sonpatki*
-
-* Make `Rails.env` fall back to `development` when `RAILS_ENV` and `RACK_ENV` is an empty string.
-
- *Daniel Deng*
-
-* Remove deprecated `CONTROLLER` environment variable for `routes` task.
-
- *Rafael Mendonça França*
-
-* Remove deprecated tasks: `rails:update`, `rails:template`, `rails:template:copy`,
- `rails:update:configs` and `rails:update:bin`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated file `rails/rack/debugger`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `config.serve_static_files`.
-
- *Rafael Mendonça França*
-
-* Remove deprecated `config.static_cache_control`.
-
- *Rafael Mendonça França*
-
-* The `log:clear` task clear all environments log files by default.
-
- *Yuji Yaginuma*
-
-* Add Webpack support in new apps via the --webpack option, which will delegate to the rails/webpacker gem.
-
- To generate a new app that has Webpack dependencies configured and binstubs for webpack and webpack-watcher:
-
- `rails new myapp --webpack`
-
- To generate a new app that has Webpack + React configured and an example intalled:
-
- `rails new myapp --webpack=react`
-
- *DHH*
-
-* Add Yarn support in new apps with a yarn binstub and package.json. Skippable via --skip-yarn option.
-
- *Liceth Ovalles*, *Guillermo Iguaran*, *DHH*
-
-* Removed jquery-rails from default stack, instead rails-ujs that is shipped
- with Action View is included as default UJS adapter.
-
- *Guillermo Iguaran*
-
-* The config file `secrets.yml` is now loaded in with all keys as symbols.
- This allows secrets files to contain more complex information without all
- child keys being strings while parent keys are symbols.
-
- *Isaac Sloan*
-
-* Add `:skip_sprockets` to `Rails::PluginBuilder::PASSTHROUGH_OPTIONS`
-
- *Tsukuru Tanimichi*
-
-* Add `--skip-coffee` option to `rails new`
-
- *Seunghwan Oh*
-
-* Allow the use of listen's 3.1.x branch
-
- *Esteban Santana Santana*
-
-* Run `Minitest.after_run` hooks when running `rails test`.
-
- *Michael Grosser*
-
-* Run `before_configuration` callbacks as soon as application constant
- inherits from `Rails::Application`.
-
- Fixes #19880.
-
- *Yuji Yaginuma*
-
-* A generated app should not include Uglifier with `--skip-javascript` option.
-
- *Ben Pickles*
-
-* Set session store to cookie store internally and remove the initializer from
- the generated app.
-
- *Prathamesh Sonpatki*
-
-* Set the server host using the `HOST` environment variable.
-
- *mahnunchik*
-
-* Add public API to register new folders for `rake notes`:
-
- config.annotations.register_directories('spec', 'features')
-
- *John Meehan*
-
-* Display name of the class defining the initializer along with the initializer
- name in the output of `rails initializers`.
-
- Before:
- disable_dependency_loading
-
- After:
- DemoApp::Application.disable_dependency_loading
-
- *ta1kt0me*
-
-* Do not run `bundle install` when generating a new plugin.
-
- Since bundler 1.12.0, the gemspec is validated so the `bundle install`
- command will fail just after the gem is created causing confusion to the
- users. This change was a bug fix to correctly validate gemspecs.
-
- *Rafael Mendonça França*
-
-* Default `config.assets.quiet = true` in the development environment. Suppress
- logging of assets requests by default.
-
- *Kevin McPhillips*
-
-* Added a shared section to `config/secrets.yml` that will be loaded for all environments.
-
- *DHH*
-
-Please check [5-0-stable](https://github.com/rails/rails/blob/5-0-stable/railties/CHANGELOG.md) for previous changes.
+Please check [5-1-stable](https://github.com/rails/rails/blob/5-1-stable/railties/CHANGELOG.md) for previous changes.
diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb
index 819e801740..7c49fabba5 100644
--- a/railties/lib/rails/application/configuration.rb
+++ b/railties/lib/rails/application/configuration.rb
@@ -14,9 +14,8 @@ module Rails
:ssl_options, :public_file_server,
:session_options, :time_zone, :reload_classes_only_on_change,
:beginning_of_week, :filter_redirect, :x, :enable_dependency_loading,
- :read_encrypted_secrets
+ :read_encrypted_secrets, :log_level
- attr_writer :log_level
attr_reader :encoding, :api_only
def initialize(*)
@@ -35,7 +34,7 @@ module Rails
@session_store = nil
@time_zone = "UTC"
@beginning_of_week = :monday
- @log_level = nil
+ @log_level = :debug
@generators = app_generators
@cache_store = [ :file_store, "#{root}/tmp/cache/" ]
@railties_order = [:all]
@@ -78,6 +77,9 @@ module Rails
assets.unknown_asset_fallback = false
end
+ when "5.2"
+ load_defaults "5.1"
+
else
raise "Unknown version #{target_version.to_s.inspect}"
end
@@ -149,10 +151,6 @@ module Rails
raise e, "Cannot load `Rails.application.database_configuration`:\n#{e.message}", e.backtrace
end
- def log_level
- @log_level ||= (Rails.env.production? ? :info : :debug)
- end
-
def colorize_logging
ActiveSupport::LogSubscriber.colorize_logging
end
diff --git a/railties/lib/rails/commands/destroy/destroy_command.rb b/railties/lib/rails/commands/destroy/destroy_command.rb
index 794673851d..281732a936 100644
--- a/railties/lib/rails/commands/destroy/destroy_command.rb
+++ b/railties/lib/rails/commands/destroy/destroy_command.rb
@@ -5,6 +5,9 @@ module Rails
class DestroyCommand < Base # :nodoc:
no_commands do
def help
+ require_application_and_environment!
+ load_generators
+
Rails::Generators.help self.class.command_name
end
end
diff --git a/railties/lib/rails/commands/runner/runner_command.rb b/railties/lib/rails/commands/runner/runner_command.rb
index 056ad980b9..6864a9726b 100644
--- a/railties/lib/rails/commands/runner/runner_command.rb
+++ b/railties/lib/rails/commands/runner/runner_command.rb
@@ -16,7 +16,7 @@ module Rails
"#{super} [<'Some.ruby(code)'> | <filename.rb>]"
end
- def perform(code_or_file = nil, *file_argv)
+ def perform(code_or_file = nil, *command_argv)
unless code_or_file
help
exit 1
@@ -27,9 +27,10 @@ module Rails
require_application_and_environment!
Rails.application.load_runner
+ ARGV.replace(command_argv)
+
if File.exist?(code_or_file)
$0 = code_or_file
- ARGV.replace(file_argv)
Kernel.load code_or_file
else
begin
diff --git a/railties/lib/rails/commands/server/server_command.rb b/railties/lib/rails/commands/server/server_command.rb
index 7e8c86fb49..278fe63c51 100644
--- a/railties/lib/rails/commands/server/server_command.rb
+++ b/railties/lib/rails/commands/server/server_command.rb
@@ -188,10 +188,12 @@ module Rails
end
def host
- unless (default_host = options[:binding])
+ if options[:binding]
+ options[:binding]
+ else
default_host = environment == "development" ? "localhost" : "0.0.0.0"
+ ENV.fetch("HOST", default_host)
end
- ENV.fetch("HOST", default_host)
end
def environment
diff --git a/railties/lib/rails/gem_version.rb b/railties/lib/rails/gem_version.rb
index 3174ffb0dc..7bacf2e0ba 100644
--- a/railties/lib/rails/gem_version.rb
+++ b/railties/lib/rails/gem_version.rb
@@ -6,9 +6,9 @@ module Rails
module VERSION
MAJOR = 5
- MINOR = 1
+ MINOR = 2
TINY = 0
- PRE = "beta1"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index ebe8cfea60..9109be5e04 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -13,6 +13,7 @@ module Rails
DATABASES = %w( mysql postgresql sqlite3 oracle frontbase ibm_db sqlserver )
JDBC_DATABASES = %w( jdbcmysql jdbcsqlite3 jdbcpostgresql jdbc )
DATABASES.concat(JDBC_DATABASES)
+ WEBPACKS = %w( react vue angular )
attr_accessor :rails_template
add_shebang_option!
@@ -30,11 +31,8 @@ module Rails
class_option :database, type: :string, aliases: "-d", default: "sqlite3",
desc: "Preconfigure for selected database (options: #{DATABASES.join('/')})"
- class_option :javascript, type: :string, aliases: "-j",
- desc: "Preconfigure for selected JavaScript library"
-
class_option :webpack, type: :string, default: nil,
- desc: "Preconfigure for app-like JavaScript with Webpack"
+ desc: "Preconfigure for app-like JavaScript with Webpack (options: #{WEBPACKS.join('/')})"
class_option :skip_yarn, type: :boolean, default: false,
desc: "Don't use Yarn for managing JavaScript dependencies"
@@ -246,6 +244,7 @@ module Rails
def rails_gemfile_entry
dev_edge_common = [
+ GemfileEntry.github("arel", "rails/arel"),
]
if options.dev?
[
@@ -340,11 +339,6 @@ module Rails
gems = [javascript_runtime_gemfile_entry]
gems << coffee_gemfile_entry unless options[:skip_coffee]
- if options[:javascript]
- gems << GemfileEntry.version("#{options[:javascript]}-rails", nil,
- "Use #{options[:javascript]} as the JavaScript library")
- end
-
unless options[:skip_turbolinks]
gems << GemfileEntry.version("turbolinks", "~> 5",
"Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks")
@@ -411,6 +405,10 @@ module Rails
!options[:skip_spring] && !options.dev? && Process.respond_to?(:fork) && !RUBY_PLATFORM.include?("cygwin")
end
+ def depends_on_system_test?
+ !(options[:skip_system_test] || options[:skip_test] || options[:api])
+ end
+
def depend_on_listen?
!options[:skip_listen] && os_supports_listen_out_of_the_box?
end
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 73c00ad41a..4f2e84f924 100644
--- a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
+++ b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
@@ -15,15 +15,15 @@
<div class="field">
<% if attribute.password_digest? -%>
<%%= form.label :password %>
- <%%= form.password_field :password %>
+ <%%= form.password_field :password, id: :<%= field_id(:password) %> %>
</div>
<div class="field">
<%%= form.label :password_confirmation %>
- <%%= form.password_field :password_confirmation %>
+ <%%= form.password_field :password_confirmation, id: :<%= field_id(:password_confirmation) %> %>
<% else -%>
<%%= form.label :<%= attribute.column_name %> %>
- <%%= form.<%= attribute.field_type %> :<%= attribute.column_name %> %>
+ <%%= form.<%= attribute.field_type %> :<%= attribute.column_name %>, id: :<%= field_id(attribute.column_name) %> %>
<% end -%>
</div>
diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb
index 02557b098a..46001f306a 100644
--- a/railties/lib/rails/generators/named_base.rb
+++ b/railties/lib/rails/generators/named_base.rb
@@ -149,6 +149,10 @@ module Rails
"new_#{singular_table_name}_url"
end
+ def field_id(attribute_name)
+ [singular_table_name, attribute_name].join('_')
+ end
+
def singular_table_name # :doc:
@singular_table_name ||= (pluralize_table_names? ? table_name.singularize : table_name)
end
diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb
index 38830ba38f..324843a5f5 100644
--- a/railties/lib/rails/generators/rails/app/app_generator.rb
+++ b/railties/lib/rails/generators/rails/app/app_generator.rb
@@ -84,6 +84,16 @@ module Rails
chmod "bin", 0755 & ~File.umask, verbose: false
end
+ def bin_when_updating
+ bin_yarn_exist = File.exist?("bin/yarn")
+
+ bin
+
+ if options[:api] && !bin_yarn_exist
+ remove_file "bin/yarn"
+ end
+ end
+
def config
empty_directory "config"
@@ -106,11 +116,11 @@ module Rails
cookie_serializer_config_exist = File.exist?("config/initializers/cookies_serializer.rb")
action_cable_config_exist = File.exist?("config/cable.yml")
rack_cors_config_exist = File.exist?("config/initializers/cors.rb")
+ assets_config_exist = File.exist?("config/initializers/assets.rb")
+ new_framework_defaults_5_1_exist = File.exist?("config/initializers/new_framework_defaults_5_1.rb")
config
- gsub_file "config/environments/development.rb", /^(\s+)config\.file_watcher/, '\1# config.file_watcher'
-
unless cookie_serializer_config_exist
gsub_file "config/initializers/cookies_serializer.rb", /json(?!,)/, "marshal"
end
@@ -122,6 +132,22 @@ module Rails
unless rack_cors_config_exist
remove_file "config/initializers/cors.rb"
end
+
+ if options[:api]
+ unless cookie_serializer_config_exist
+ remove_file "config/initializers/cookies_serializer.rb"
+ end
+
+ unless assets_config_exist
+ remove_file "config/initializers/assets.rb"
+ end
+
+ # Sprockets owns the only new default for 5.1:
+ # In API-only Applications, we don't want the file.
+ unless new_framework_defaults_5_1_exist
+ remove_file "config/initializers/new_framework_defaults_5_1.rb"
+ end
+ end
end
def database_yml
@@ -232,6 +258,11 @@ module Rails
build(:bin)
end
+ def update_bin_files
+ build(:bin_when_updating)
+ end
+ remove_task :update_bin_files
+
def create_config_files
build(:config)
end
@@ -277,7 +308,7 @@ module Rails
end
def create_system_test_files
- build(:system_test) unless options[:skip_system_test] || options[:skip_test] || options[:api]
+ build(:system_test) if depends_on_system_test?
end
def create_tmp_files
diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile
index ab4aa04fff..06f0dd6d6d 100644
--- a/railties/lib/rails/generators/rails/app/templates/Gemfile
+++ b/railties/lib/rails/generators/rails/app/templates/Gemfile
@@ -32,7 +32,7 @@ end
group :development, :test do
# Call 'byebug' anywhere in the code to stop execution and get a debugger console
gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
- <%- unless options.skip_system_test? || options.api? -%>
+ <%- if depends_on_system_test? -%>
# Adds support for Capybara system testing and selenium driver
gem 'capybara', '~> 2.13.0'
gem 'selenium-webdriver'
diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
index 511b4a82eb..b75b65c8df 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
+++ b/railties/lib/rails/generators/rails/app/templates/config/environments/development.rb.tt
@@ -13,6 +13,7 @@ Rails.application.configure do
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
+ # Run rails dev:cache to toggle caching.
if Rails.root.join('tmp/caching-dev.txt').exist?
config.action_controller.perform_caching = true
diff --git a/railties/lib/rails/generators/rails/app/templates/config/secrets.yml b/railties/lib/rails/generators/rails/app/templates/config/secrets.yml
index 816efcc5b1..ea9d47396c 100644
--- a/railties/lib/rails/generators/rails/app/templates/config/secrets.yml
+++ b/railties/lib/rails/generators/rails/app/templates/config/secrets.yml
@@ -12,8 +12,8 @@
# Shared secrets are available across all environments.
-shared:
- api_key: 123
+# shared:
+# api_key: a1B2c3D4e5F6
# Environmental secrets are only available for that specific environment.
diff --git a/railties/lib/rails/tasks/framework.rake b/railties/lib/rails/tasks/framework.rake
index f5586b53f0..32a6b109bc 100644
--- a/railties/lib/rails/tasks/framework.rake
+++ b/railties/lib/rails/tasks/framework.rake
@@ -63,7 +63,7 @@ namespace :app do
# desc "Adds new executables to the application bin/ directory"
task :bin do
- RailsUpdate.invoke_from_app_generator :create_bin_files
+ RailsUpdate.invoke_from_app_generator :update_bin_files
end
task :upgrade_guide_info do
diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb
index ee0d697599..fe581db286 100644
--- a/railties/test/application/generators_test.rb
+++ b/railties/test/application/generators_test.rb
@@ -189,6 +189,9 @@ module ApplicationTests
FileUtils.cd(rails_root) do
output = `bin/rails generate --help`
assert_no_match "active_record:migration", output
+
+ output = `bin/rails destroy --help`
+ assert_no_match "active_record:migration", output
end
end
end
diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb
index dc1d816dc5..93b5263bf7 100644
--- a/railties/test/application/middleware/cache_test.rb
+++ b/railties/test/application/middleware/cache_test.rb
@@ -117,12 +117,12 @@ module ApplicationTests
assert_equal "miss, store", last_response.headers["X-Rack-Cache"]
assert_equal "public", last_response.headers["Cache-Control"]
- body = last_response.body
etag = last_response.headers["ETag"]
- get "/expires/expires_etag", {}, "If-None-Match" => etag
+ get "/expires/expires_etag", {}, "HTTP_IF_NONE_MATCH" => etag
assert_equal "stale, valid, store", last_response.headers["X-Rack-Cache"]
- assert_equal body, last_response.body
+ assert_equal 304, last_response.status
+ assert_equal "", last_response.body
end
def test_cache_works_with_etags_private
@@ -137,7 +137,7 @@ module ApplicationTests
body = last_response.body
etag = last_response.headers["ETag"]
- get "/expires/expires_etag", { private: true }, "If-None-Match" => etag
+ get "/expires/expires_etag", { private: true }, "HTTP_IF_NONE_MATCH" => etag
assert_equal "miss", last_response.headers["X-Rack-Cache"]
assert_not_equal body, last_response.body
end
@@ -151,12 +151,12 @@ module ApplicationTests
assert_equal "miss, store", last_response.headers["X-Rack-Cache"]
assert_equal "public", last_response.headers["Cache-Control"]
- body = last_response.body
last = last_response.headers["Last-Modified"]
- get "/expires/expires_last_modified", {}, "If-Modified-Since" => last
+ get "/expires/expires_last_modified", {}, "HTTP_IF_MODIFIED_SINCE" => last
assert_equal "stale, valid, store", last_response.headers["X-Rack-Cache"]
- assert_equal body, last_response.body
+ assert_equal 304, last_response.status
+ assert_equal "", last_response.body
end
def test_cache_works_with_last_modified_private
@@ -171,7 +171,7 @@ module ApplicationTests
body = last_response.body
last = last_response.headers["Last-Modified"]
- get "/expires/expires_last_modified", { private: true }, "If-Modified-Since" => last
+ get "/expires/expires_last_modified", { private: true }, "HTTP_IF_MODIFIED_SINCE" => last
assert_equal "miss", last_response.headers["X-Rack-Cache"]
assert_not_equal body, last_response.body
end
diff --git a/railties/test/application/rake/migrations_test.rb b/railties/test/application/rake/migrations_test.rb
index 76cb302c62..00f6620188 100644
--- a/railties/test/application/rake/migrations_test.rb
+++ b/railties/test/application/rake/migrations_test.rb
@@ -37,6 +37,22 @@ module ApplicationTests
end
end
+ test "migration with empty version" do
+ Dir.chdir(app_path) do
+ output = `bin/rails db:migrate VERSION= 2>&1`
+ assert_match(/Empty VERSION provided/, output)
+
+ output = `bin/rails db:migrate:redo VERSION= 2>&1`
+ assert_match(/Empty VERSION provided/, output)
+
+ output = `bin/rails db:migrate:up VERSION= 2>&1`
+ assert_match(/VERSION is required/, output)
+
+ output = `bin/rails db:migrate:down VERSION= 2>&1`
+ assert_match(/VERSION is required - To go down one migration, use db:rollback/, output)
+ end
+ end
+
test "model and migration generator with change syntax" do
Dir.chdir(app_path) do
`bin/rails generate model user username:string password:string;
diff --git a/railties/test/application/runner_test.rb b/railties/test/application/runner_test.rb
index 7d058f6ee6..0c45bc398a 100644
--- a/railties/test/application/runner_test.rb
+++ b/railties/test/application/runner_test.rb
@@ -35,6 +35,14 @@ module ApplicationTests
assert_match "42", Dir.chdir(app_path) { `bin/rails runner "puts User.count"` }
end
+ def test_should_set_argv_when_running_code
+ output = Dir.chdir(app_path) {
+ # Both long and short args, at start and end of ARGV
+ `bin/rails runner "puts ARGV.join(',')" --foo a1 -b a2 a3 --moo`
+ }
+ assert_equal "--foo,a1,-b,a2,a3,--moo", output.chomp
+ end
+
def test_should_run_file
app_file "bin/count_users.rb", <<-SCRIPT
puts User.count
diff --git a/railties/test/commands/server_test.rb b/railties/test/commands/server_test.rb
index d21a80982b..2d1f071969 100644
--- a/railties/test/commands/server_test.rb
+++ b/railties/test/commands/server_test.rb
@@ -139,6 +139,14 @@ class Rails::ServerTest < ActiveSupport::TestCase
end
end
+ def test_argument_precedence_over_environment_variable
+ switch_env "HOST", "1.2.3.4" do
+ args = ["-b", "127.0.0.1"]
+ options = parse_arguments(args)
+ assert_equal "127.0.0.1", options[:Host]
+ end
+ end
+
def test_records_user_supplied_options
server_options = parse_arguments(["-p", 3001])
assert_equal [:Port], server_options[:user_supplied_options]
diff --git a/railties/test/generators/api_app_generator_test.rb b/railties/test/generators/api_app_generator_test.rb
index bb8b29501a..2edb39c8e8 100644
--- a/railties/test/generators/api_app_generator_test.rb
+++ b/railties/test/generators/api_app_generator_test.rb
@@ -61,6 +61,28 @@ class ApiAppGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_app_update_does_not_generate_unnecessary_config_files
+ run_generator
+
+ generator = Rails::Generators::AppGenerator.new ["rails"],
+ { api: true, update: true }, destination_root: destination_root, shell: @shell
+ quietly { generator.send(:update_config_files) }
+
+ assert_no_file "config/initializers/cookies_serializer.rb"
+ assert_no_file "config/initializers/assets.rb"
+ assert_no_file "config/initializers/new_framework_defaults_5_1.rb"
+ end
+
+ def test_app_update_does_not_generate_unnecessary_bin_files
+ run_generator
+
+ generator = Rails::Generators::AppGenerator.new ["rails"],
+ { api: true, update: true }, destination_root: destination_root, shell: @shell
+ quietly { generator.send(:update_bin_files) }
+
+ assert_no_file "bin/yarn"
+ end
+
private
def default_files
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index ac43e8d22d..7965bd68d0 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -199,20 +199,6 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
- def test_app_update_dont_set_file_watcher
- app_root = File.join(destination_root, "myapp")
- run_generator [app_root]
-
- stub_rails_application(app_root) do
- generator = Rails::Generators::AppGenerator.new ["rails"], [], destination_root: app_root, shell: @shell
- generator.send(:app_const)
- quietly { generator.send(:update_config_files) }
- assert_file "#{app_root}/config/environments/development.rb" do |content|
- assert_match(/# config.file_watcher/, content)
- end
- end
- end
-
def test_app_update_create_new_framework_defaults
app_root = File.join(destination_root, "myapp")
run_generator [app_root]
@@ -450,6 +436,30 @@ class AppGeneratorTest < Rails::Generators::TestCase
assert_file "Gemfile", /^# gem 'redis'/
end
+ def test_generator_if_skip_test_is_given
+ run_generator [destination_root, "--skip-test"]
+ assert_file "Gemfile" do |content|
+ assert_no_match(/capybara/, content)
+ assert_no_match(/selenium-webdriver/, content)
+ end
+ end
+
+ def test_generator_if_skip_system_test_is_given
+ run_generator [destination_root, "--skip_system_test"]
+ assert_file "Gemfile" do |content|
+ assert_no_match(/capybara/, content)
+ assert_no_match(/selenium-webdriver/, content)
+ end
+ end
+
+ def test_generator_if_api_is_given
+ run_generator [destination_root, "--api"]
+ assert_file "Gemfile" do |content|
+ assert_no_match(/capybara/, content)
+ assert_no_match(/selenium-webdriver/, content)
+ end
+ end
+
def test_inclusion_of_javascript_runtime
run_generator
if defined?(JRUBY_VERSION)
@@ -466,14 +476,6 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
- def test_inclusion_of_javascript_libraries_if_required
- run_generator [destination_root, "-j", "jquery"]
- assert_file "app/assets/javascripts/application.js" do |contents|
- assert_match %r{^//= require jquery}, contents
- end
- assert_gem "jquery-rails"
- end
-
def test_javascript_is_skipped_if_required
run_generator [destination_root, "--skip-javascript"]
diff --git a/railties/test/generators/scaffold_generator_test.rb b/railties/test/generators/scaffold_generator_test.rb
index 0e0ef7d293..bc76cead18 100644
--- a/railties/test/generators/scaffold_generator_test.rb
+++ b/railties/test/generators/scaffold_generator_test.rb
@@ -437,8 +437,8 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
end
assert_file "app/views/accounts/_form.html.erb" do |content|
- assert_match(/^\W{4}<%= form\.text_field :name %>/, content)
- assert_match(/^\W{4}<%= form\.text_field :currency_id %>/, content)
+ assert_match(/^\W{4}<%= form\.text_field :name, id: :account_name %>/, content)
+ assert_match(/^\W{4}<%= form\.text_field :currency_id, id: :account_currency_id %>/, content)
end
end
@@ -461,8 +461,8 @@ class ScaffoldGeneratorTest < Rails::Generators::TestCase
end
assert_file "app/views/users/_form.html.erb" do |content|
- assert_match(/<%= form\.password_field :password %>/, content)
- assert_match(/<%= form\.password_field :password_confirmation %>/, content)
+ assert_match(/<%= form\.password_field :password, id: :user_password %>/, content)
+ assert_match(/<%= form\.password_field :password_confirmation, id: :user_password_confirmation %>/, content)
end
assert_file "app/views/users/index.html.erb" do |content|
diff --git a/version.rb b/version.rb
index 3174ffb0dc..7bacf2e0ba 100644
--- a/version.rb
+++ b/version.rb
@@ -6,9 +6,9 @@ module Rails
module VERSION
MAJOR = 5
- MINOR = 1
+ MINOR = 2
TINY = 0
- PRE = "beta1"
+ PRE = "alpha"
STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".")
end