diff options
665 files changed, 6116 insertions, 3850 deletions
diff --git a/.codeclimate.yml b/.codeclimate.yml index 7114a98266..952b330d8c 100644 --- a/.codeclimate.yml +++ b/.codeclimate.yml @@ -25,6 +25,6 @@ checks: plugins: rubocop: enabled: true - channel: rubocop-0-67 + channel: rubocop-0-71 exclude_patterns: [] diff --git a/.rubocop.yml b/.rubocop.yml index 0cfe5d5d84..e310351bf5 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,4 +1,6 @@ -require: rubocop-performance +require: + - rubocop-performance + - rubocop-rails AllCops: TargetRubyVersion: 2.5 @@ -18,9 +20,6 @@ Performance: Exclude: - '**/test/**/*' -Rails: - Enabled: true - # Prefer assert_not over assert ! Rails/AssertNot: Include: @@ -62,6 +61,10 @@ Layout/EndAlignment: Layout/EmptyLineAfterMagicComment: Enabled: true +Layout/EmptyLinesAroundAccessModifier: + Enabled: true + EnforcedStyle: only_before + Layout/EmptyLinesAroundBlockBody: Enabled: true @@ -77,13 +80,13 @@ Layout/EmptyLinesAroundMethodBody: Layout/EmptyLinesAroundModuleBody: Enabled: true -Layout/FirstParameterIndentation: - Enabled: true - # Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. Style/HashSyntax: Enabled: true +Layout/IndentFirstArgument: + Enabled: true + # Method definitions after `private` or `protected` isolated calls need one # extra level of indentation. Layout/IndentationConsistency: @@ -9,8 +9,8 @@ gemspec # We need a newish Rake since Active Job sets its test tasks' descriptions. gem "rake", ">= 11.1" -gem "capybara", ">= 2.15" -gem "selenium-webdriver", ">= 3.5.0", "< 3.13.0" +gem "capybara", ">= 3.26" +gem "selenium-webdriver", ">= 3.141.592" gem "rack-cache", "~> 1.2" gem "sass-rails" @@ -30,6 +30,7 @@ gem "json", ">= 2.0.0" gem "rubocop", ">= 0.47", require: false gem "rubocop-performance", require: false +gem "rubocop-rails", require: false group :doc do gem "sdoc", "~> 1.0" diff --git a/Gemfile.lock b/Gemfile.lock index 6633c7a741..0618bcf7ec 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -71,7 +71,7 @@ PATH i18n (>= 0.7, < 2) minitest (~> 5.1) tzinfo (~> 1.1) - zeitwerk (~> 2.1, >= 2.1.4) + zeitwerk (~> 2.1, >= 2.1.8) rails (6.1.0.alpha) actioncable (= 6.1.0.alpha) actionmailbox (= 6.1.0.alpha) @@ -175,16 +175,16 @@ GEM bunny (2.13.0) amq-protocol (~> 2.3, >= 2.3.0) byebug (10.0.2) - capybara (3.10.1) + capybara (3.26.0) addressable mini_mime (>= 0.1.3) nokogiri (~> 1.8) rack (>= 1.6.0) rack-test (>= 0.6.3) - regexp_parser (~> 1.2) + regexp_parser (~> 1.5) xpath (~> 3.2) - childprocess (0.9.0) - ffi (~> 1.0, >= 1.0.11) + childprocess (1.0.1) + rake (< 13.0) coffee-script (2.4.1) coffee-script-source execjs @@ -236,10 +236,10 @@ GEM faye-websocket (0.10.7) eventmachine (>= 0.12.0) websocket-driver (>= 0.5.1) - ffi (1.10.0) - ffi (1.10.0-java) - ffi (1.10.0-x64-mingw32) - ffi (1.10.0-x86-mingw32) + ffi (1.11.1) + ffi (1.11.1-java) + ffi (1.11.1-x64-mingw32) + ffi (1.11.1-x86-mingw32) fugit (1.2.1) et-orbi (~> 1.1, >= 1.1.8) raabro (~> 1.1) @@ -279,7 +279,6 @@ GEM image_processing (1.7.1) mini_magick (~> 4.0) ruby-vips (>= 2.0.13, < 3) - jar-dependencies (0.4.0) jaro_winkler (1.5.2) jaro_winkler (1.5.2-java) jdbc-mysql (5.1.46) @@ -338,29 +337,24 @@ GEM mysql2 (0.5.2) mysql2 (0.5.2-x64-mingw32) mysql2 (0.5.2-x86-mingw32) - net_http_ssl_fix (0.0.10) nio4r (2.3.1) nio4r (2.3.1-java) - nokogiri (1.9.1) + nokogiri (1.10.3) mini_portile2 (~> 2.4.0) - nokogiri (1.9.1-java) - nokogiri (1.9.1-x64-mingw32) + nokogiri (1.10.3-java) + nokogiri (1.10.3-x64-mingw32) mini_portile2 (~> 2.4.0) - nokogiri (1.9.1-x86-mingw32) + nokogiri (1.10.3-x86-mingw32) mini_portile2 (~> 2.4.0) os (1.0.0) - parallel (1.13.0) - parser (2.6.2.0) + parallel (1.17.0) + parser (2.6.3.0) ast (~> 2.4.0) path_expander (1.0.3) pg (1.1.3) pg (1.1.3-x64-mingw32) pg (1.1.3-x86-mingw32) psych (3.1.0) - psych (3.1.0-java) - jar-dependencies (>= 0.1.7) - psych (3.1.0-x64-mingw32) - psych (3.1.0-x86-mingw32) public_suffix (3.0.3) puma (3.12.1) puma (3.12.1-java) @@ -394,7 +388,7 @@ GEM redis (4.1.1) redis-namespace (1.6.0) redis (>= 3.0.4) - regexp_parser (1.3.0) + regexp_parser (1.6.0) representable (3.0.4) declarative (< 0.1.0) declarative-option (< 0.2.0) @@ -411,21 +405,23 @@ GEM resque (>= 1.26) rufus-scheduler (~> 3.2) retriable (3.1.2) - rubocop (0.67.2) + rubocop (0.71.0) jaro_winkler (~> 1.5.1) parallel (~> 1.10) - parser (>= 2.5, != 2.5.1.1) - psych (>= 3.1.0) + parser (>= 2.6) rainbow (>= 2.2.2, < 4.0) ruby-progressbar (~> 1.7) - unicode-display_width (>= 1.4.0, < 1.6) + unicode-display_width (>= 1.4.0, < 1.7) rubocop-performance (1.1.0) rubocop (>= 0.67.0) - ruby-progressbar (1.10.0) + rubocop-rails (2.0.0) + rack (>= 2.0) + rubocop (>= 0.70.0) + ruby-progressbar (1.10.1) ruby-vips (2.0.13) ffi (~> 1.9) ruby_dep (1.5.0) - rubyzip (1.2.2) + rubyzip (1.2.3) rufus-scheduler (3.6.0) fugit (~> 1.1, >= 1.1.6) safe_yaml (1.0.4) @@ -442,9 +438,9 @@ GEM tilt (>= 1.1, < 3) sdoc (1.0.0) rdoc (>= 5.0) - selenium-webdriver (3.12.0) - childprocess (~> 0.5) - rubyzip (~> 1.2) + selenium-webdriver (3.142.3) + childprocess (>= 0.5, < 2.0) + rubyzip (~> 1.2, >= 1.2.2) sequel (5.14.0) serverengine (2.0.7) sigdump (~> 0.2.2) @@ -499,7 +495,7 @@ GEM uber (0.1.0) uglifier (4.1.19) execjs (>= 0.3.0, < 3) - unicode-display_width (1.5.0) + unicode-display_width (1.6.0) useragent (0.16.10) vegas (0.1.11) rack (>= 1.0.0) @@ -507,8 +503,7 @@ GEM json (>= 1.8) nokogiri (~> 1.6) wdm (0.1.1) - webdrivers (3.7.0) - net_http_ssl_fix + webdrivers (4.0.0) nokogiri (~> 1.6) rubyzip (~> 1.0) selenium-webdriver (~> 3.0) @@ -528,7 +523,7 @@ GEM websocket-extensions (0.1.3) xpath (3.2.0) nokogiri (~> 1.8) - zeitwerk (2.1.4) + zeitwerk (2.1.8) PLATFORMS java @@ -550,7 +545,7 @@ DEPENDENCIES blade-sauce_labs_plugin bootsnap (>= 1.4.4) byebug - capybara (>= 2.15) + capybara (>= 3.26) connection_pool dalli delayed_job @@ -584,9 +579,10 @@ DEPENDENCIES resque-scheduler rubocop (>= 0.47) rubocop-performance + rubocop-rails sass-rails sdoc (~> 1.0) - selenium-webdriver (>= 3.5.0, < 3.13.0) + selenium-webdriver (>= 3.141.592) sequel sidekiq sneakers diff --git a/actioncable/lib/action_cable/server/broadcasting.rb b/actioncable/lib/action_cable/server/broadcasting.rb index bc54d784b3..b73cfa7d1f 100644 --- a/actioncable/lib/action_cable/server/broadcasting.rb +++ b/actioncable/lib/action_cable/server/broadcasting.rb @@ -40,7 +40,7 @@ module ActionCable end def broadcast(message) - server.logger.debug "[ActionCable] Broadcasting to #{broadcasting}: #{message.inspect}" + server.logger.debug { "[ActionCable] Broadcasting to #{broadcasting}: #{message.inspect}" } payload = { broadcasting: broadcasting, message: message, coder: coder } ActiveSupport::Notifications.instrument("broadcast.action_cable", payload) do diff --git a/actioncable/lib/action_cable/server/worker.rb b/actioncable/lib/action_cable/server/worker.rb index 187c8f7939..b918d4ae72 100644 --- a/actioncable/lib/action_cable/server/worker.rb +++ b/actioncable/lib/action_cable/server/worker.rb @@ -66,7 +66,6 @@ module ActionCable end private - def logger ActionCable.server.logger end diff --git a/actionmailbox/app/controllers/rails/conductor/action_mailbox/inbound_emails_controller.rb b/actionmailbox/app/controllers/rails/conductor/action_mailbox/inbound_emails_controller.rb index d051dfe665..8713f545f5 100644 --- a/actionmailbox/app/controllers/rails/conductor/action_mailbox/inbound_emails_controller.rb +++ b/actionmailbox/app/controllers/rails/conductor/action_mailbox/inbound_emails_controller.rb @@ -21,6 +21,7 @@ module Rails private def new_mail Mail.new(params.require(:mail).permit(:from, :to, :cc, :bcc, :in_reply_to, :subject, :body).to_h).tap do |mail| + mail[:bcc]&.include_in_headers = true params[:mail][:attachments].to_a.each do |attachment| mail.add_file(filename: attachment.path, content: attachment.read) end diff --git a/actionmailbox/test/controllers/rails/action_mailbox/inbound_emails_controller_test.rb b/actionmailbox/test/controllers/rails/action_mailbox/inbound_emails_controller_test.rb index fcd9ad839f..6fc39c2433 100644 --- a/actionmailbox/test/controllers/rails/action_mailbox/inbound_emails_controller_test.rb +++ b/actionmailbox/test/controllers/rails/action_mailbox/inbound_emails_controller_test.rb @@ -10,6 +10,8 @@ class Rails::Conductor::ActionMailbox::InboundEmailsControllerTest < ActionDispa mail: { from: "Jason Fried <jason@37signals.com>", to: "Replies <replies@example.com>", + cc: "CC <cc@example.com>", + bcc: "Bcc <bcc@example.com>", in_reply_to: "<4e6e35f5a38b4_479f13bb90078178@small-app-01.mail>", subject: "Hey there", body: "How's it going?" @@ -20,6 +22,8 @@ class Rails::Conductor::ActionMailbox::InboundEmailsControllerTest < ActionDispa mail = ActionMailbox::InboundEmail.last.mail assert_equal %w[ jason@37signals.com ], mail.from assert_equal %w[ replies@example.com ], mail.to + assert_equal %w[ cc@example.com ], mail.cc + assert_equal %w[ bcc@example.com ], mail.bcc assert_equal "4e6e35f5a38b4_479f13bb90078178@small-app-01.mail", mail.in_reply_to assert_equal "Hey there", mail.subject assert_equal "How's it going?", mail.body.decoded diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index c1ac9c2ad1..ba914c4813 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -591,7 +591,6 @@ module ActionMailer end private - def set_payload_for_mail(payload, mail) payload[:mail] = mail.encoded payload[:mailer] = name @@ -873,7 +872,6 @@ module ActionMailer end private - # Used by #mail to set the content type of the message. # # It will use the given +user_content_type+, or multipart if the mail diff --git a/actionmailer/lib/action_mailer/preview.rb b/actionmailer/lib/action_mailer/preview.rb index 500b3bede0..a763b9776c 100644 --- a/actionmailer/lib/action_mailer/preview.rb +++ b/actionmailer/lib/action_mailer/preview.rb @@ -55,7 +55,6 @@ module ActionMailer end private - def interceptor_class_for(interceptor) case interceptor when String, Symbol diff --git a/actionmailer/lib/action_mailer/test_case.rb b/actionmailer/lib/action_mailer/test_case.rb index ee5a864847..97afd87840 100644 --- a/actionmailer/lib/action_mailer/test_case.rb +++ b/actionmailer/lib/action_mailer/test_case.rb @@ -22,7 +22,6 @@ module ActionMailer end private - def clear_test_deliveries if ActionMailer::Base.delivery_method == :test ActionMailer::Base.deliveries.clear @@ -76,7 +75,6 @@ module ActionMailer end private - def initialize_test_deliveries set_delivery_method :test @old_perform_deliveries = ActionMailer::Base.perform_deliveries diff --git a/actionmailer/lib/action_mailer/test_helper.rb b/actionmailer/lib/action_mailer/test_helper.rb index e222301dff..988db2491c 100644 --- a/actionmailer/lib/action_mailer/test_helper.rb +++ b/actionmailer/lib/action_mailer/test_helper.rb @@ -152,7 +152,6 @@ module ActionMailer end private - def delivery_job_filter(job) job_class = job.is_a?(Hash) ? job.fetch(:job) : job.class diff --git a/actionmailer/test/base_test.rb b/actionmailer/test/base_test.rb index c07fca5b5e..4ea5634cd0 100644 --- a/actionmailer/test/base_test.rb +++ b/actionmailer/test/base_test.rb @@ -939,7 +939,6 @@ class BaseTest < ActiveSupport::TestCase end private - # Execute the block setting the given values and restoring old values after # the block is executed. def swap(klass, new_values) diff --git a/actionmailer/test/caching_test.rb b/actionmailer/test/caching_test.rb index b658c96ec7..c3a3e418d0 100644 --- a/actionmailer/test/caching_test.rb +++ b/actionmailer/test/caching_test.rb @@ -189,7 +189,6 @@ class FunctionalFragmentCachingTest < BaseCachingTest end private - def template_digest(name, format) ActionView::Digestor.digest(name: name, format: format, finder: @mailer.lookup_context) end diff --git a/actionmailer/test/i18n_with_controller_test.rb b/actionmailer/test/i18n_with_controller_test.rb index 6e75cff347..eea72e06ba 100644 --- a/actionmailer/test/i18n_with_controller_test.rb +++ b/actionmailer/test/i18n_with_controller_test.rb @@ -67,7 +67,6 @@ class ActionMailerI18nWithControllerTest < ActionDispatch::IntegrationTest end private - def with_translation(locale, data) I18n.backend.store_translations(locale, data) yield diff --git a/actionmailer/test/legacy_delivery_job_test.rb b/actionmailer/test/legacy_delivery_job_test.rb index 3a3872df47..a9b2a160d4 100644 --- a/actionmailer/test/legacy_delivery_job_test.rb +++ b/actionmailer/test/legacy_delivery_job_test.rb @@ -69,7 +69,6 @@ class LegacyDeliveryJobTest < ActiveSupport::TestCase end private - def with_delivery_job(job) old_params_delivery_job = ParamsMailer.delivery_job old_regular_delivery_job = DelayedMailer.delivery_job diff --git a/actionmailer/test/mail_helper_test.rb b/actionmailer/test/mail_helper_test.rb index 51d6ccb10f..a8ab19a95c 100644 --- a/actionmailer/test/mail_helper_test.rb +++ b/actionmailer/test/mail_helper_test.rb @@ -68,7 +68,6 @@ The second end private - def mail_with_defaults(&block) mail(to: "test@localhost", from: "tester@example.com", subject: "using helpers", &block) diff --git a/actionmailer/test/mailers/proc_mailer.rb b/actionmailer/test/mailers/proc_mailer.rb index 76e730bb79..75ee5dd9b6 100644 --- a/actionmailer/test/mailers/proc_mailer.rb +++ b/actionmailer/test/mailers/proc_mailer.rb @@ -18,7 +18,6 @@ class ProcMailer < ActionMailer::Base end private - def give_a_greeting "Thanks for signing up this afternoon" end diff --git a/actionmailer/test/parameterized_test.rb b/actionmailer/test/parameterized_test.rb index 7dd6156744..62dd671f48 100644 --- a/actionmailer/test/parameterized_test.rb +++ b/actionmailer/test/parameterized_test.rb @@ -81,7 +81,6 @@ class ParameterizedTest < ActiveSupport::TestCase end private - def with_delivery_job(job) old_delivery_job = ParamsMailer.delivery_job ParamsMailer.delivery_job = job diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index 55592585ea..ca7ae6621b 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -1,3 +1,55 @@ +* Fix IntegrationTest `follow_redirect!` to follow redirection using the same HTTP verb when following + a 307 redirection. + + *Edouard Chin* + +* System tests require Capybara 3.26 or newer. + + *George Claghorn* + +* Reduced log noise handling ActionController::RoutingErrors. + + *Alberto Fernández-Capel* + +* Add DSL for configuring HTTP Feature Policy + + This new DSL provides a way to configure a HTTP Feature Policy at a + global or per-controller level. Full details of HTTP Feature Policy + specification and guidelines can be found at MDN: + + https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy + + Example global policy + + ``` + Rails.application.config.feature_policy do |f| + f.camera :none + f.gyroscope :none + f.microphone :none + f.usb :none + f.fullscreen :self + f.payment :self, "https://secure.example.com" + end + ``` + + Example controller level policy + + ``` + class PagesController < ApplicationController + feature_policy do |p| + p.geolocation "https://example.com" + end + end + ``` + + *Jacob Bednarz* + +* Add the ability to set the CSP nonce only to the specified directives. + + Fixes #35137. + + *Yuji Yaginuma* + * Keep part when scope option has value. When a route was defined within an optional scope, if that route didn't diff --git a/actionpack/lib/abstract_controller.rb b/actionpack/lib/abstract_controller.rb index 3a98931167..d1ff62a032 100644 --- a/actionpack/lib/abstract_controller.rb +++ b/actionpack/lib/abstract_controller.rb @@ -1,6 +1,7 @@ # frozen_string_literal: true require "action_pack" +require "active_support" require "active_support/rails" require "active_support/i18n" diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb index bb42f2e119..3ff922029b 100644 --- a/actionpack/lib/abstract_controller/base.rb +++ b/actionpack/lib/abstract_controller/base.rb @@ -176,7 +176,6 @@ module AbstractController end private - # Returns true if the name can be considered an action because # it has a method defined in the controller. # diff --git a/actionpack/lib/abstract_controller/collector.rb b/actionpack/lib/abstract_controller/collector.rb index d4a078ab32..0af546cc96 100644 --- a/actionpack/lib/abstract_controller/collector.rb +++ b/actionpack/lib/abstract_controller/collector.rb @@ -22,7 +22,6 @@ module AbstractController end private - def method_missing(symbol, &block) unless mime_constant = Mime[symbol] raise NoMethodError, "To respond to a custom format, register it as a MIME type first: " \ diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb index 3913259ecc..abb09456e0 100644 --- a/actionpack/lib/abstract_controller/helpers.rb +++ b/actionpack/lib/abstract_controller/helpers.rb @@ -7,7 +7,7 @@ module AbstractController extend ActiveSupport::Concern included do - class_attribute :_helpers, default: Module.new + class_attribute :_helpers, default: define_helpers_module(self) class_attribute :_helper_methods, default: Array.new end @@ -31,7 +31,7 @@ module AbstractController # independently of the child class's. def inherited(klass) helpers = _helpers - klass._helpers = Module.new { include helpers } + klass._helpers = define_helpers_module(klass, helpers) klass.class_eval { default_helper_module! } unless klass.anonymous? super end @@ -61,12 +61,17 @@ module AbstractController meths.flatten! self._helper_methods += meths + location = caller_locations(1, 1).first + file, line = location.path, location.lineno + meths.each do |meth| - _helpers.class_eval <<-ruby_eval, __FILE__, __LINE__ + 1 - def #{meth}(*args, &blk) # def current_user(*args, &blk) - controller.send(%(#{meth}), *args, &blk) # controller.send(:current_user, *args, &blk) - end # end - ruby_eval + method_def = [ + "def #{meth}(*args, &blk)", + " controller.send(%(#{meth}), *args, &blk)", + "end" + ].join(";") + + _helpers.class_eval method_def, file, line end end @@ -170,6 +175,17 @@ module AbstractController end private + def define_helpers_module(klass, helpers = nil) + # In some tests inherited is called explicitly. In that case, just + # return the module from the first time it was defined + return klass.const_get(:HelperMethods) if klass.const_defined?(:HelperMethods, false) + + mod = Module.new + klass.const_set(:HelperMethods, mod) + mod.include(helpers) if helpers + mod + end + # Makes all the (instance) methods in the helper module available to templates # rendered through this controller. # diff --git a/actionpack/lib/action_controller.rb b/actionpack/lib/action_controller.rb index 29d61c3ceb..22dc229599 100644 --- a/actionpack/lib/action_controller.rb +++ b/actionpack/lib/action_controller.rb @@ -1,6 +1,5 @@ # frozen_string_literal: true -require "active_support/rails" require "abstract_controller" require "action_dispatch" require "action_controller/metal/live" @@ -28,6 +27,7 @@ module ActionController autoload :DefaultHeaders autoload :EtagWithTemplateDigest autoload :EtagWithFlash + autoload :FeaturePolicy autoload :Flash autoload :ForceSSL autoload :Head diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 2e565d5d44..63c138af55 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -226,6 +226,7 @@ module ActionController FormBuilder, RequestForgeryProtection, ContentSecurityPolicy, + FeaturePolicy, ForceSSL, Streaming, DataStreaming, diff --git a/actionpack/lib/action_controller/caching.rb b/actionpack/lib/action_controller/caching.rb index bf3b00a7b7..83e3e0c37c 100644 --- a/actionpack/lib/action_controller/caching.rb +++ b/actionpack/lib/action_controller/caching.rb @@ -30,7 +30,6 @@ module ActionController end private - def instrument_payload(key) { controller: controller_name, diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb index 9ca0bbb9db..ec2207b8da 100644 --- a/actionpack/lib/action_controller/metal.rb +++ b/actionpack/lib/action_controller/metal.rb @@ -35,7 +35,6 @@ module ActionController end private - INCLUDE = ->(list, action) { list.include? action } EXCLUDE = ->(list, action) { !list.include? action } NULL = ->(list, action) { true } diff --git a/actionpack/lib/action_controller/metal/content_security_policy.rb b/actionpack/lib/action_controller/metal/content_security_policy.rb index b8fab4ebe3..ebd90f07c8 100644 --- a/actionpack/lib/action_controller/metal/content_security_policy.rb +++ b/actionpack/lib/action_controller/metal/content_security_policy.rb @@ -36,7 +36,6 @@ module ActionController #:nodoc: end private - def content_security_policy? request.content_security_policy end diff --git a/actionpack/lib/action_controller/metal/data_streaming.rb b/actionpack/lib/action_controller/metal/data_streaming.rb index 9ef4f50df1..879745a895 100644 --- a/actionpack/lib/action_controller/metal/data_streaming.rb +++ b/actionpack/lib/action_controller/metal/data_streaming.rb @@ -53,7 +53,7 @@ module ActionController #:nodoc: # # Show a 404 page in the browser: # - # send_file '/path/to/404.html', type: 'text/html; charset=utf-8', status: 404 + # send_file '/path/to/404.html', type: 'text/html; charset=utf-8', disposition: 'inline', status: 404 # # Read about the other Content-* HTTP headers if you'd like to # provide the user with more information (such as Content-Description) in diff --git a/actionpack/lib/action_controller/metal/feature_policy.rb b/actionpack/lib/action_controller/metal/feature_policy.rb new file mode 100644 index 0000000000..a627eabea6 --- /dev/null +++ b/actionpack/lib/action_controller/metal/feature_policy.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +module ActionController #:nodoc: + # HTTP Feature Policy is a web standard for defining a mechanism to + # allow and deny the use of browser features in its own context, and + # in content within any <iframe> elements in the document. + # + # Full details of HTTP Feature Policy specification and guidelines can + # be found at MDN: + # + # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Feature-Policy + # + # Examples of usage: + # + # # Global policy + # Rails.application.config.feature_policy do |f| + # f.camera :none + # f.gyroscope :none + # f.microphone :none + # f.usb :none + # f.fullscreen :self + # f.payment :self, "https://secure.example.com" + # end + # + # # Controller level policy + # class PagesController < ApplicationController + # feature_policy do |p| + # p.geolocation "https://example.com" + # end + # end + module FeaturePolicy + extend ActiveSupport::Concern + + module ClassMethods + def feature_policy(**options, &block) + before_action(options) do + if block_given? + policy = request.feature_policy.clone + yield policy + request.feature_policy = policy + end + end + end + end + end +end diff --git a/actionpack/lib/action_controller/metal/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb index 51fac08749..6f7fc0d624 100644 --- a/actionpack/lib/action_controller/metal/instrumentation.rb +++ b/actionpack/lib/action_controller/metal/instrumentation.rb @@ -69,7 +69,6 @@ module ActionController end private - # A hook invoked every time a before callback is halted. def halted_callback_hook(filter) ActiveSupport::Notifications.instrument("halted_callback.action_controller", filter: filter) diff --git a/actionpack/lib/action_controller/metal/live.rb b/actionpack/lib/action_controller/metal/live.rb index dd69930e25..4454ba1e3d 100644 --- a/actionpack/lib/action_controller/metal/live.rb +++ b/actionpack/lib/action_controller/metal/live.rb @@ -107,7 +107,6 @@ module ActionController end private - def perform_write(json, options) current_options = @options.merge(options).stringify_keys @@ -205,7 +204,6 @@ module ActionController end private - def each_chunk(&block) loop do str = nil @@ -220,7 +218,6 @@ module ActionController class Response < ActionDispatch::Response #:nodoc: all private - def before_committed super jar = request.cookie_jar @@ -286,7 +283,6 @@ module ActionController end private - # Spawn a new thread to serve up the controller in. This is to get # around the fact that Rack isn't based around IOs and we need to use # a thread to stream data from the response bodies. Nobody should call diff --git a/actionpack/lib/action_controller/metal/params_wrapper.rb b/actionpack/lib/action_controller/metal/params_wrapper.rb index e635abec8e..150ae2666c 100644 --- a/actionpack/lib/action_controller/metal/params_wrapper.rb +++ b/actionpack/lib/action_controller/metal/params_wrapper.rb @@ -246,7 +246,6 @@ module ActionController end private - # Returns the wrapper key which will be used to store wrapped parameters. def _wrapper_key _wrapper_options.name diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb index 7f7c736965..efa5de313c 100644 --- a/actionpack/lib/action_controller/metal/rendering.rb +++ b/actionpack/lib/action_controller/metal/rendering.rb @@ -53,7 +53,6 @@ module ActionController end private - def _process_variant(options) if defined?(request) && !request.nil? && request.variant.present? options[:variant] = request.variant diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb index 4bf8d90b69..5a5c04234b 100644 --- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb +++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb @@ -151,7 +151,6 @@ module ActionController #:nodoc: end private - def protection_method_class(name) ActionController::RequestForgeryProtection::ProtectionMethods.const_get(name.to_s.classify) rescue NameError @@ -175,7 +174,6 @@ module ActionController #:nodoc: end private - class NullSessionHash < Rack::Session::Abstract::SessionHash #:nodoc: def initialize(req) super(nil, req) diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb index 8dc01a5eb9..94a62e5cab 100644 --- a/actionpack/lib/action_controller/metal/streaming.rb +++ b/actionpack/lib/action_controller/metal/streaming.rb @@ -196,7 +196,6 @@ module ActionController #:nodoc: extend ActiveSupport::Concern private - # Set proper cache control and transfer encoding when streaming def _process_options(options) super diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb index 27c2a8db36..920ae52f2b 100644 --- a/actionpack/lib/action_controller/metal/strong_parameters.rb +++ b/actionpack/lib/action_controller/metal/strong_parameters.rb @@ -259,6 +259,11 @@ module ActionController @parameters == other end end + alias eql? == + + def hash + [@parameters.hash, @permitted].hash + end # Returns a safe <tt>ActiveSupport::HashWithIndifferentAccess</tt> # representation of the parameters with all unpermitted keys removed. diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 57921f32b7..47e0099f20 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -158,7 +158,6 @@ module ActionController end.new private - def params_parsers super.merge @custom_param_parsers end @@ -208,7 +207,6 @@ module ActionController end private - def load! @id end @@ -594,7 +592,6 @@ module ActionController end private - def scrub_env!(env) env.delete_if { |k, v| k =~ /^(action_dispatch|rack)\.request/ } env.delete_if { |k, v| k =~ /^action_dispatch\.rescue/ } diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb index 6a4ba9af4a..67d303a368 100644 --- a/actionpack/lib/action_dispatch.rb +++ b/actionpack/lib/action_dispatch.rb @@ -43,6 +43,7 @@ module ActionDispatch eager_autoload do autoload_under "http" do autoload :ContentSecurityPolicy + autoload :FeaturePolicy autoload :Request autoload :Response end diff --git a/actionpack/lib/action_dispatch/http/cache.rb b/actionpack/lib/action_dispatch/http/cache.rb index 8cc84ff36c..7be30be77a 100644 --- a/actionpack/lib/action_dispatch/http/cache.rb +++ b/actionpack/lib/action_dispatch/http/cache.rb @@ -123,7 +123,6 @@ module ActionDispatch end private - DATE = "Date" LAST_MODIFIED = "Last-Modified" SPECIAL_KEYS = Set.new(%w[extras no-cache max-age public private must-revalidate]) diff --git a/actionpack/lib/action_dispatch/http/content_security_policy.rb b/actionpack/lib/action_dispatch/http/content_security_policy.rb index b1e5a28be5..9c430b57e3 100644 --- a/actionpack/lib/action_dispatch/http/content_security_policy.rb +++ b/actionpack/lib/action_dispatch/http/content_security_policy.rb @@ -22,15 +22,15 @@ module ActionDispatch #:nodoc: if policy = request.content_security_policy nonce = request.content_security_policy_nonce + nonce_directives = request.content_security_policy_nonce_directives context = request.controller_instance || request - headers[header_name(request)] = policy.build(context, nonce) + headers[header_name(request)] = policy.build(context, nonce, nonce_directives) end response end private - def html_response?(headers) if content_type = headers[CONTENT_TYPE] content_type =~ /html/ @@ -55,6 +55,7 @@ module ActionDispatch #:nodoc: POLICY_REPORT_ONLY = "action_dispatch.content_security_policy_report_only" NONCE_GENERATOR = "action_dispatch.content_security_policy_nonce_generator" NONCE = "action_dispatch.content_security_policy_nonce" + NONCE_DIRECTIVES = "action_dispatch.content_security_policy_nonce_directives" def content_security_policy get_header(POLICY) @@ -80,6 +81,14 @@ module ActionDispatch #:nodoc: set_header(NONCE_GENERATOR, generator) end + def content_security_policy_nonce_directives + get_header(NONCE_DIRECTIVES) + end + + def content_security_policy_nonce_directives=(generator) + set_header(NONCE_DIRECTIVES, generator) + end + def content_security_policy_nonce if content_security_policy_nonce_generator if nonce = get_header(NONCE) @@ -91,7 +100,6 @@ module ActionDispatch #:nodoc: end private - def generate_content_security_policy_nonce content_security_policy_nonce_generator.call(self) end @@ -129,13 +137,17 @@ module ActionDispatch #:nodoc: object_src: "object-src", prefetch_src: "prefetch-src", script_src: "script-src", + script_src_attr: "script-src-attr", + script_src_elem: "script-src-elem", style_src: "style-src", + style_src_attr: "style-src-attr", + style_src_elem: "style-src-elem", worker_src: "worker-src" }.freeze - NONCE_DIRECTIVES = %w[script-src style-src].freeze + DEFAULT_NONCE_DIRECTIVES = %w[script-src style-src].freeze - private_constant :MAPPINGS, :DIRECTIVES, :NONCE_DIRECTIVES + private_constant :MAPPINGS, :DIRECTIVES, :DEFAULT_NONCE_DIRECTIVES attr_reader :directives @@ -204,8 +216,9 @@ module ActionDispatch #:nodoc: end end - def build(context = nil, nonce = nil) - build_directives(context, nonce).compact.join("; ") + def build(context = nil, nonce = nil, nonce_directives = nil) + nonce_directives = DEFAULT_NONCE_DIRECTIVES if nonce_directives.nil? + build_directives(context, nonce, nonce_directives).compact.join("; ") end private @@ -228,10 +241,10 @@ module ActionDispatch #:nodoc: end end - def build_directives(context, nonce) + def build_directives(context, nonce, nonce_directives) @directives.map do |directive, sources| if sources.is_a?(Array) - if nonce && nonce_directive?(directive) + if nonce && nonce_directive?(directive, nonce_directives) "#{directive} #{build_directive(sources, context).join(' ')} 'nonce-#{nonce}'" else "#{directive} #{build_directive(sources, context).join(' ')}" @@ -266,8 +279,8 @@ module ActionDispatch #:nodoc: end end - def nonce_directive?(directive) - NONCE_DIRECTIVES.include?(directive) + def nonce_directive?(directive, nonce_directives) + nonce_directives.include?(directive) end end end diff --git a/actionpack/lib/action_dispatch/http/feature_policy.rb b/actionpack/lib/action_dispatch/http/feature_policy.rb new file mode 100644 index 0000000000..592b6e4393 --- /dev/null +++ b/actionpack/lib/action_dispatch/http/feature_policy.rb @@ -0,0 +1,168 @@ +# frozen_string_literal: true + +require "active_support/core_ext/object/deep_dup" + +module ActionDispatch #:nodoc: + class FeaturePolicy + class Middleware + CONTENT_TYPE = "Content-Type" + POLICY = "Feature-Policy" + + def initialize(app) + @app = app + end + + def call(env) + request = ActionDispatch::Request.new(env) + _, headers, _ = response = @app.call(env) + + return response unless html_response?(headers) + return response if policy_present?(headers) + + if policy = request.feature_policy + headers[POLICY] = policy.build(request.controller_instance) + end + + if policy_empty?(policy) + headers.delete(POLICY) + end + + response + end + + private + def html_response?(headers) + if content_type = headers[CONTENT_TYPE] + content_type =~ /html/ + end + end + + def policy_present?(headers) + headers[POLICY] + end + + def policy_empty?(policy) + policy.try(:directives) && policy.directives.empty? + end + end + + module Request + POLICY = "action_dispatch.feature_policy" + + def feature_policy + get_header(POLICY) + end + + def feature_policy=(policy) + set_header(POLICY, policy) + end + end + + MAPPINGS = { + self: "'self'", + none: "'none'", + }.freeze + + # List of available features can be found at + # https://github.com/WICG/feature-policy/blob/master/features.md#policy-controlled-features + DIRECTIVES = { + accelerometer: "accelerometer", + ambient_light_sensor: "ambient-light-sensor", + autoplay: "autoplay", + camera: "camera", + encrypted_media: "encrypted-media", + fullscreen: "fullscreen", + geolocation: "geolocation", + gyroscope: "gyroscope", + magnetometer: "magnetometer", + microphone: "microphone", + midi: "midi", + payment: "payment", + picture_in_picture: "picture-in-picture", + speaker: "speaker", + usb: "usb", + vibrate: "vibrate", + vr: "vr", + }.freeze + + private_constant :MAPPINGS, :DIRECTIVES + + attr_reader :directives + + def initialize + @directives = {} + yield self if block_given? + end + + def initialize_copy(other) + @directives = other.directives.deep_dup + end + + DIRECTIVES.each do |name, directive| + define_method(name) do |*sources| + if sources.first + @directives[directive] = apply_mappings(sources) + else + @directives.delete(directive) + end + end + end + + def build(context = nil) + build_directives(context).compact.join("; ") + end + + private + def apply_mappings(sources) + sources.map do |source| + case source + when Symbol + apply_mapping(source) + when String, Proc + source + else + raise ArgumentError, "Invalid HTTP feature policy source: #{source.inspect}" + end + end + end + + def apply_mapping(source) + MAPPINGS.fetch(source) do + raise ArgumentError, "Unknown HTTP feature policy source mapping: #{source.inspect}" + end + end + + def build_directives(context) + @directives.map do |directive, sources| + if sources.is_a?(Array) + "#{directive} #{build_directive(sources, context).join(' ')}" + elsif sources + directive + else + nil + end + end + end + + def build_directive(sources, context) + sources.map { |source| resolve_source(source, context) } + end + + def resolve_source(source, context) + case source + when String + source + when Symbol + source.to_s + when Proc + if context.nil? + raise RuntimeError, "Missing context for the dynamic feature policy source: #{source.inspect}" + else + context.instance_exec(&source) + end + else + raise RuntimeError, "Unexpected feature policy source: #{source.inspect}" + end + end + end +end diff --git a/actionpack/lib/action_dispatch/http/filter_parameters.rb b/actionpack/lib/action_dispatch/http/filter_parameters.rb index cbb772175c..7a7a493f64 100644 --- a/actionpack/lib/action_dispatch/http/filter_parameters.rb +++ b/actionpack/lib/action_dispatch/http/filter_parameters.rb @@ -56,7 +56,6 @@ module ActionDispatch end private - def parameter_filter # :doc: parameter_filter_for fetch_header("action_dispatch.parameter_filter") { return NULL_PARAM_FILTER diff --git a/actionpack/lib/action_dispatch/http/filter_redirect.rb b/actionpack/lib/action_dispatch/http/filter_redirect.rb index 8c4e852235..d780d5f793 100644 --- a/actionpack/lib/action_dispatch/http/filter_redirect.rb +++ b/actionpack/lib/action_dispatch/http/filter_redirect.rb @@ -14,7 +14,6 @@ module ActionDispatch end private - def location_filters if request request.get_header("action_dispatch.redirect_filter") || [] diff --git a/actionpack/lib/action_dispatch/http/headers.rb b/actionpack/lib/action_dispatch/http/headers.rb index 6c7d24d2d0..6ab913bfd0 100644 --- a/actionpack/lib/action_dispatch/http/headers.rb +++ b/actionpack/lib/action_dispatch/http/headers.rb @@ -116,7 +116,6 @@ module ActionDispatch def env; @req.env.dup; end private - # Converts an HTTP header name to an environment variable name if it is # not contained within the headers hash. def env_name(key) diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb index 4e81ba12a5..a2cac49082 100644 --- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb +++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb @@ -154,7 +154,6 @@ module ActionDispatch end private - BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/ def valid_accept_header # :doc: diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 88b3a93211..ed1d50f3b9 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -290,11 +290,9 @@ module Mime def all?; false; end protected - attr_reader :string, :synonyms private - def to_ary; end def to_a; end diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb index 13d0963a33..3c16817af3 100644 --- a/actionpack/lib/action_dispatch/http/parameters.rb +++ b/actionpack/lib/action_dispatch/http/parameters.rb @@ -85,7 +85,6 @@ module ActionDispatch end private - def set_binary_encoding(params, controller, action) return params unless controller && controller.valid_encoding? diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 44f23940d3..4ac7c5c2bd 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -23,6 +23,7 @@ module ActionDispatch include ActionDispatch::Http::FilterParameters include ActionDispatch::Http::URL include ActionDispatch::ContentSecurityPolicy::Request + include ActionDispatch::FeaturePolicy::Request include Rack::Request::Env autoload :Session, "action_dispatch/request/session" diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index e5cffccf35..ea3692951f 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -86,6 +86,7 @@ module ActionDispatch # :nodoc: cattr_accessor :default_charset, default: "utf-8" cattr_accessor :default_headers + cattr_accessor :return_only_media_type_on_content_type, default: false include Rack::Response::Helpers # Aliasing these off because AD::Http::Cache::Response defines them. @@ -143,7 +144,6 @@ module ActionDispatch # :nodoc: end private - def each_chunk(&block) @buf.each(&block) end @@ -244,7 +244,17 @@ module ActionDispatch # :nodoc: # Content type of response. def content_type - super.presence + if self.class.return_only_media_type_on_content_type + ActiveSupport::Deprecation.warn( + "Rails 6.1 will return Content-Type header without modification." \ + " If you want just the MIME type, please use `#media_type` instead." + ) + + content_type = super + content_type ? content_type.split(/;\s*charset=/)[0].presence : content_type + else + super.presence + end end # Media type of response. @@ -409,7 +419,6 @@ module ActionDispatch # :nodoc: end private - ContentTypeHeader = Struct.new :mime_type, :charset NullContentTypeHeader = ContentTypeHeader.new nil, nil diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 8227749986..3b0f6378ea 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -78,7 +78,6 @@ module ActionDispatch end private - def add_params(path, params) params = { params: params } unless params.is_a?(Hash) params.reject! { |_, v| v.to_param.nil? } diff --git a/actionpack/lib/action_dispatch/journey/formatter.rb b/actionpack/lib/action_dispatch/journey/formatter.rb index 53c404ee7c..a4861719f8 100644 --- a/actionpack/lib/action_dispatch/journey/formatter.rb +++ b/actionpack/lib/action_dispatch/journey/formatter.rb @@ -62,7 +62,6 @@ module ActionDispatch end private - def extract_parameterized_parts(route, options, recall, parameterize = nil) parameterized_parts = recall.merge(options) diff --git a/actionpack/lib/action_dispatch/journey/gtg/builder.rb b/actionpack/lib/action_dispatch/journey/gtg/builder.rb index 44c31053cb..2600e7fb70 100644 --- a/actionpack/lib/action_dispatch/journey/gtg/builder.rb +++ b/actionpack/lib/action_dispatch/journey/gtg/builder.rb @@ -128,7 +128,6 @@ module ActionDispatch end private - def followpos_table @followpos ||= build_followpos end diff --git a/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb b/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb index ea647e051a..5003e92f43 100644 --- a/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb +++ b/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb @@ -141,7 +141,6 @@ module ActionDispatch end private - def states_hash_for(sym) case sym when String diff --git a/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb b/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb index fe55861507..b36003089d 100644 --- a/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb +++ b/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb @@ -94,7 +94,6 @@ module ActionDispatch end private - def inverted return @inverted if @inverted diff --git a/actionpack/lib/action_dispatch/journey/path/pattern.rb b/actionpack/lib/action_dispatch/journey/path/pattern.rb index dee2980eb1..e4ba82ebdd 100644 --- a/actionpack/lib/action_dispatch/journey/path/pattern.rb +++ b/actionpack/lib/action_dispatch/journey/path/pattern.rb @@ -174,7 +174,6 @@ module ActionDispatch end private - def regexp_visitor @anchored ? AnchoredRegexp : UnanchoredRegexp end diff --git a/actionpack/lib/action_dispatch/journey/router.rb b/actionpack/lib/action_dispatch/journey/router.rb index 89a164f968..4a6639af74 100644 --- a/actionpack/lib/action_dispatch/journey/router.rb +++ b/actionpack/lib/action_dispatch/journey/router.rb @@ -81,7 +81,6 @@ module ActionDispatch end private - def partitioned_routes routes.partition { |r| r.path.anchored && r.ast.grep(Nodes::Symbol).all? { |n| n.default_regexp? } diff --git a/actionpack/lib/action_dispatch/journey/routes.rb b/actionpack/lib/action_dispatch/journey/routes.rb index 3ba8361d77..3f055db66d 100644 --- a/actionpack/lib/action_dispatch/journey/routes.rb +++ b/actionpack/lib/action_dispatch/journey/routes.rb @@ -71,7 +71,6 @@ module ActionDispatch end private - def clear_cache! @ast = nil @simulator = nil diff --git a/actionpack/lib/action_dispatch/journey/scanner.rb b/actionpack/lib/action_dispatch/journey/scanner.rb index 2a075862e9..eb6fd17aa7 100644 --- a/actionpack/lib/action_dispatch/journey/scanner.rb +++ b/actionpack/lib/action_dispatch/journey/scanner.rb @@ -33,7 +33,6 @@ module ActionDispatch end private - # takes advantage of String @- deduping capabilities in Ruby 2.5 upwards # see: https://bugs.ruby-lang.org/issues/13077 def dedup_scan(regex) diff --git a/actionpack/lib/action_dispatch/journey/visitors.rb b/actionpack/lib/action_dispatch/journey/visitors.rb index d2619cbf3a..ff26c9a3b0 100644 --- a/actionpack/lib/action_dispatch/journey/visitors.rb +++ b/actionpack/lib/action_dispatch/journey/visitors.rb @@ -59,7 +59,6 @@ module ActionDispatch end private - def visit(node) send(DISPATCH_CACHE[node.type], node) end @@ -168,7 +167,6 @@ module ActionDispatch class String < FunctionalVisitor # :nodoc: private - def binary(node, seed) visit(node.right, visit(node.left, seed)) end @@ -214,7 +212,6 @@ module ActionDispatch end private - def binary(node, seed) seed.last.concat node.children.map { |c| "#{node.object_id} -> #{c.object_id};" diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index dac60a13c6..642f155085 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -252,7 +252,6 @@ module ActionDispatch end private - def upgrade_legacy_hmac_aes_cbc_cookies? request.secret_key_base.present? && request.encrypted_signed_cookie_salt.present? && @@ -428,7 +427,6 @@ module ActionDispatch mattr_accessor :always_write_cookie, default: false private - def escape(string) ::Rack::Utils.escape(string) end diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb index 59113e13f4..e546d1c11f 100644 --- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb @@ -42,7 +42,6 @@ module ActionDispatch end private - def invoke_interceptors(request, exception) backtrace_cleaner = request.get_header("action_dispatch.backtrace_cleaner") wrapper = ExceptionWrapper.new(backtrace_cleaner, exception) @@ -138,9 +137,7 @@ module ActionDispatch return unless logger exception = wrapper.exception - - trace = wrapper.application_trace - trace = wrapper.framework_trace if trace.empty? + trace = wrapper.exception_trace ActiveSupport::Deprecation.silence do message = [] diff --git a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb index 0cc56f5013..e4a2a51c57 100644 --- a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb +++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb @@ -36,18 +36,23 @@ module ActionDispatch "ActionView::Template::Error" ] + cattr_accessor :silent_exceptions, default: [ + "ActionController::RoutingError" + ] + attr_reader :backtrace_cleaner, :exception, :wrapped_causes, :line_number, :file def initialize(backtrace_cleaner, exception) @backtrace_cleaner = backtrace_cleaner @exception = exception + @exception_class_name = @exception.class.name @wrapped_causes = wrapped_causes_for(exception, backtrace_cleaner) expand_backtrace if exception.is_a?(SyntaxError) || exception.cause.is_a?(SyntaxError) end def unwrapped_exception - if wrapper_exceptions.include?(exception.class.to_s) + if wrapper_exceptions.include?(@exception_class_name) exception.cause else exception @@ -55,13 +60,19 @@ module ActionDispatch end def rescue_template - @@rescue_templates[@exception.class.name] + @@rescue_templates[@exception_class_name] end def status_code self.class.status_code_for_exception(unwrapped_exception.class.name) end + def exception_trace + trace = application_trace + trace = framework_trace if trace.empty? && !silent_exceptions.include?(@exception_class_name) + trace + end + def application_trace clean_backtrace(:silent) end @@ -130,7 +141,6 @@ module ActionDispatch end private - def backtrace Array(@exception.backtrace) end diff --git a/actionpack/lib/action_dispatch/middleware/host_authorization.rb b/actionpack/lib/action_dispatch/middleware/host_authorization.rb index b7dff1df41..de7739b9b6 100644 --- a/actionpack/lib/action_dispatch/middleware/host_authorization.rb +++ b/actionpack/lib/action_dispatch/middleware/host_authorization.rb @@ -30,7 +30,6 @@ module ActionDispatch end private - def sanitize_hosts(hosts) Array(hosts).map do |host| case host @@ -87,7 +86,6 @@ module ActionDispatch end private - def authorized?(request) origin_host = request.get_header("HTTP_HOST").to_s.sub(/:\d+\z/, "") forwarded_host = request.x_forwarded_host.to_s.split(/,\s?/).last.to_s.sub(/:\d+\z/, "") diff --git a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb index a88ad40f21..3a2a1d7334 100644 --- a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb @@ -32,7 +32,6 @@ module ActionDispatch end private - def render(status, content_type, body) format = "to_#{content_type.to_sym}" if content_type if format && body.respond_to?(format) diff --git a/actionpack/lib/action_dispatch/middleware/remote_ip.rb b/actionpack/lib/action_dispatch/middleware/remote_ip.rb index a5667573f4..c5d4a0bd31 100644 --- a/actionpack/lib/action_dispatch/middleware/remote_ip.rb +++ b/actionpack/lib/action_dispatch/middleware/remote_ip.rb @@ -156,7 +156,6 @@ module ActionDispatch end private - def ips_from(header) # :doc: return [] unless header # Split the comma-separated list into an array of strings. diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb index 5b0be96223..3815971acb 100644 --- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb @@ -30,7 +30,6 @@ module ActionDispatch end private - def initialize_sid # :doc: @default_options.delete(:sidbits) @default_options.delete(:secure_random) @@ -83,7 +82,6 @@ module ActionDispatch include SessionObject private - def set_cookie(request, session_id, cookie) request.cookie_jar[key] = cookie end diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb index 7c43c781c7..892d88803e 100644 --- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb @@ -67,7 +67,6 @@ module ActionDispatch end private - def extract_session_id(req) stale_session_check! do unpacked_cookie_data(req)["session_id"] diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 767143a368..a35c0da3d9 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -40,7 +40,6 @@ module ActionDispatch end private - def render_exception(request, exception) backtrace_cleaner = request.get_header "action_dispatch.backtrace_cleaner" wrapper = ExceptionWrapper.new(backtrace_cleaner, exception) diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index 57e4adb457..775110d95e 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -134,7 +134,6 @@ module ActionDispatch end private - def assert_index(index, where) i = index.is_a?(Integer) ? index : middlewares.index { |m| m.klass == index } raise "No such middleware to insert #{where}: #{index.inspect}" unless i diff --git a/actionpack/lib/action_dispatch/railtie.rb b/actionpack/lib/action_dispatch/railtie.rb index 5f711c7348..2e09aed41d 100644 --- a/actionpack/lib/action_dispatch/railtie.rb +++ b/actionpack/lib/action_dispatch/railtie.rb @@ -23,6 +23,7 @@ module ActionDispatch config.action_dispatch.use_authenticated_cookie_encryption = false config.action_dispatch.use_cookies_with_metadata = false config.action_dispatch.perform_deep_munge = true + config.action_dispatch.return_only_media_type_on_content_type = true config.action_dispatch.default_headers = { "X-Frame-Options" => "SAMEORIGIN", @@ -43,6 +44,7 @@ module ActionDispatch ActionDispatch::Request::Utils.perform_deep_munge = app.config.action_dispatch.perform_deep_munge ActionDispatch::Response.default_charset = app.config.action_dispatch.default_charset || app.config.encoding ActionDispatch::Response.default_headers = app.config.action_dispatch.default_headers + ActionDispatch::Response.return_only_media_type_on_content_type = app.config.action_dispatch.return_only_media_type_on_content_type ActionDispatch::ExceptionWrapper.rescue_responses.merge!(config.action_dispatch.rescue_responses) ActionDispatch::ExceptionWrapper.rescue_templates.merge!(config.action_dispatch.rescue_templates) @@ -52,11 +54,5 @@ module ActionDispatch ActionDispatch.test_app = app end - - initializer "action_dispatch.system_tests" do |app| - ActiveSupport.on_load(:action_dispatch_system_test_case) do - include app.routes.url_helpers - end - end end end diff --git a/actionpack/lib/action_dispatch/request/session.rb b/actionpack/lib/action_dispatch/request/session.rb index bc5e0670e0..8faedf15b9 100644 --- a/actionpack/lib/action_dispatch/request/session.rb +++ b/actionpack/lib/action_dispatch/request/session.rb @@ -216,7 +216,6 @@ module ActionDispatch end private - def load_for_read! load! if !loaded? && exists? end diff --git a/actionpack/lib/action_dispatch/routing/inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb index 413e524ef6..6e40a18009 100644 --- a/actionpack/lib/action_dispatch/routing/inspector.rb +++ b/actionpack/lib/action_dispatch/routing/inspector.rb @@ -177,7 +177,6 @@ module ActionDispatch end private - def draw_section(routes) header_lengths = ["Prefix", "Verb", "URI Pattern"].map(&:length) name_width, verb_width, path_width = widths(routes).zip(header_lengths).map(&:max) @@ -210,7 +209,6 @@ module ActionDispatch end private - def draw_expanded_section(routes) routes.map.each_with_index do |r, i| <<~MESSAGE.chomp diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 0aba484a45..d1100089b1 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -1673,7 +1673,6 @@ module ActionDispatch end private - def parent_resource @scope[:scope_level_resource] end diff --git a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb index 4de5f9e2f7..e3322e99ab 100644 --- a/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb +++ b/actionpack/lib/action_dispatch/routing/polymorphic_routes.rb @@ -156,7 +156,6 @@ module ActionDispatch end private - def polymorphic_url_for_action(action, record_or_hash, options) polymorphic_url(record_or_hash, options.merge(action: action)) end @@ -323,7 +322,6 @@ module ActionDispatch end private - def polymorphic_mapping(target, record) if record.respond_to?(:to_model) target._routes.polymorphic_mappings[record.to_model.model_name.name] diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index bbb5762b3c..5b35b68c44 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -40,7 +40,6 @@ module ActionDispatch end private - def controller(req) req.controller_class rescue NameError => e @@ -59,7 +58,6 @@ module ActionDispatch end private - def controller(_); @controller_class; end end @@ -215,7 +213,6 @@ module ActionDispatch end private - def optimized_helper(args) params = parameterize_args(args) do raise_generation_error(args) diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index fcb8ae296b..e02a6541c1 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -215,13 +215,11 @@ module ActionDispatch end protected - def optimize_routes_generation? _routes.optimize_routes_generation? && default_url_options.empty? end private - def _with_routes(routes) # :doc: old_routes, @_routes = @_routes, routes yield diff --git a/actionpack/lib/action_dispatch/system_test_case.rb b/actionpack/lib/action_dispatch/system_test_case.rb index a7fb5fa330..aae96975c7 100644 --- a/actionpack/lib/action_dispatch/system_test_case.rb +++ b/actionpack/lib/action_dispatch/system_test_case.rb @@ -1,9 +1,10 @@ # frozen_string_literal: true -gem "capybara", ">= 2.15" +gem "capybara", ">= 3.26" require "capybara/dsl" require "capybara/minitest" +require "selenium/webdriver" require "action_controller" require "action_dispatch/system_testing/driver" require "action_dispatch/system_testing/browser" @@ -158,12 +159,33 @@ module ActionDispatch driven_by :selenium - def url_options # :nodoc: - default_url_options.merge(host: Capybara.app_host) - end + private + def url_helpers + @url_helpers ||= + if ActionDispatch.test_app + Class.new do + include ActionDispatch.test_app.routes.url_helpers - ActiveSupport.run_load_hooks(:action_dispatch_system_test_case, self) - end + def url_options + default_url_options.reverse_merge(host: Capybara.app_host || Capybara.current_session.server_url) + end + end.new + end + end - SystemTestCase.start_application + def method_missing(name, *args, &block) + if url_helpers.respond_to?(name) + url_helpers.public_send(name, *args, &block) + else + super + end + end + + def respond_to_missing?(name, include_private = false) + url_helpers.respond_to?(name) + end + end end + +ActiveSupport.run_load_hooks :action_dispatch_system_test_case, ActionDispatch::SystemTestCase +ActionDispatch::SystemTestCase.start_application diff --git a/actionpack/lib/action_dispatch/system_testing/browser.rb b/actionpack/lib/action_dispatch/system_testing/browser.rb index c34907b6cb..e861e52f09 100644 --- a/actionpack/lib/action_dispatch/system_testing/browser.rb +++ b/actionpack/lib/action_dispatch/system_testing/browser.rb @@ -39,6 +39,29 @@ module ActionDispatch end end + # driver_path can be configured as a proc. The webdrivers gem uses this + # proc to update web drivers. Running this proc early allows us to only + # update the webdriver once and avoid race conditions when using + # parallel tests. + def preload + case type + when :chrome + if ::Selenium::WebDriver::Service.respond_to? :driver_path= + ::Selenium::WebDriver::Chrome::Service.driver_path.try(:call) + else + # Selenium <= v3.141.0 + ::Selenium::WebDriver::Chrome.driver_path + end + when :firefox + if ::Selenium::WebDriver::Service.respond_to? :driver_path= + ::Selenium::WebDriver::Firefox::Service.driver_path.try(:call) + else + # Selenium <= v3.141.0 + ::Selenium::WebDriver::Firefox.driver_path + end + end + end + private def headless_chrome_browser_options capabilities.args << "--headless" diff --git a/actionpack/lib/action_dispatch/system_testing/driver.rb b/actionpack/lib/action_dispatch/system_testing/driver.rb index 25a09dd918..15943a55ea 100644 --- a/actionpack/lib/action_dispatch/system_testing/driver.rb +++ b/actionpack/lib/action_dispatch/system_testing/driver.rb @@ -9,6 +9,8 @@ module ActionDispatch @screen_size = options[:screen_size] @options = options[:options] @capabilities = capabilities + + @browser.preload end def use diff --git a/actionpack/lib/action_dispatch/system_testing/test_helpers/setup_and_teardown.rb b/actionpack/lib/action_dispatch/system_testing/test_helpers/setup_and_teardown.rb index 20f6a7634f..30dc21ebb9 100644 --- a/actionpack/lib/action_dispatch/system_testing/test_helpers/setup_and_teardown.rb +++ b/actionpack/lib/action_dispatch/system_testing/test_helpers/setup_and_teardown.rb @@ -4,15 +4,12 @@ module ActionDispatch module SystemTesting module TestHelpers module SetupAndTeardown # :nodoc: - DEFAULT_HOST = "http://127.0.0.1" - def host!(host) - Capybara.app_host = host - end + ActiveSupport::Deprecation.warn \ + "ActionDispatch::SystemTestCase#host! is deprecated with no replacement. " \ + "Set Capybara.app_host directly or rely on Capybara's default host." - def before_setup - host! DEFAULT_HOST - super + Capybara.app_host = host end def before_teardown diff --git a/actionpack/lib/action_dispatch/testing/assertion_response.rb b/actionpack/lib/action_dispatch/testing/assertion_response.rb index dc019db6ac..79af372cc1 100644 --- a/actionpack/lib/action_dispatch/testing/assertion_response.rb +++ b/actionpack/lib/action_dispatch/testing/assertion_response.rb @@ -35,7 +35,6 @@ module ActionDispatch end private - def code_from_name(name) GENERIC_RESPONSE_CODES[name] || Rack::Utils::SYMBOL_TO_STATUS_CODE[name] end diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index bb8b43ad4d..9e7b4301a8 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -3,7 +3,6 @@ require "stringio" require "uri" require "active_support/core_ext/kernel/singleton_class" -require "active_support/core_ext/object/try" require "rack/test" require "minitest" @@ -50,11 +49,16 @@ module ActionDispatch # Follow a single redirect response. If the last response was not a # redirect, an exception will be raised. Otherwise, the redirect is - # performed on the location header. Any arguments are passed to the - # underlying call to `get`. + # performed on the location header. If the redirection is a 307 redirect, + # the same HTTP verb will be used when redirecting, otherwise a GET request + # will be performed. Any arguments are passed to the + # underlying request. def follow_redirect!(**args) raise "not a redirect! #{status} #{status_message}" unless redirect? - get(response.location, **args) + + method = response.status == 307 ? request.method.downcase : :get + public_send(method, response.location, **args) + status end end diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 32a0b8efeb..1decfcee95 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -335,7 +335,6 @@ module RoutingTestHelpers end private - def make_request(env) Request.new super, url_helpers, @block, strict end diff --git a/actionpack/test/controller/api/conditional_get_test.rb b/actionpack/test/controller/api/conditional_get_test.rb index e366ce9532..f1cd9e46f9 100644 --- a/actionpack/test/controller/api/conditional_get_test.rb +++ b/actionpack/test/controller/api/conditional_get_test.rb @@ -18,7 +18,6 @@ class ConditionalGetApiController < ActionController::API end private - def handle_last_modified_and_etags fresh_when(last_modified: Time.now.utc.beginning_of_day, etag: [ :foo, 123 ]) end diff --git a/actionpack/test/controller/content_type_test.rb b/actionpack/test/controller/content_type_test.rb index aeb0d07195..fcf767b706 100644 --- a/actionpack/test/controller/content_type_test.rb +++ b/actionpack/test/controller/content_type_test.rb @@ -132,7 +132,6 @@ class ContentTypeTest < ActionController::TestCase end private - def with_default_charset(charset) old_default_charset = ActionDispatch::Response.default_charset ActionDispatch::Response.default_charset = charset diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb index fcee812ee4..40443a9397 100644 --- a/actionpack/test/controller/filters_test.rb +++ b/actionpack/test/controller/filters_test.rb @@ -310,7 +310,6 @@ class FilterTest < ActionController::TestCase after_action :conditional_in_parent_after, only: [:show, :another_action] private - def conditional_in_parent_before @ran_filter ||= [] @ran_filter << "conditional_in_parent_before" @@ -508,7 +507,6 @@ class FilterTest < ActionController::TestCase end private - def filter_one @filters ||= [] @filters << "filter_one" @@ -532,7 +530,6 @@ class FilterTest < ActionController::TestCase before_action :find_except, except: :edit private - def find_only @only = "Only" end diff --git a/actionpack/test/controller/flash_test.rb b/actionpack/test/controller/flash_test.rb index bf95c633e5..1f44c7a68e 100644 --- a/actionpack/test/controller/flash_test.rb +++ b/actionpack/test/controller/flash_test.rb @@ -361,7 +361,6 @@ class FlashIntegrationTest < ActionDispatch::IntegrationTest end private - # Overwrite get to send SessionSecret in env hash def get(path, *args) args[0] ||= {} diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb index de8072a994..93a2ba1071 100644 --- a/actionpack/test/controller/helper_test.rb +++ b/actionpack/test/controller/helper_test.rb @@ -150,8 +150,8 @@ class HelperTest < ActiveSupport::TestCase end def test_default_helpers_only - assert_equal [JustMeHelper], JustMeController._helpers.ancestors.reject(&:anonymous?) - assert_equal [MeTooHelper, JustMeHelper], MeTooController._helpers.ancestors.reject(&:anonymous?) + assert_equal %w[JustMeHelper], JustMeController._helpers.ancestors.reject(&:anonymous?).map(&:to_s) + assert_equal %w[MeTooController::HelperMethods MeTooHelper JustMeHelper], MeTooController._helpers.ancestors.reject(&:anonymous?).map(&:to_s) end def test_base_helper_methods_after_clear_helpers diff --git a/actionpack/test/controller/http_basic_authentication_test.rb b/actionpack/test/controller/http_basic_authentication_test.rb index 1544a627ee..73524d0443 100644 --- a/actionpack/test/controller/http_basic_authentication_test.rb +++ b/actionpack/test/controller/http_basic_authentication_test.rb @@ -32,7 +32,6 @@ class HttpBasicAuthenticationTest < ActionController::TestCase end private - def authenticate authenticate_or_request_with_http_basic do |username, password| username == "lifo" && password == "world" @@ -172,7 +171,6 @@ class HttpBasicAuthenticationTest < ActionController::TestCase end private - def encode_credentials(username, password) "Basic #{::Base64.encode64("#{username}:#{password}")}" end diff --git a/actionpack/test/controller/http_digest_authentication_test.rb b/actionpack/test/controller/http_digest_authentication_test.rb index dd4ff85d11..a0f543f607 100644 --- a/actionpack/test/controller/http_digest_authentication_test.rb +++ b/actionpack/test/controller/http_digest_authentication_test.rb @@ -20,7 +20,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase end private - def authenticate authenticate_or_request_with_http_digest("SuperSecret") do |username| # Returns the password @@ -254,7 +253,6 @@ class HttpDigestAuthenticationTest < ActionController::TestCase end private - def encode_credentials(options) options.reverse_merge!(nc: "00000001", cnonce: "0a4f113b", password_is_ha1: false) password = options.delete(:password) diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb index 103123f98c..57b78154bc 100644 --- a/actionpack/test/controller/http_token_authentication_test.rb +++ b/actionpack/test/controller/http_token_authentication_test.rb @@ -21,7 +21,6 @@ class HttpTokenAuthenticationTest < ActionController::TestCase end private - def authenticate authenticate_or_request_with_http_token do |token, _| token == "lifo" @@ -190,7 +189,6 @@ class HttpTokenAuthenticationTest < ActionController::TestCase end private - def sample_request(token, options = { nonce: "def" }) authorization = options.inject([%{Token token="#{token}"}]) do |arr, (k, v)| arr << "#{k}=\"#{v}\"" diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index cce229b30d..caacd66bd6 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -213,6 +213,10 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest redirect_to action_url("get") end + def redirect_307 + redirect_to action_url("post"), status: 307 + end + def remove_header response.headers.delete params[:header] head :ok, "c" => "3" @@ -337,6 +341,15 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest end end + def test_307_redirect_uses_the_same_http_verb + with_test_route_set do + post "/redirect_307" + assert_equal 307, status + follow_redirect! + assert_equal "POST", request.method + end + end + def test_redirect_reset_html_document with_test_route_set do get "/redirect" diff --git a/actionpack/test/controller/mime/accept_format_test.rb b/actionpack/test/controller/mime/accept_format_test.rb index eed671d593..fb038ae158 100644 --- a/actionpack/test/controller/mime/accept_format_test.rb +++ b/actionpack/test/controller/mime/accept_format_test.rb @@ -43,7 +43,6 @@ class PostController < AbstractPostController end private - def with_iphone request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone" yield diff --git a/actionpack/test/controller/new_base/render_template_test.rb b/actionpack/test/controller/new_base/render_template_test.rb index 14dc958475..270f75eb9e 100644 --- a/actionpack/test/controller/new_base/render_template_test.rb +++ b/actionpack/test/controller/new_base/render_template_test.rb @@ -67,7 +67,6 @@ module RenderTemplate end private - def show_detailed_exceptions? request.local? end diff --git a/actionpack/test/controller/new_base/render_test.rb b/actionpack/test/controller/new_base/render_test.rb index eb29203f59..dfeb2e2b15 100644 --- a/actionpack/test/controller/new_base/render_test.rb +++ b/actionpack/test/controller/new_base/render_test.rb @@ -37,7 +37,6 @@ module Render end private - def secretz render plain: "FAIL WHALE!" end diff --git a/actionpack/test/controller/parameters/accessors_test.rb b/actionpack/test/controller/parameters/accessors_test.rb index cb49eeb1b7..3d1538ff64 100644 --- a/actionpack/test/controller/parameters/accessors_test.rb +++ b/actionpack/test/controller/parameters/accessors_test.rb @@ -284,12 +284,14 @@ class ParametersAccessorsTest < ActiveSupport::TestCase params1 = ActionController::Parameters.new(a: 1, b: 2) params2 = ActionController::Parameters.new(a: 1, b: 2) assert(params1 == params2) + assert(params1.hash == params2.hash) end test "is equal to Parameters instance with same permitted params" do params1 = ActionController::Parameters.new(a: 1, b: 2).permit(:a) params2 = ActionController::Parameters.new(a: 1, b: 2).permit(:a) assert(params1 == params2) + assert(params1.hash == params2.hash) end test "is equal to Parameters instance with same different source params, but same permitted params" do @@ -297,6 +299,8 @@ class ParametersAccessorsTest < ActiveSupport::TestCase params2 = ActionController::Parameters.new(a: 1, c: 3).permit(:a) assert(params1 == params2) assert(params2 == params1) + assert(params1.hash == params2.hash) + assert(params2.hash == params1.hash) end test "is not equal to an unpermitted Parameters instance with same params" do @@ -304,6 +308,8 @@ class ParametersAccessorsTest < ActiveSupport::TestCase params2 = ActionController::Parameters.new(a: 1) assert(params1 != params2) assert(params2 != params1) + assert(params1.hash != params2.hash) + assert(params2.hash != params1.hash) end test "is not equal to Parameters instance with different permitted params" do @@ -311,6 +317,8 @@ class ParametersAccessorsTest < ActiveSupport::TestCase params2 = ActionController::Parameters.new(a: 1, b: 2).permit(:a) assert(params1 != params2) assert(params2 != params1) + assert(params1.hash != params2.hash) + assert(params2.hash != params1.hash) end test "equality with simple types works" do diff --git a/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb b/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb index fc9229ca1d..4fffcf6b10 100644 --- a/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb +++ b/actionpack/test/controller/parameters/log_on_unpermitted_params_test.rb @@ -52,7 +52,6 @@ class LogOnUnpermittedParamsTest < ActiveSupport::TestCase end private - def assert_logged(message) old_logger = ActionController::Base.logger log = StringIO.new diff --git a/actionpack/test/controller/params_parse_test.rb b/actionpack/test/controller/params_parse_test.rb index 440ab06fd7..091b567473 100644 --- a/actionpack/test/controller/params_parse_test.rb +++ b/actionpack/test/controller/params_parse_test.rb @@ -24,7 +24,6 @@ class ParamsParseTest < ActionController::TestCase end private - def capture_log_output output = StringIO.new request.set_header "action_dispatch.logger", ActiveSupport::Logger.new(output) diff --git a/actionpack/test/controller/params_wrapper_test.rb b/actionpack/test/controller/params_wrapper_test.rb index c4c74e8f2b..894a3824c0 100644 --- a/actionpack/test/controller/params_wrapper_test.rb +++ b/actionpack/test/controller/params_wrapper_test.rb @@ -411,7 +411,6 @@ class IrregularInflectionParamsWrapperTest < ActionController::TestCase end private - def with_dup original = ActiveSupport::Inflector::Inflections.instance_variable_get(:@__instance__)[:en] ActiveSupport::Inflector::Inflections.instance_variable_set(:@__instance__, en: original.dup) diff --git a/actionpack/test/controller/render_test.rb b/actionpack/test/controller/render_test.rb index 8bb6617eaa..a2a6c69dd3 100644 --- a/actionpack/test/controller/render_test.rb +++ b/actionpack/test/controller/render_test.rb @@ -265,7 +265,6 @@ class TestController < ActionController::Base end private - def set_variable_for_layout @variable_for_layout = nil end diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index ea94a3e048..01250880f5 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -112,7 +112,6 @@ class PrependProtectForgeryBaseController < ActionController::Base end private - def add_called_callback(name) @called_callbacks ||= [] @called_callbacks << name diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb index 089b0b94d4..538bc15fc9 100644 --- a/actionpack/test/controller/rescue_test.rb +++ b/actionpack/test/controller/rescue_test.rb @@ -304,7 +304,6 @@ class RescueControllerTest < ActionController::TestCase end private - def capture_log_output output = StringIO.new request.set_header "action_dispatch.logger", ActiveSupport::Logger.new(output) @@ -351,7 +350,6 @@ class RescueTest < ActionDispatch::IntegrationTest end private - def with_test_routing with_routing do |set| set.draw do diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index d2146f12a5..339025ec52 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true require "abstract_unit" -require "active_support/core_ext/object/try" require "active_support/core_ext/object/with_options" require "active_support/core_ext/array/extract_options" @@ -36,7 +35,6 @@ class ResourcesTest < ActionController::TestCase collection: collection_methods, member: member_methods, path_names: path_names do - assert_restful_routes_for :messages, collection: collection_methods, member: member_methods, @@ -58,7 +56,6 @@ class ResourcesTest < ActionController::TestCase collection: collection_methods, member: member_methods, path_names: path_names do |options| - collection_methods.each_key do |action| assert_named_route "/messages/#{path_names[action] || action}", "#{action}_messages_path", action: action end @@ -1251,7 +1248,7 @@ class ResourcesTest < ActionController::TestCase shallow_path = "/#{options[:shallow] ? options[:namespace] : options[:path_prefix]}#{path}" full_path = "/#{options[:path_prefix]}#{path}" name_prefix = options[:name_prefix] - shallow_prefix = options[:shallow] ? options[:namespace].try(:gsub, /\//, "_") : options[:name_prefix] + shallow_prefix = options[:shallow] ? options[:namespace]&.gsub(/\//, "_") : options[:name_prefix] new_action = "new" edit_action = "edit" diff --git a/actionpack/test/controller/show_exceptions_test.rb b/actionpack/test/controller/show_exceptions_test.rb index 2cd2114db6..8e1068fecf 100644 --- a/actionpack/test/controller/show_exceptions_test.rb +++ b/actionpack/test/controller/show_exceptions_test.rb @@ -51,7 +51,6 @@ module ShowExceptions class ShowExceptionsOverriddenController < ShowExceptionsController private - def show_detailed_exceptions? params["detailed"] == "1" end diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb index 998a495d0d..635a91507d 100644 --- a/actionpack/test/controller/test_case_test.rb +++ b/actionpack/test/controller/test_case_test.rb @@ -165,7 +165,6 @@ XML end private - def generate_url(opts) url_for(opts.merge(action: "test_uri")) end diff --git a/actionpack/test/dispatch/callbacks_test.rb b/actionpack/test/dispatch/callbacks_test.rb index fc80191c02..aa8640c506 100644 --- a/actionpack/test/dispatch/callbacks_test.rb +++ b/actionpack/test/dispatch/callbacks_test.rb @@ -38,7 +38,6 @@ class DispatcherTest < ActiveSupport::TestCase end private - def dispatch(&block) ActionDispatch::Callbacks.new(block || DummyApp.new).call( "rack.input" => StringIO.new("") diff --git a/actionpack/test/dispatch/content_security_policy_test.rb b/actionpack/test/dispatch/content_security_policy_test.rb index c8c885f35c..3d60dc1661 100644 --- a/actionpack/test/dispatch/content_security_policy_test.rb +++ b/actionpack/test/dispatch/content_security_policy_test.rb @@ -128,12 +128,36 @@ class ContentSecurityPolicyTest < ActiveSupport::TestCase @policy.script_src false assert_no_match %r{script-src}, @policy.build + @policy.script_src_attr :self + assert_match %r{script-src-attr 'self'}, @policy.build + + @policy.script_src_attr false + assert_no_match %r{script-src-attr}, @policy.build + + @policy.script_src_elem :self + assert_match %r{script-src-elem 'self'}, @policy.build + + @policy.script_src_elem false + assert_no_match %r{script-src-elem}, @policy.build + @policy.style_src :self assert_match %r{style-src 'self'}, @policy.build @policy.style_src false assert_no_match %r{style-src}, @policy.build + @policy.style_src_attr :self + assert_match %r{style-src-attr 'self'}, @policy.build + + @policy.style_src_attr false + assert_no_match %r{style-src-attr}, @policy.build + + @policy.style_src_elem :self + assert_match %r{style-src-elem 'self'}, @policy.build + + @policy.style_src_elem false + assert_no_match %r{style-src-elem}, @policy.build + @policy.worker_src :self assert_match %r{worker-src 'self'}, @policy.build @@ -307,7 +331,6 @@ class DefaultContentSecurityPolicyIntegrationTest < ActionDispatch::IntegrationT end private - def assert_policy(expected, report_only: false) if report_only expected_header = "Content-Security-Policy-Report-Only" @@ -470,7 +493,6 @@ class ContentSecurityPolicyIntegrationTest < ActionDispatch::IntegrationTest end private - def assert_policy(expected, report_only: false) assert_response :success @@ -544,3 +566,57 @@ class DisabledContentSecurityPolicyIntegrationTest < ActionDispatch::Integration assert_equal "default-src https://example.com", response.headers["Content-Security-Policy"] end end + +class NonceDirectiveContentSecurityPolicyIntegrationTest < ActionDispatch::IntegrationTest + class PolicyController < ActionController::Base + def index + head :ok + end + end + + ROUTES = ActionDispatch::Routing::RouteSet.new + ROUTES.draw do + scope module: "nonce_directive_content_security_policy_integration_test" do + get "/", to: "policy#index" + end + end + + POLICY = ActionDispatch::ContentSecurityPolicy.new do |p| + p.default_src -> { :self } + p.script_src -> { :https } + p.style_src -> { :https } + end + + class PolicyConfigMiddleware + def initialize(app) + @app = app + end + + def call(env) + env["action_dispatch.content_security_policy"] = POLICY + env["action_dispatch.content_security_policy_nonce_generator"] = proc { "iyhD0Yc0W+c=" } + env["action_dispatch.content_security_policy_report_only"] = false + env["action_dispatch.content_security_policy_nonce_directives"] = %w(script-src) + env["action_dispatch.show_exceptions"] = false + + @app.call(env) + end + end + + APP = build_app(ROUTES) do |middleware| + middleware.use PolicyConfigMiddleware + middleware.use ActionDispatch::ContentSecurityPolicy::Middleware + end + + def app + APP + end + + def test_generate_nonce_only_specified_in_nonce_directives + get "/" + + assert_response :success + assert_match "script-src https: 'nonce-iyhD0Yc0W+c='", response.headers["Content-Security-Policy"] + assert_no_match "style-src https: 'nonce-iyhD0Yc0W+c='", response.headers["Content-Security-Policy"] + end +end diff --git a/actionpack/test/dispatch/debug_exceptions_test.rb b/actionpack/test/dispatch/debug_exceptions_test.rb index 68817ccdea..fa629bc761 100644 --- a/actionpack/test/dispatch/debug_exceptions_test.rb +++ b/actionpack/test/dispatch/debug_exceptions_test.rb @@ -466,6 +466,8 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest end test "logs exception backtrace when all lines silenced" do + @app = DevelopmentApp + output = StringIO.new backtrace_cleaner = ActiveSupport::BacktraceCleaner.new backtrace_cleaner.add_silencer { true } @@ -478,6 +480,27 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest assert_operator((output.rewind && output.read).lines.count, :>, 10) end + test "doesn't log the framework backtrace when error type is a routing error" do + @app = ProductionApp + + output = StringIO.new + backtrace_cleaner = ActiveSupport::BacktraceCleaner.new + backtrace_cleaner.add_silencer { true } + + env = { "action_dispatch.show_exceptions" => true, + "action_dispatch.logger" => Logger.new(output), + "action_dispatch.backtrace_cleaner" => backtrace_cleaner } + + assert_raises ActionController::RoutingError do + get "/pass", headers: env + end + + log = output.rewind && output.read + + assert_includes log, "ActionController::RoutingError (No route matches [GET] \"/pass\")" + assert_equal 3, log.lines.count + end + test "display backtrace when error type is SyntaxError" do @app = DevelopmentApp diff --git a/actionpack/test/dispatch/feature_policy_test.rb b/actionpack/test/dispatch/feature_policy_test.rb new file mode 100644 index 0000000000..ebcc8a8b6d --- /dev/null +++ b/actionpack/test/dispatch/feature_policy_test.rb @@ -0,0 +1,142 @@ +# frozen_string_literal: true + +require "abstract_unit" + +class FeaturePolicyTest < ActiveSupport::TestCase + def setup + @policy = ActionDispatch::FeaturePolicy.new + end + + def test_mappings + @policy.midi :self + assert_equal "midi 'self'", @policy.build + + @policy.midi :none + assert_equal "midi 'none'", @policy.build + end + + def test_multiple_sources_for_a_single_directive + @policy.geolocation :self, "https://example.com" + assert_equal "geolocation 'self' https://example.com", @policy.build + end + + def test_single_directive_for_multiple_directives + @policy.geolocation :self + @policy.usb :none + assert_equal "geolocation 'self'; usb 'none'", @policy.build + end + + def test_multiple_directives_for_multiple_directives + @policy.geolocation :self, "https://example.com" + @policy.usb :none, "https://example.com" + assert_equal "geolocation 'self' https://example.com; usb 'none' https://example.com", @policy.build + end + + def test_invalid_directive_source + exception = assert_raises(ArgumentError) do + @policy.vr [:non_existent] + end + + assert_equal "Invalid HTTP feature policy source: [:non_existent]", exception.message + end +end + +class FeaturePolicyIntegrationTest < ActionDispatch::IntegrationTest + class PolicyController < ActionController::Base + feature_policy only: :index do |f| + f.gyroscope :none + end + + feature_policy only: :sample_controller do |f| + f.gyroscope nil + f.usb :self + end + + feature_policy only: :multiple_directives do |f| + f.gyroscope nil + f.usb :self + f.autoplay "https://example.com" + f.payment "https://secure.example.com" + end + + def index + head :ok + end + + def sample_controller + head :ok + end + + def multiple_directives + head :ok + end + end + + ROUTES = ActionDispatch::Routing::RouteSet.new + ROUTES.draw do + scope module: "feature_policy_integration_test" do + get "/", to: "policy#index" + get "/sample_controller", to: "policy#sample_controller" + get "/multiple_directives", to: "policy#multiple_directives" + end + end + + POLICY = ActionDispatch::FeaturePolicy.new do |p| + p.gyroscope :self + end + + class PolicyConfigMiddleware + def initialize(app) + @app = app + end + + def call(env) + env["action_dispatch.feature_policy"] = POLICY + env["action_dispatch.show_exceptions"] = false + + @app.call(env) + end + end + + APP = build_app(ROUTES) do |middleware| + middleware.use PolicyConfigMiddleware + middleware.use ActionDispatch::FeaturePolicy::Middleware + end + + def app + APP + end + + def test_generates_feature_policy_header + get "/" + assert_policy "gyroscope 'none'" + end + + def test_generates_per_controller_feature_policy_header + get "/sample_controller" + assert_policy "usb 'self'" + end + + def test_generates_multiple_directives_feature_policy_header + get "/multiple_directives" + assert_policy "usb 'self'; autoplay https://example.com; payment https://secure.example.com" + end + + private + def env_config + Rails.application.env_config + end + + def feature_policy + env_config["action_dispatch.feature_policy"] + end + + def feature_policy=(policy) + env_config["action_dispatch.feature_policy"] = policy + end + + def assert_policy(expected) + assert_response :success + assert_equal expected, response.headers["Feature-Policy"] + end +end diff --git a/actionpack/test/dispatch/request_id_test.rb b/actionpack/test/dispatch/request_id_test.rb index 9df4712dab..036180c297 100644 --- a/actionpack/test/dispatch/request_id_test.rb +++ b/actionpack/test/dispatch/request_id_test.rb @@ -29,7 +29,6 @@ class RequestIdTest < ActiveSupport::TestCase end private - def stub_request(env = {}) ActionDispatch::RequestId.new(lambda { |environment| [ 200, environment, [] ] }).call(env) ActionDispatch::Request.new(env) @@ -58,7 +57,6 @@ class RequestIdResponseTest < ActionDispatch::IntegrationTest end private - def with_test_route_set with_routing do |set| set.draw do diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb index eb49396145..0ec8dd25e0 100644 --- a/actionpack/test/dispatch/request_test.rb +++ b/actionpack/test/dispatch/request_test.rb @@ -681,7 +681,6 @@ end class RequestMethod < BaseRequestTest test "method returns environment's request method when it has not been overridden by middleware".squish do - ActionDispatch::Request::HTTP_METHODS.each do |method| request = stub_request("REQUEST_METHOD" => method) diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb index 33cf86a081..ed64d89902 100644 --- a/actionpack/test/dispatch/response_test.rb +++ b/actionpack/test/dispatch/response_test.rb @@ -593,4 +593,33 @@ class ResponseIntegrationTest < ActionDispatch::IntegrationTest assert_equal("text/csv", @response.media_type) assert_equal("utf-16", @response.charset) end + + test "`content type` returns header that excludes `charset` when specified `return_only_media_type_on_content_type`" do + original = ActionDispatch::Response.return_only_media_type_on_content_type + ActionDispatch::Response.return_only_media_type_on_content_type = true + + @app = lambda { |env| + if env["PATH_INFO"] == "/with_parameters" + [200, { "Content-Type" => "text/csv; header=present; charset=utf-16" }, [""]] + else + [200, { "Content-Type" => "text/csv; charset=utf-16" }, [""]] + end + } + + get "/" + assert_response :success + + assert_deprecated do + assert_equal("text/csv", @response.content_type) + end + + get "/with_parameters" + assert_response :success + + assert_deprecated do + assert_equal("text/csv; header=present", @response.content_type) + end + ensure + ActionDispatch::Response.return_only_media_type_on_content_type = original + end end diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index 0070d7af72..b67b1dd347 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -3810,7 +3810,6 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest end private - def draw(&block) self.class.stub_controllers do |routes| routes.default_url_options = { host: "www.example.com" } @@ -4953,7 +4952,6 @@ class TestPartialDynamicPathSegments < ActionDispatch::IntegrationTest end private - def assert_params(params) assert_equal(params, request.path_parameters) end @@ -5184,7 +5182,6 @@ class TestRecognizePath < ActionDispatch::IntegrationTest end private - def recognize_path(*args) Routes.recognize_path(*args) end diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb index e34426a471..b6f83f4062 100644 --- a/actionpack/test/dispatch/session/cookie_store_test.rb +++ b/actionpack/test/dispatch/session/cookie_store_test.rb @@ -379,7 +379,6 @@ class CookieStoreTest < ActionDispatch::IntegrationTest end private - # Overwrite get to send SessionSecret in env hash def get(path, *args) args[0] ||= {} diff --git a/actionpack/test/dispatch/static_test.rb b/actionpack/test/dispatch/static_test.rb index d44aa00122..1f93d594a6 100644 --- a/actionpack/test/dispatch/static_test.rb +++ b/actionpack/test/dispatch/static_test.rb @@ -232,7 +232,6 @@ module StaticTests end private - def assert_gzip(file_name, response) expected = File.read("#{FIXTURE_LOAD_PATH}/#{public_path}" + file_name) actual = ActiveSupport::Gzip.decompress(response.body) diff --git a/actionpack/test/dispatch/system_testing/driver_test.rb b/actionpack/test/dispatch/system_testing/driver_test.rb index 0d08f17af3..d3b16d0328 100644 --- a/actionpack/test/dispatch/system_testing/driver_test.rb +++ b/actionpack/test/dispatch/system_testing/driver_test.rb @@ -66,7 +66,7 @@ class DriverTest < ActiveSupport::TestCase end driver.use - expected = { args: ["start-maximized"], mobileEmulation: { deviceName: "iphone 6" }, prefs: { detach: true } } + expected = { "goog:chromeOptions" => { args: ["start-maximized"], mobileEmulation: { deviceName: "iphone 6" }, prefs: { detach: true } } } assert_equal expected, driver_option.as_json end @@ -81,7 +81,7 @@ class DriverTest < ActiveSupport::TestCase end driver.use - expected = { args: ["start-maximized"], mobileEmulation: { deviceName: "iphone 6" }, prefs: { detach: true } } + expected = { "goog:chromeOptions" => { args: ["start-maximized"], mobileEmulation: { deviceName: "iphone 6" }, prefs: { detach: true } } } assert_equal expected, driver_option.as_json end @@ -120,4 +120,17 @@ class DriverTest < ActiveSupport::TestCase driver.use end end + + test "preloads browser's driver_path" do + called = false + + original_driver_path = ::Selenium::WebDriver::Chrome::Service.driver_path + ::Selenium::WebDriver::Chrome::Service.driver_path = -> { called = true } + + ActionDispatch::SystemTesting::Driver.new(:selenium, screen_size: [1400, 1400], using: :chrome) + + assert called + ensure + ::Selenium::WebDriver::Chrome::Service.driver_path = original_driver_path + end end diff --git a/actionpack/test/dispatch/system_testing/system_test_case_test.rb b/actionpack/test/dispatch/system_testing/system_test_case_test.rb index 3319db1665..d235f7ad89 100644 --- a/actionpack/test/dispatch/system_testing/system_test_case_test.rb +++ b/actionpack/test/dispatch/system_testing/system_test_case_test.rb @@ -36,12 +36,10 @@ class SetDriverToSeleniumHeadlessFirefoxTest < DrivenBySeleniumWithHeadlessFiref end class SetHostTest < DrivenByRackTest - test "sets default host" do - assert_equal "http://127.0.0.1", Capybara.app_host - end - test "overrides host" do - host! "http://example.com" + assert_deprecated do + host! "http://example.com" + end assert_equal "http://example.com", Capybara.app_host end diff --git a/actionpack/test/journey/route/definition/scanner_test.rb b/actionpack/test/journey/route/definition/scanner_test.rb index 092177d315..e55ed92cc8 100644 --- a/actionpack/test/journey/route/definition/scanner_test.rb +++ b/actionpack/test/journey/route/definition/scanner_test.rb @@ -66,7 +66,6 @@ module ActionDispatch end private - def assert_tokens(expected_tokens, scanner, pattern) actual_tokens = [] while token = scanner.next_token diff --git a/actionpack/test/journey/router_test.rb b/actionpack/test/journey/router_test.rb index f8d89def6a..fe0e3a975b 100644 --- a/actionpack/test/journey/router_test.rb +++ b/actionpack/test/journey/router_test.rb @@ -503,7 +503,6 @@ module ActionDispatch end private - def get(*args) ActiveSupport::Deprecation.silence do mapper.get(*args) diff --git a/actiontext/lib/action_text/engine.rb b/actiontext/lib/action_text/engine.rb index 0c2aebfd08..0f55d460a1 100644 --- a/actiontext/lib/action_text/engine.rb +++ b/actiontext/lib/action_text/engine.rb @@ -25,6 +25,10 @@ module ActionText def previewable_attachable? representable? end + + def attachable_plain_text_representation(caption = nil) + "[#{caption || filename}]" + end end end diff --git a/actiontext/test/unit/attachment_test.rb b/actiontext/test/unit/attachment_test.rb index 026078dcec..54831a0271 100644 --- a/actiontext/test/unit/attachment_test.rb +++ b/actiontext/test/unit/attachment_test.rb @@ -50,6 +50,11 @@ class ActionText::AttachmentTest < ActiveSupport::TestCase assert_not_nil trix_attachment.attributes["content"] end + test "converts to plain text" do + assert_equal "[Vroom vroom]", ActionText::Attachment.from_attachable(attachable, caption: "Vroom vroom").to_plain_text + assert_equal "[racecar.jpg]", ActionText::Attachment.from_attachable(attachable).to_plain_text + end + test "defaults trix partial to model partial" do attachable = Page.create! title: "Homepage" assert_equal "pages/page", attachable.to_trix_content_attachment_partial_path diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md index a1e94384bd..504b1d3e98 100644 --- a/actionview/CHANGELOG.md +++ b/actionview/CHANGELOG.md @@ -1,3 +1,16 @@ +* annotated_source_code returns an empty array so TemplateErrors without a + template in the backtrace are surfaced properly by DebugExceptions. + + *Guilherme Mansur*, *Kasper Timm Hansen* + +* Add autoload for SyntaxErrorInTemplate so syntax errors are correctly raised by DebugExceptions. + + *Guilherme Mansur*, *Gannon McGibbon* + +* `RenderingHelper` supports rendering objects that `respond_to?` `:render_in` + + *Joel Hawksley*, *Natasha Umer*, *Aaron Patterson*, *Shawn Allen*, *Emily Plummer*, *Diana Mounter*, *John Hawthorn*, *Nathan Herald*, *Zaid Zawaideh*, *Zach Ahn* + * Fix `select_tag` so that it doesn't change `options` when `include_blank` is present. *Younes SERRAJ* diff --git a/actionview/app/assets/javascripts/rails-ujs/features/remote.coffee b/actionview/app/assets/javascripts/rails-ujs/features/remote.coffee index a5b61220bb..d1aeef56c7 100644 --- a/actionview/app/assets/javascripts/rails-ujs/features/remote.coffee +++ b/actionview/app/assets/javascripts/rails-ujs/features/remote.coffee @@ -88,6 +88,6 @@ Rails.preventInsignificantClick = (e) -> data = link.getAttribute('data-params') metaClick = e.metaKey or e.ctrlKey insignificantMetaClick = metaClick and method is 'GET' and not data - primaryMouseKey = e.button is 0 - e.stopImmediatePropagation() if not primaryMouseKey or insignificantMetaClick + nonPrimaryMouseClick = e.button? and e.button isnt 0 + e.stopImmediatePropagation() if nonPrimaryMouseClick or insignificantMetaClick diff --git a/actionview/lib/action_view.rb b/actionview/lib/action_view.rb index 7f85bf2a5e..11b4563548 100644 --- a/actionview/lib/action_view.rb +++ b/actionview/lib/action_view.rb @@ -77,6 +77,7 @@ module ActionView autoload :ActionViewError autoload :EncodingError autoload :TemplateError + autoload :SyntaxErrorInTemplate autoload :WrongEncodingError end end diff --git a/actionview/lib/action_view/base.rb b/actionview/lib/action_view/base.rb index 5253ef7b0c..40d5ed36a1 100644 --- a/actionview/lib/action_view/base.rb +++ b/actionview/lib/action_view/base.rb @@ -3,7 +3,6 @@ require "active_support/core_ext/module/attr_internal" require "active_support/core_ext/module/attribute_accessors" require "active_support/ordered_options" -require "active_support/deprecation" require "action_view/log_subscriber" require "action_view/helpers" require "action_view/context" diff --git a/actionview/lib/action_view/cache_expiry.rb b/actionview/lib/action_view/cache_expiry.rb index 7cdc2e9982..27690561b7 100644 --- a/actionview/lib/action_view/cache_expiry.rb +++ b/actionview/lib/action_view/cache_expiry.rb @@ -41,7 +41,6 @@ module ActionView end private - def dirs_to_watch fs_paths = all_view_paths.grep(FileSystemResolver) fs_paths.map(&:path).sort.uniq diff --git a/actionview/lib/action_view/flows.rb b/actionview/lib/action_view/flows.rb index ff44fa6619..1609777182 100644 --- a/actionview/lib/action_view/flows.rb +++ b/actionview/lib/action_view/flows.rb @@ -68,7 +68,6 @@ module ActionView end private - def inside_fiber? Fiber.current.object_id != @root end diff --git a/actionview/lib/action_view/helpers/active_model_helper.rb b/actionview/lib/action_view/helpers/active_model_helper.rb index e41a95d2ce..e8f1d4fee5 100644 --- a/actionview/lib/action_view/helpers/active_model_helper.rb +++ b/actionview/lib/action_view/helpers/active_model_helper.rb @@ -38,7 +38,6 @@ module ActionView end private - def object_has_errors? object.respond_to?(:errors) && object.errors.respond_to?(:[]) && error_message.present? end diff --git a/actionview/lib/action_view/helpers/asset_tag_helper.rb b/actionview/lib/action_view/helpers/asset_tag_helper.rb index 59d70a1dc4..1e1d97fe75 100644 --- a/actionview/lib/action_view/helpers/asset_tag_helper.rb +++ b/actionview/lib/action_view/helpers/asset_tag_helper.rb @@ -3,7 +3,6 @@ require "active_support/core_ext/array/extract_options" require "active_support/core_ext/hash/keys" require "active_support/core_ext/object/inclusion" -require "active_support/core_ext/object/try" require "action_view/helpers/asset_url_helper" require "action_view/helpers/tag_helper" @@ -268,7 +267,7 @@ module ActionView def preload_link_tag(source, options = {}) href = asset_path(source, skip_pipeline: options.delete(:skip_pipeline)) extname = File.extname(source).downcase.delete(".") - mime_type = options.delete(:type) || Template::Types[extname].try(:to_s) + mime_type = options.delete(:type) || Template::Types[extname]&.to_s as_type = options.delete(:as) || resolve_link_as(extname, mime_type) crossorigin = options.delete(:crossorigin) crossorigin = "anonymous" if crossorigin == true || (crossorigin.blank? && as_type == "font") diff --git a/actionview/lib/action_view/helpers/asset_url_helper.rb b/actionview/lib/action_view/helpers/asset_url_helper.rb index cc62783d60..295f945325 100644 --- a/actionview/lib/action_view/helpers/asset_url_helper.rb +++ b/actionview/lib/action_view/helpers/asset_url_helper.rb @@ -133,6 +133,8 @@ module ActionView # which is implemented by sprockets-rails. # # asset_path("application.js") # => "/assets/application-60aa4fdc5cea14baf5400fba1abf4f2a46a5166bad4772b1effe341570f07de9.js" + # asset_path('application.js', host: 'example.com') # => "//example.com/assets/application.js" + # asset_path("application.js", host: 'example.com', protocol: 'https') # => "https://example.com/assets/application.js" # # === Without the asset pipeline (<tt>skip_pipeline: true</tt>) # diff --git a/actionview/lib/action_view/helpers/cache_helper.rb b/actionview/lib/action_view/helpers/cache_helper.rb index 020aebeea3..5a05f8706a 100644 --- a/actionview/lib/action_view/helpers/cache_helper.rb +++ b/actionview/lib/action_view/helpers/cache_helper.rb @@ -227,7 +227,6 @@ module ActionView end private - def fragment_name_with_digest(name, virtual_path, digest_path) virtual_path ||= @virtual_path diff --git a/actionview/lib/action_view/helpers/date_helper.rb b/actionview/lib/action_view/helpers/date_helper.rb index 9d5e5eaba3..f1d9fdc678 100644 --- a/actionview/lib/action_view/helpers/date_helper.rb +++ b/actionview/lib/action_view/helpers/date_helper.rb @@ -688,7 +688,6 @@ module ActionView end private - def normalize_distance_of_time_argument_to_time(value) if value.is_a?(Numeric) Time.at(value) diff --git a/actionview/lib/action_view/helpers/number_helper.rb b/actionview/lib/action_view/helpers/number_helper.rb index 03ec7df9c1..827e0bd02c 100644 --- a/actionview/lib/action_view/helpers/number_helper.rb +++ b/actionview/lib/action_view/helpers/number_helper.rb @@ -403,7 +403,6 @@ module ActionView end private - def delegate_number_helper_method(method, number, options) return unless number options = escape_unsafe_options(options.symbolize_keys) diff --git a/actionview/lib/action_view/helpers/rendering_helper.rb b/actionview/lib/action_view/helpers/rendering_helper.rb index 7ead691113..4be23b68f3 100644 --- a/actionview/lib/action_view/helpers/rendering_helper.rb +++ b/actionview/lib/action_view/helpers/rendering_helper.rb @@ -35,7 +35,11 @@ module ActionView end end else - view_renderer.render_partial(self, partial: options, locals: locals, &block) + if options.respond_to?(:render_in) + options.render_in(self, &block) + else + view_renderer.render_partial(self, partial: options, locals: locals, &block) + end end end diff --git a/actionview/lib/action_view/helpers/tags/base.rb b/actionview/lib/action_view/helpers/tags/base.rb index 39c01f3334..4ce1f507f3 100644 --- a/actionview/lib/action_view/helpers/tags/base.rb +++ b/actionview/lib/action_view/helpers/tags/base.rb @@ -34,7 +34,6 @@ module ActionView end private - def value if @allow_method_names_outside_object object.public_send @method_name if object && object.respond_to?(@method_name) diff --git a/actionview/lib/action_view/helpers/tags/check_box.rb b/actionview/lib/action_view/helpers/tags/check_box.rb index 4327e07cae..dbf020e514 100644 --- a/actionview/lib/action_view/helpers/tags/check_box.rb +++ b/actionview/lib/action_view/helpers/tags/check_box.rb @@ -39,7 +39,6 @@ module ActionView end private - def checked?(value) case value when TrueClass, FalseClass diff --git a/actionview/lib/action_view/helpers/tags/collection_check_boxes.rb b/actionview/lib/action_view/helpers/tags/collection_check_boxes.rb index 455442178e..d058eb2c72 100644 --- a/actionview/lib/action_view/helpers/tags/collection_check_boxes.rb +++ b/actionview/lib/action_view/helpers/tags/collection_check_boxes.rb @@ -22,7 +22,6 @@ module ActionView end private - def render_component(builder) builder.check_box + builder.label end diff --git a/actionview/lib/action_view/helpers/tags/collection_helpers.rb b/actionview/lib/action_view/helpers/tags/collection_helpers.rb index e1ad11bff8..62060547de 100644 --- a/actionview/lib/action_view/helpers/tags/collection_helpers.rb +++ b/actionview/lib/action_view/helpers/tags/collection_helpers.rb @@ -37,7 +37,6 @@ module ActionView end private - def instantiate_builder(builder_class, item, value, text, html_options) builder_class.new(@template_object, @object_name, @method_name, item, sanitize_attribute_name(value), text, value, html_options) diff --git a/actionview/lib/action_view/helpers/tags/collection_radio_buttons.rb b/actionview/lib/action_view/helpers/tags/collection_radio_buttons.rb index 16d37134e5..0c3b899f53 100644 --- a/actionview/lib/action_view/helpers/tags/collection_radio_buttons.rb +++ b/actionview/lib/action_view/helpers/tags/collection_radio_buttons.rb @@ -21,7 +21,6 @@ module ActionView end private - def render_component(builder) builder.radio_button + builder.label end diff --git a/actionview/lib/action_view/helpers/tags/color_field.rb b/actionview/lib/action_view/helpers/tags/color_field.rb index 39ab1285c3..69b190809f 100644 --- a/actionview/lib/action_view/helpers/tags/color_field.rb +++ b/actionview/lib/action_view/helpers/tags/color_field.rb @@ -12,7 +12,6 @@ module ActionView end private - def validate_color_string(string) regex = /#[0-9a-fA-F]{6}/ if regex.match?(string) diff --git a/actionview/lib/action_view/helpers/tags/date_field.rb b/actionview/lib/action_view/helpers/tags/date_field.rb index b17a907651..ceaabfa99c 100644 --- a/actionview/lib/action_view/helpers/tags/date_field.rb +++ b/actionview/lib/action_view/helpers/tags/date_field.rb @@ -5,7 +5,6 @@ module ActionView module Tags # :nodoc: class DateField < DatetimeField # :nodoc: private - def format_date(value) value.try(:strftime, "%Y-%m-%d") end diff --git a/actionview/lib/action_view/helpers/tags/date_select.rb b/actionview/lib/action_view/helpers/tags/date_select.rb index fe4e3914d7..f222bf2075 100644 --- a/actionview/lib/action_view/helpers/tags/date_select.rb +++ b/actionview/lib/action_view/helpers/tags/date_select.rb @@ -23,7 +23,6 @@ module ActionView end private - def select_type self.class.select_type end diff --git a/actionview/lib/action_view/helpers/tags/datetime_field.rb b/actionview/lib/action_view/helpers/tags/datetime_field.rb index 5d9b639b1b..e2dbf408c8 100644 --- a/actionview/lib/action_view/helpers/tags/datetime_field.rb +++ b/actionview/lib/action_view/helpers/tags/datetime_field.rb @@ -14,7 +14,6 @@ module ActionView end private - def format_date(value) raise NotImplementedError end diff --git a/actionview/lib/action_view/helpers/tags/datetime_local_field.rb b/actionview/lib/action_view/helpers/tags/datetime_local_field.rb index d8f8fd00d1..8908bf9948 100644 --- a/actionview/lib/action_view/helpers/tags/datetime_local_field.rb +++ b/actionview/lib/action_view/helpers/tags/datetime_local_field.rb @@ -11,7 +11,6 @@ module ActionView end private - def format_date(value) value.try(:strftime, "%Y-%m-%dT%T") end diff --git a/actionview/lib/action_view/helpers/tags/label.rb b/actionview/lib/action_view/helpers/tags/label.rb index 02bd099784..436c4cbda3 100644 --- a/actionview/lib/action_view/helpers/tags/label.rb +++ b/actionview/lib/action_view/helpers/tags/label.rb @@ -71,7 +71,6 @@ module ActionView end private - def render_component(builder) builder.translation end diff --git a/actionview/lib/action_view/helpers/tags/month_field.rb b/actionview/lib/action_view/helpers/tags/month_field.rb index 93b2bf11f0..463866a181 100644 --- a/actionview/lib/action_view/helpers/tags/month_field.rb +++ b/actionview/lib/action_view/helpers/tags/month_field.rb @@ -5,7 +5,6 @@ module ActionView module Tags # :nodoc: class MonthField < DatetimeField # :nodoc: private - def format_date(value) value.try(:strftime, "%Y-%m") end diff --git a/actionview/lib/action_view/helpers/tags/radio_button.rb b/actionview/lib/action_view/helpers/tags/radio_button.rb index 621db2b1b5..4ce6c9f6bc 100644 --- a/actionview/lib/action_view/helpers/tags/radio_button.rb +++ b/actionview/lib/action_view/helpers/tags/radio_button.rb @@ -23,7 +23,6 @@ module ActionView end private - def checked?(value) value.to_s == @tag_value.to_s end diff --git a/actionview/lib/action_view/helpers/tags/select.rb b/actionview/lib/action_view/helpers/tags/select.rb index 790721a0b7..172e3a9226 100644 --- a/actionview/lib/action_view/helpers/tags/select.rb +++ b/actionview/lib/action_view/helpers/tags/select.rb @@ -29,7 +29,6 @@ module ActionView end private - # Grouped choices look like this: # # [nil, []] diff --git a/actionview/lib/action_view/helpers/tags/text_field.rb b/actionview/lib/action_view/helpers/tags/text_field.rb index d92967e212..c579e9e79f 100644 --- a/actionview/lib/action_view/helpers/tags/text_field.rb +++ b/actionview/lib/action_view/helpers/tags/text_field.rb @@ -24,7 +24,6 @@ module ActionView end private - def field_type self.class.field_type end diff --git a/actionview/lib/action_view/helpers/tags/time_field.rb b/actionview/lib/action_view/helpers/tags/time_field.rb index 9384a83a3e..e74c578db9 100644 --- a/actionview/lib/action_view/helpers/tags/time_field.rb +++ b/actionview/lib/action_view/helpers/tags/time_field.rb @@ -5,7 +5,6 @@ module ActionView module Tags # :nodoc: class TimeField < DatetimeField # :nodoc: private - def format_date(value) value.try(:strftime, "%T.%L") end diff --git a/actionview/lib/action_view/helpers/tags/week_field.rb b/actionview/lib/action_view/helpers/tags/week_field.rb index 572535d1d6..5a403ed91d 100644 --- a/actionview/lib/action_view/helpers/tags/week_field.rb +++ b/actionview/lib/action_view/helpers/tags/week_field.rb @@ -5,7 +5,6 @@ module ActionView module Tags # :nodoc: class WeekField < DatetimeField # :nodoc: private - def format_date(value) value.try(:strftime, "%Y-W%V") end diff --git a/actionview/lib/action_view/helpers/text_helper.rb b/actionview/lib/action_view/helpers/text_helper.rb index c282505e13..8203a43239 100644 --- a/actionview/lib/action_view/helpers/text_helper.rb +++ b/actionview/lib/action_view/helpers/text_helper.rb @@ -426,7 +426,6 @@ module ActionView end private - def next_index step_index(1) end diff --git a/actionview/lib/action_view/helpers/translation_helper.rb b/actionview/lib/action_view/helpers/translation_helper.rb index d5b0a9263f..baa337c62f 100644 --- a/actionview/lib/action_view/helpers/translation_helper.rb +++ b/actionview/lib/action_view/helpers/translation_helper.rb @@ -60,7 +60,7 @@ module ActionView def translate(key, options = {}) options = options.dup if options.has_key?(:default) - remaining_defaults = Array(options.delete(:default)).compact + remaining_defaults = Array.wrap(options.delete(:default)).compact options[:default] = remaining_defaults unless remaining_defaults.first.kind_of?(Symbol) end diff --git a/actionview/lib/action_view/helpers/url_helper.rb b/actionview/lib/action_view/helpers/url_helper.rb index df83dff681..85fd549177 100644 --- a/actionview/lib/action_view/helpers/url_helper.rb +++ b/actionview/lib/action_view/helpers/url_helper.rb @@ -60,8 +60,8 @@ module ActionView # Creates an anchor element of the given +name+ using a URL created by the set of +options+. # See the valid options in the documentation for +url_for+. It's also possible to - # pass a String instead of an options hash, which generates an anchor element that uses the - # value of the String as the href for the link. Using a <tt>:back</tt> Symbol instead + # pass a \String instead of an options hash, which generates an anchor element that uses the + # value of the \String as the href for the link. Using a <tt>:back</tt> \Symbol instead # of an options hash will generate a link to the referrer (a JavaScript back link # will be used in place of a referrer if none exists). If +nil+ is passed as the name # the value of the link itself will become the name. @@ -226,7 +226,7 @@ module ActionView # The +options+ hash accepts the same options as +url_for+. # # There are a few special +html_options+: - # * <tt>:method</tt> - Symbol of HTTP verb. Supported verbs are <tt>:post</tt>, <tt>:get</tt>, + # * <tt>:method</tt> - \Symbol of HTTP verb. Supported verbs are <tt>:post</tt>, <tt>:get</tt>, # <tt>:delete</tt>, <tt>:patch</tt>, and <tt>:put</tt>. By default it will be <tt>:post</tt>. # * <tt>:disabled</tt> - If set to true, it will generate a disabled button. # * <tt>:data</tt> - This option can be used to add custom data attributes. @@ -235,7 +235,7 @@ module ActionView # * <tt>:form</tt> - This hash will be form attributes # * <tt>:form_class</tt> - This controls the class of the form within which the submit button will # be placed - # * <tt>:params</tt> - Hash of parameters to be rendered as hidden fields within the form. + # * <tt>:params</tt> - \Hash of parameters to be rendered as hidden fields within the form. # # ==== Data attributes # @@ -253,7 +253,7 @@ module ActionView # # <input value="New" type="submit" /> # # </form>" # - # <%= button_to "New", new_articles_path %> + # <%= button_to "New", new_article_path %> # # => "<form method="post" action="/articles/new" class="button_to"> # # <input value="New" type="submit" /> # # </form>" @@ -571,6 +571,54 @@ module ActionView end end + # Creates an SMS anchor link tag to the specified +phone_number+, which is + # also used as the name of the link unless +name+ is specified. Additional + # HTML attributes for the link can be passed in +html_options+. + # + # When clicked, an SMS message is prepopulated with the passed phone number + # and optional +body+ value. + # + # +sms_to+ has a +body+ option for customizing the SMS message itself by + # passing special keys to +html_options+. + # + # ==== Options + # * <tt>:body</tt> - Preset the body of the message. + # + # ==== Examples + # sms_to "5155555785" + # # => <a href="sms:5155555785;">5155555785</a> + # + # sms_to "5155555785", "Text me" + # # => <a href="sms:5155555785;">Text me</a> + # + # sms_to "5155555785", "Text me", + # body: "Hello Jim I have a question about your product." + # # => <a href="sms:5155555785;?body=Hello%20Jim%20I%20have%20a%20question%20about%20your%20product">Text me</a> + # + # You can use a block as well if your link target is hard to fit into the name parameter. \ERB example: + # + # <%= sms_to "5155555785" do %> + # <strong>Text me:</strong> + # <% end %> + # # => <a href="sms:5155555785;"> + # <strong>Text me:</strong> + # </a> + def sms_to(phone_number, name = nil, html_options = {}, &block) + html_options, name = name, nil if block_given? + html_options = (html_options || {}).stringify_keys + + extras = %w{ body }.map! { |item| + option = html_options.delete(item).presence || next + "#{item.dasherize}=#{ERB::Util.url_encode(option)}" + }.compact + extras = extras.empty? ? "" : "?&" + extras.join("&") + + encoded_phone_number = ERB::Util.url_encode(phone_number) + html_options["href"] = "sms:#{encoded_phone_number};#{extras}" + + content_tag("a", name || phone_number, html_options, &block) + end + private def convert_options_to_data_attributes(options, html_options) if html_options diff --git a/actionview/lib/action_view/layouts.rb b/actionview/lib/action_view/layouts.rb index 08f66bf435..be21ff0e5d 100644 --- a/actionview/lib/action_view/layouts.rb +++ b/actionview/lib/action_view/layouts.rb @@ -224,7 +224,6 @@ module ActionView # that if no layout conditions are used, this method is not used module LayoutConditions # :nodoc: private - # Determines whether the current action has a layout definition by # checking the action name against the :only and :except conditions # set by the <tt>layout</tt> method. @@ -334,7 +333,6 @@ module ActionView end private - # If no layout is supplied, look for a template named the return # value of this method. # @@ -372,7 +370,6 @@ module ActionView end private - def _conditional_layout? true end diff --git a/actionview/lib/action_view/log_subscriber.rb b/actionview/lib/action_view/log_subscriber.rb index 227f025385..02ac0ce477 100644 --- a/actionview/lib/action_view/log_subscriber.rb +++ b/actionview/lib/action_view/log_subscriber.rb @@ -54,7 +54,6 @@ module ActionView end private - EMPTY = "" def from_rails_root(string) # :doc: string = string.sub(rails_root, EMPTY) diff --git a/actionview/lib/action_view/lookup_context.rb b/actionview/lib/action_view/lookup_context.rb index b9a8cc129c..211fbc8e6c 100644 --- a/actionview/lib/action_view/lookup_context.rb +++ b/actionview/lib/action_view/lookup_context.rb @@ -3,7 +3,6 @@ require "concurrent/map" require "active_support/core_ext/module/remove_method" require "active_support/core_ext/module/attribute_accessors" -require "active_support/deprecation" require "action_view/template/resolver" module ActionView @@ -112,7 +111,6 @@ module ActionView end private - def _set_detail(key, value) # :doc: @details = @details.dup if @digest_cache || @details_key @digest_cache = nil @@ -171,7 +169,6 @@ module ActionView end private - # Whenever setting view paths, makes a copy so that we can manipulate them in # instance objects as we wish. def build_view_paths(paths) diff --git a/actionview/lib/action_view/path_set.rb b/actionview/lib/action_view/path_set.rb index d54749d8e3..a6401323db 100644 --- a/actionview/lib/action_view/path_set.rb +++ b/actionview/lib/action_view/path_set.rb @@ -69,7 +69,6 @@ module ActionView #:nodoc: end private - def _find_all(path, prefixes, args) prefixes = [prefixes] if String === prefixes prefixes.each do |prefix| diff --git a/actionview/lib/action_view/record_identifier.rb b/actionview/lib/action_view/record_identifier.rb index ee39b6050d..7491dbe15a 100644 --- a/actionview/lib/action_view/record_identifier.rb +++ b/actionview/lib/action_view/record_identifier.rb @@ -95,7 +95,6 @@ module ActionView end private - # Returns a string representation of the key attribute(s) that is suitable for use in an HTML DOM id. # This can be overwritten to customize the default generated string representation if desired. # If you need to read back a key from a dom_id in order to query for the underlying database record, diff --git a/actionview/lib/action_view/renderer/abstract_renderer.rb b/actionview/lib/action_view/renderer/abstract_renderer.rb index b397c02cde..a52e5d3aca 100644 --- a/actionview/lib/action_view/renderer/abstract_renderer.rb +++ b/actionview/lib/action_view/renderer/abstract_renderer.rb @@ -74,7 +74,6 @@ module ActionView end private - def extract_details(options) # :doc: @lookup_context.registered_details.each_with_object({}) do |key, details| value = options[key] diff --git a/actionview/lib/action_view/renderer/partial_renderer.rb b/actionview/lib/action_view/renderer/partial_renderer.rb index 608e417583..46bc4c9d5f 100644 --- a/actionview/lib/action_view/renderer/partial_renderer.rb +++ b/actionview/lib/action_view/renderer/partial_renderer.rb @@ -322,7 +322,6 @@ module ActionView end private - def render_collection(view, template) identifier = (template && template.identifier) || @path instrument(:collection, identifier: identifier, count: @collection.size) do |payload| diff --git a/actionview/lib/action_view/renderer/streaming_template_renderer.rb b/actionview/lib/action_view/renderer/streaming_template_renderer.rb index 19fa399e2c..08a280c7ee 100644 --- a/actionview/lib/action_view/renderer/streaming_template_renderer.rb +++ b/actionview/lib/action_view/renderer/streaming_template_renderer.rb @@ -27,7 +27,6 @@ module ActionView end private - # This is the same logging logic as in ShowExceptions middleware. def log_error(exception) logger = ActionView::Base.logger @@ -55,7 +54,6 @@ module ActionView end private - def delayed_render(buffer, template, layout, view, locals) # Wrap the given buffer in the StreamingBuffer and pass it to the # underlying template handler. Now, every time something is concatenated diff --git a/actionview/lib/action_view/renderer/template_renderer.rb b/actionview/lib/action_view/renderer/template_renderer.rb index 4cd8fc5bb2..b2d7332572 100644 --- a/actionview/lib/action_view/renderer/template_renderer.rb +++ b/actionview/lib/action_view/renderer/template_renderer.rb @@ -14,7 +14,6 @@ module ActionView end private - # Determine the template to be rendered using the given options. def determine_template(options) keys = options.has_key?(:locals) ? options[:locals].keys : [] diff --git a/actionview/lib/action_view/rendering.rb b/actionview/lib/action_view/rendering.rb index 5a06bd9da6..7247598ac2 100644 --- a/actionview/lib/action_view/rendering.rb +++ b/actionview/lib/action_view/rendering.rb @@ -104,7 +104,6 @@ module ActionView end private - # Find and render a template based on the options given. def _render_template(options) variant = options.delete(:variant) diff --git a/actionview/lib/action_view/template.rb b/actionview/lib/action_view/template.rb index b80bf56c1b..3877108fef 100644 --- a/actionview/lib/action_view/template.rb +++ b/actionview/lib/action_view/template.rb @@ -1,8 +1,6 @@ # frozen_string_literal: true -require "active_support/core_ext/object/try" require "active_support/core_ext/kernel/singleton_class" -require "active_support/deprecation" require "thread" require "delegate" @@ -264,7 +262,6 @@ module ActionView end private - # Compile a template. This method ensures a template is compiled # just once and removes the source after it is compiled. def compile!(view) diff --git a/actionview/lib/action_view/template/error.rb b/actionview/lib/action_view/template/error.rb index d0ea03e228..7fc74a5502 100644 --- a/actionview/lib/action_view/template/error.rb +++ b/actionview/lib/action_view/template/error.rb @@ -81,8 +81,8 @@ module ActionView end end - def source_extract(indentation = 0, output = :console) - return unless num = line_number + def source_extract(indentation = 0) + return [] unless num = line_number num = num.to_i source_code = @template.source.split("\n") @@ -91,9 +91,9 @@ module ActionView end_on_line = [ num + SOURCE_CODE_RADIUS - 1, source_code.length].min indent = end_on_line.to_s.size + indentation - return unless source_code = source_code[start_on_line..end_on_line] + return [] unless source_code = source_code[start_on_line..end_on_line] - formatted_code_for(source_code, start_on_line, indent, output) + formatted_code_for(source_code, start_on_line, indent) end def sub_template_of(template_path) @@ -114,7 +114,6 @@ module ActionView end private - def source_location if line_number "on line ##{line_number} of " @@ -123,15 +122,11 @@ module ActionView end + file_name end - def formatted_code_for(source_code, line_counter, indent, output) - start_value = (output == :html) ? {} : [] - source_code.inject(start_value) do |result, line| + def formatted_code_for(source_code, line_counter, indent) + indent_template = "%#{indent}s: %s" + source_code.map do |line| line_counter += 1 - if output == :html - result.update(line_counter.to_s => "%#{indent}s %s\n" % ["", line]) - else - result << "%#{indent}s: %s" % [line_counter, line] - end + indent_template % [line_counter, line] end end end diff --git a/actionview/lib/action_view/template/handlers.rb b/actionview/lib/action_view/template/handlers.rb index 6450513003..c7ef456125 100644 --- a/actionview/lib/action_view/template/handlers.rb +++ b/actionview/lib/action_view/template/handlers.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require "active_support/deprecation" - module ActionView #:nodoc: # = Action View Template Handlers class Template #:nodoc: diff --git a/actionview/lib/action_view/template/handlers/erb.rb b/actionview/lib/action_view/template/handlers/erb.rb index b6314a5bc3..69a5a0b1b9 100644 --- a/actionview/lib/action_view/template/handlers/erb.rb +++ b/actionview/lib/action_view/template/handlers/erb.rb @@ -63,7 +63,6 @@ module ActionView end private - def valid_encoding(string, encoding) # If a magic encoding comment was found, tag the # String with this encoding. This is for a case diff --git a/actionview/lib/action_view/template/html.rb b/actionview/lib/action_view/template/html.rb index ecd1c31e79..563bffd333 100644 --- a/actionview/lib/action_view/template/html.rb +++ b/actionview/lib/action_view/template/html.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require "active_support/deprecation" - module ActionView #:nodoc: # = Action View HTML Template class Template #:nodoc: diff --git a/actionview/lib/action_view/template/resolver.rb b/actionview/lib/action_view/template/resolver.rb index ce53eb046d..bfac4c08a0 100644 --- a/actionview/lib/action_view/template/resolver.rb +++ b/actionview/lib/action_view/template/resolver.rb @@ -93,7 +93,6 @@ module ActionView end private - def canonical_no_templates(templates) templates.empty? ? NO_TEMPLATES : templates end @@ -130,7 +129,6 @@ module ActionView end private - def _find_all(name, prefix, partial, details, key, locals) find_templates(name, prefix, partial, details, locals) end @@ -183,7 +181,6 @@ module ActionView end private - def _find_all(name, prefix, partial, details, key, locals) path = Path.build(name, prefix, partial) query(path, details, details[:formats], locals, cache: !!key) @@ -282,12 +279,8 @@ module ActionView format, variant = pieces.last.split(EXTENSIONS[:variants], 2) if pieces.last format = if format Template::Types[format]&.ref - else - if handler.respond_to?(:default_format) # default_format can return nil - handler.default_format - else - nil - end + elsif handler.respond_to?(:default_format) # default_format can return nil + handler.default_format end # Template::Types[format] and handler.default_format can return nil @@ -323,7 +316,6 @@ module ActionView end private - def find_template_paths_from_details(path, details) # Instead of checking for every possible path, as our other globs would # do, scan the directory for files with the right prefix. diff --git a/actionview/lib/action_view/test_case.rb b/actionview/lib/action_view/test_case.rb index 3a75633743..b08f8b2dfb 100644 --- a/actionview/lib/action_view/test_case.rb +++ b/actionview/lib/action_view/test_case.rb @@ -93,7 +93,6 @@ module ActionView end private - def include_helper_modules! helper(helper_class) if helper_class include _helpers @@ -163,7 +162,6 @@ module ActionView end private - # Need to experiment if this priority is the best one: rendered => output_buffer def document_root_element Nokogiri::HTML::Document.parse(@rendered.blank? ? @output_buffer : @rendered).root diff --git a/actionview/lib/action_view/testing/resolvers.rb b/actionview/lib/action_view/testing/resolvers.rb index 87e6286907..99443663dd 100644 --- a/actionview/lib/action_view/testing/resolvers.rb +++ b/actionview/lib/action_view/testing/resolvers.rb @@ -22,7 +22,6 @@ module ActionView #:nodoc: end private - def query(path, exts, _, locals, cache:) query = +"" EXTENSIONS.each do |ext, prefix| diff --git a/actionview/lib/action_view/unbound_template.rb b/actionview/lib/action_view/unbound_template.rb index db69b6d016..3d4434b2e9 100644 --- a/actionview/lib/action_view/unbound_template.rb +++ b/actionview/lib/action_view/unbound_template.rb @@ -4,9 +4,9 @@ require "concurrent/map" module ActionView class UnboundTemplate - def initialize(source, identifer, handler, options) + def initialize(source, identifier, handler, options) @source = source - @identifer = identifer + @identifier = identifier @handler = handler @options = options @@ -18,12 +18,11 @@ module ActionView end private - def build_template(locals) options = @options.merge(locals: locals) Template.new( @source, - @identifer, + @identifier, @handler, options ) diff --git a/actionview/lib/action_view/view_paths.rb b/actionview/lib/action_view/view_paths.rb index 3ca5aedc14..7e05f15648 100644 --- a/actionview/lib/action_view/view_paths.rb +++ b/actionview/lib/action_view/view_paths.rb @@ -29,7 +29,6 @@ module ActionView end private - # Override this method in your controller if you want to change paths prefixes for finding views. # Prefixes defined here will still be added to parents' <tt>._prefixes</tt>. def local_prefixes diff --git a/actionview/test/abstract_unit.rb b/actionview/test/abstract_unit.rb index 2c1b277b41..b652f2e6cb 100644 --- a/actionview/test/abstract_unit.rb +++ b/actionview/test/abstract_unit.rb @@ -192,6 +192,8 @@ module ActionDispatch end class ActiveSupport::TestCase + parallelize + include ActiveSupport::Testing::MethodCallAssertions private diff --git a/actionview/test/actionpack/abstract/abstract_controller_test.rb b/actionview/test/actionpack/abstract/abstract_controller_test.rb index eecc19d413..2de81596b5 100644 --- a/actionview/test/actionpack/abstract/abstract_controller_test.rb +++ b/actionview/test/actionpack/abstract/abstract_controller_test.rb @@ -230,6 +230,7 @@ module AbstractController class ActionMissingRespondToActionController < AbstractController::Base # No actions + private def action_missing(action_name) self.response_body = "success" @@ -242,7 +243,6 @@ module AbstractController def fail() self.response_body = "fail" end private - def method_for_action(action_name) action_name.to_s != "fail" && action_name end diff --git a/actionview/test/actionpack/abstract/layouts_test.rb b/actionview/test/actionpack/abstract/layouts_test.rb index 1146e6f64b..15643c161d 100644 --- a/actionview/test/actionpack/abstract/layouts_test.rb +++ b/actionview/test/actionpack/abstract/layouts_test.rb @@ -140,6 +140,7 @@ module AbstractControllerTests def index render template: ActionView::Template::Text.new("Hello symbol!") end + private def hello "overwrite" @@ -295,7 +296,7 @@ module AbstractControllerTests 10.times do |x| controller = WithString.new controller.define_singleton_method :index do - render template: ActionView::Template::Text.new("Hello string!"), locals: { :"x#{x}" => :omg } + render template: ActionView::Template::Text.new("Hello string!"), locals: { "x#{x}": :omg } end controller.process(:index) end diff --git a/actionview/test/actionpack/controller/render_test.rb b/actionview/test/actionpack/controller/render_test.rb index 9b1a720636..64070a9542 100644 --- a/actionview/test/actionpack/controller/render_test.rb +++ b/actionview/test/actionpack/controller/render_test.rb @@ -607,7 +607,6 @@ class TestController < ActionController::Base end private - def set_variable_for_layout @variable_for_layout = nil end diff --git a/actionview/test/active_record_unit.rb b/actionview/test/active_record_unit.rb index e4ea6a426d..4efb31a360 100644 --- a/actionview/test/active_record_unit.rb +++ b/actionview/test/active_record_unit.rb @@ -42,6 +42,12 @@ class ActiveRecordTestConnector self.able_to_connect = false end + def reconnect + return unless able_to_connect + ActiveRecord::Base.connection.reconnect! + load_schema + end + private def setup_connection if Object.const_defined?(:ActiveRecord) @@ -102,3 +108,7 @@ class ActiveRecordTestCase < ActionController::TestCase end ActiveRecordTestConnector.setup + +ActiveSupport::Testing::Parallelization.after_fork_hook do + ActiveRecordTestConnector.reconnect +end diff --git a/actionview/test/activerecord/form_helper_activerecord_test.rb b/actionview/test/activerecord/form_helper_activerecord_test.rb index 34655bfe23..1b196ade6d 100644 --- a/actionview/test/activerecord/form_helper_activerecord_test.rb +++ b/actionview/test/activerecord/form_helper_activerecord_test.rb @@ -58,7 +58,6 @@ class FormHelperActiveRecordTest < ActionView::TestCase end private - def hidden_fields(method = nil) txt = +%{<input name="utf8" type="hidden" value="✓" />} diff --git a/actionview/test/lib/test_component.rb b/actionview/test/lib/test_component.rb new file mode 100644 index 0000000000..0d45d6e25f --- /dev/null +++ b/actionview/test/lib/test_component.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +class TestComponent < ActionView::Base + include ActiveModel::Validations + + validates :content, :title, presence: true + delegate :render, to: :view_context + + def initialize(title:) + @title = title + end + + # Entrypoint for rendering. Called by ActionView::RenderingHelper#render. + # + # Returns ActionView::OutputBuffer. + def render_in(view_context, &block) + self.class.compile + @view_context = view_context + @content = view_context.capture(&block) if block_given? + validate! + rendered_template + end + + def self.template + <<~'erb' + <span title="<%= title %>"><%= content %> (<%= render(plain: "Inline render") %>)</span> + erb + end + + def self.compile + @compiled ||= nil + return if @compiled + + class_eval( + "def rendered_template; @output_buffer = ActionView::OutputBuffer.new; " + + ActionView::Template::Handlers::ERB.erb_implementation.new(template, trim: true).src + + "; end" + ) + + @compiled = true + end + +private + attr_reader :content, :title, :view_context +end diff --git a/actionview/test/template/compiled_templates_test.rb b/actionview/test/template/compiled_templates_test.rb index d7f2e8ee07..59fa058bed 100644 --- a/actionview/test/template/compiled_templates_test.rb +++ b/actionview/test/template/compiled_templates_test.rb @@ -60,46 +60,8 @@ class CompiledTemplatesTest < ActiveSupport::TestCase assert_equal "two", render(template: "test/render_file_with_locals_and_default", locals: { secret: "two" }) end - def test_template_changes_are_not_reflected_with_cached_templates - assert_equal "Hello world!", render(template: "test/hello_world") - modify_template "test/hello_world.erb", "Goodbye world!" do - assert_equal "Hello world!", render(template: "test/hello_world") - end - assert_equal "Hello world!", render(template: "test/hello_world") - end - - def test_template_changes_are_reflected_with_uncached_templates - assert_equal "Hello world!", render_without_cache(template: "test/hello_world") - modify_template "test/hello_world.erb", "Goodbye world!" do - assert_equal "Goodbye world!", render_without_cache(template: "test/hello_world") - end - assert_equal "Hello world!", render_without_cache(template: "test/hello_world") - end - private def render(*args) - render_with_cache(*args) - end - - def render_with_cache(*args) - view_paths = ActionController::Base.view_paths - view_class.with_view_paths(view_paths, {}).render(*args) - end - - def render_without_cache(*args) - path = ActionView::FileSystemResolver.new(FIXTURE_LOAD_PATH) - view_paths = ActionView::PathSet.new([path]) - view_class.with_view_paths(view_paths, {}).render(*args) - end - - def modify_template(template, content) - filename = "#{FIXTURE_LOAD_PATH}/#{template}" - old_content = File.read(filename) - begin - File.open(filename, "wb+") { |f| f.write(content) } - yield - ensure - File.open(filename, "wb+") { |f| f.write(old_content) } - end + ActionController::Base.render(*args) end end diff --git a/actionview/test/template/form_helper_test.rb b/actionview/test/template/form_helper_test.rb index 91052e5ae2..83b089397c 100644 --- a/actionview/test/template/form_helper_test.rb +++ b/actionview/test/template/form_helper_test.rb @@ -1897,7 +1897,6 @@ class FormHelperTest < ActionView::TestCase def test_form_tags_do_not_call_private_properties_on_form_object obj = Class.new do private - def private_property raise "This method should not be called." end diff --git a/actionview/test/template/form_options_helper_test.rb b/actionview/test/template/form_options_helper_test.rb index c9c36917d6..d7a7b95ab3 100644 --- a/actionview/test/template/form_options_helper_test.rb +++ b/actionview/test/template/form_options_helper_test.rb @@ -1472,7 +1472,6 @@ class FormOptionsHelperTest < ActionView::TestCase end private - def dummy_posts [ Post.new("<Abe> went home", "<Abe>", "To a little house", "shh!"), Post.new("Babe went home", "Babe", "To a little house", "shh!"), diff --git a/actionview/test/template/form_tag_helper_test.rb b/actionview/test/template/form_tag_helper_test.rb index 70c5ae6771..80afed96e5 100644 --- a/actionview/test/template/form_tag_helper_test.rb +++ b/actionview/test/template/form_tag_helper_test.rb @@ -803,7 +803,6 @@ class FormTagHelperTest < ActionView::TestCase end private - def root_elem(rendered_content) Nokogiri::HTML::DocumentFragment.parse(rendered_content).children.first # extract from nodeset end diff --git a/actionview/test/template/render_test.rb b/actionview/test/template/render_test.rb index 2235a7816f..c82264a170 100644 --- a/actionview/test/template/render_test.rb +++ b/actionview/test/template/render_test.rb @@ -2,6 +2,8 @@ require "abstract_unit" require "controller/fake_models" +require "test_component" +require "active_model/validations" class TestController < ActionController::Base end @@ -670,6 +672,21 @@ module RenderTestCases def test_render_throws_exception_when_no_extensions_passed_to_register_template_handler_function_call assert_raises(ArgumentError) { ActionView::Template.register_template_handler CustomHandler } end + + def test_render_component + assert_equal( + %(<span title="my title">Hello, World! (Inline render)</span>), + @view.render(TestComponent.new(title: "my title")) { "Hello, World!" }.strip + ) + end + + def test_render_component_with_validation_error + error = assert_raises(ActiveModel::ValidationError) do + @view.render(TestComponent.new(title: "my title")).strip + end + + assert_match "Content can't be blank", error.message + end end class CachedViewRenderTest < ActiveSupport::TestCase diff --git a/actionview/test/template/template_error_test.rb b/actionview/test/template/template_error_test.rb index c4dc88e4aa..643c29602b 100644 --- a/actionview/test/template/template_error_test.rb +++ b/actionview/test/template/template_error_test.rb @@ -34,4 +34,20 @@ class TemplateErrorTest < ActiveSupport::TestCase assert_equal "#<ActionView::Template::Error: original>", error.inspect end + + def test_annotated_source_code_returns_empty_array_if_source_cant_be_found + template = Class.new do + def identifier + "something" + end + end.new + + error = begin + raise + rescue + raise ActionView::Template::Error.new(template) rescue $! + end + + assert_equal [], error.annotated_source_code + end end diff --git a/actionview/test/template/translation_helper_test.rb b/actionview/test/template/translation_helper_test.rb index 9afdc3c68f..3475a1dada 100644 --- a/actionview/test/template/translation_helper_test.rb +++ b/actionview/test/template/translation_helper_test.rb @@ -121,6 +121,11 @@ class TranslationHelperTest < ActiveSupport::TestCase I18n.exception_handler = old_exception_handler end + def test_hash_default + default = { separator: ".", delimiter: "," } + assert_equal default, translate(:'special.number.format', default: default) + end + def test_translation_returning_an_array expected = %w(foo bar) assert_equal expected, translate(:"translations.array") diff --git a/actionview/test/template/url_helper_test.rb b/actionview/test/template/url_helper_test.rb index 632b32f09f..bce6e7f370 100644 --- a/actionview/test/template/url_helper_test.rb +++ b/actionview/test/template/url_helper_test.rb @@ -708,6 +708,68 @@ class UrlHelperTest < ActiveSupport::TestCase assert_equal({ class: "special" }, options) end + def test_sms_to + assert_dom_equal %{<a href="sms:15155555785;">15155555785</a>}, sms_to("15155555785") + assert_dom_equal %{<a href="sms:15155555785;">Jim Jones</a>}, sms_to("15155555785", "Jim Jones") + assert_dom_equal( + %{<a class="admin" href="sms:15155555785;">Jim Jones</a>}, + sms_to("15155555785", "Jim Jones", "class" => "admin") + ) + assert_equal sms_to("15155555785", "Jim Jones", "class" => "admin"), + sms_to("15155555785", "Jim Jones", class: "admin") + end + + def test_sms_to_with_options + assert_dom_equal( + %{<a class="simple-class" href="sms:15155555785;?&body=Hello%20from%20Jim">Text me</a>}, + sms_to("15155555785", "Text me", class: "simple-class", body: "Hello from Jim") + ) + + assert_dom_equal( + %{<a href="sms:15155555785;?&body=This%20is%20the%20body%20of%20the%20message.">Text me</a>}, + sms_to("15155555785", "Text me", body: "This is the body of the message.") + ) + end + + def test_sms_with_img + assert_dom_equal %{<a href="sms:15155555785;"><img src="/feedback.png" /></a>}, + sms_to("15155555785", raw('<img src="/feedback.png" />')) + end + + def test_sms_with_html_safe_string + assert_dom_equal( + %{<a href="sms:1%2B5155555785;">1+5155555785</a>}, + sms_to(raw("1+5155555785")) + ) + end + + def test_sms_with_nil + assert_dom_equal( + %{<a href="sms:;"></a>}, + sms_to(nil) + ) + end + + def test_sms_returns_html_safe_string + assert_predicate sms_to("15155555785"), :html_safe? + end + + def test_sms_with_block + assert_dom_equal %{<a href="sms:15155555785;"><span>Text me</span></a>}, + sms_to("15155555785") { content_tag(:span, "Text me") } + end + + def test_sms_with_block_and_options + assert_dom_equal %{<a class="special" href="sms:15155555785;?&body=Hello%20from%20Jim"><span>Text me</span></a>}, + sms_to("15155555785", body: "Hello from Jim", class: "special") { content_tag(:span, "Text me") } + end + + def test_sms_does_not_modify_html_options_hash + options = { class: "special" } + sms_to "15155555785", "ME!", options + assert_equal({ class: "special" }, options) + end + def protect_against_forgery? request_forgery end diff --git a/actionview/test/ujs/public/test/data-remote.js b/actionview/test/ujs/public/test/data-remote.js index 9e41067549..16ea114f3b 100644 --- a/actionview/test/ujs/public/test/data-remote.js +++ b/actionview/test/ujs/public/test/data-remote.js @@ -82,6 +82,20 @@ asyncTest('right/mouse-wheel-clicking on a link does not fire ajaxyness', 0, fun setTimeout(function() { start() }, 13) }) +asyncTest('clicking on a link via a non-mouse Event (such as from js) works', 1, function() { + var link = $('a[data-remote]') + + link + .removeAttr('data-params') + .bindNative('ajax:beforeSend', function() { + ok(true, 'ajax should be triggered') + }) + + Rails.fire(link[0], 'click') + + setTimeout(function() { start() }, 13) +}) + asyncTest('ctrl-clicking on a link still fires ajax for non-GET links and for links with "data-params"', 2, function() { var link = $('a[data-remote]') diff --git a/activejob/lib/active_job/arguments.rb b/activejob/lib/active_job/arguments.rb index 92eb58aaaf..e08e30040b 100644 --- a/activejob/lib/active_job/arguments.rb +++ b/activejob/lib/active_job/arguments.rb @@ -45,7 +45,6 @@ module ActiveJob end private - # :nodoc: PERMITTED_TYPES = [ NilClass, String, Integer, Float, BigDecimal, TrueClass, FalseClass ] # :nodoc: diff --git a/activejob/lib/active_job/serializers/date_serializer.rb b/activejob/lib/active_job/serializers/date_serializer.rb index e995d30faa..3ec587bc54 100644 --- a/activejob/lib/active_job/serializers/date_serializer.rb +++ b/activejob/lib/active_job/serializers/date_serializer.rb @@ -12,7 +12,6 @@ module ActiveJob end private - def klass Date end diff --git a/activejob/lib/active_job/serializers/date_time_serializer.rb b/activejob/lib/active_job/serializers/date_time_serializer.rb index fe780a1978..42df338b73 100644 --- a/activejob/lib/active_job/serializers/date_time_serializer.rb +++ b/activejob/lib/active_job/serializers/date_time_serializer.rb @@ -12,7 +12,6 @@ module ActiveJob end private - def klass DateTime end diff --git a/activejob/lib/active_job/serializers/duration_serializer.rb b/activejob/lib/active_job/serializers/duration_serializer.rb index 715fe27a5c..b35eaf5f60 100644 --- a/activejob/lib/active_job/serializers/duration_serializer.rb +++ b/activejob/lib/active_job/serializers/duration_serializer.rb @@ -15,7 +15,6 @@ module ActiveJob end private - def klass ActiveSupport::Duration end diff --git a/activejob/lib/active_job/serializers/object_serializer.rb b/activejob/lib/active_job/serializers/object_serializer.rb index 6d280969be..be69ddf90c 100644 --- a/activejob/lib/active_job/serializers/object_serializer.rb +++ b/activejob/lib/active_job/serializers/object_serializer.rb @@ -44,7 +44,6 @@ module ActiveJob end private - # The class of the object that will be serialized. def klass # :doc: raise NotImplementedError diff --git a/activejob/lib/active_job/serializers/symbol_serializer.rb b/activejob/lib/active_job/serializers/symbol_serializer.rb index 7e1f9553a2..3f6ee9101f 100644 --- a/activejob/lib/active_job/serializers/symbol_serializer.rb +++ b/activejob/lib/active_job/serializers/symbol_serializer.rb @@ -12,7 +12,6 @@ module ActiveJob end private - def klass Symbol end diff --git a/activejob/lib/active_job/serializers/time_serializer.rb b/activejob/lib/active_job/serializers/time_serializer.rb index fe20772f35..d385cca6bb 100644 --- a/activejob/lib/active_job/serializers/time_serializer.rb +++ b/activejob/lib/active_job/serializers/time_serializer.rb @@ -12,7 +12,6 @@ module ActiveJob end private - def klass Time end diff --git a/activejob/lib/active_job/serializers/time_with_zone_serializer.rb b/activejob/lib/active_job/serializers/time_with_zone_serializer.rb index 43017fc75b..0b29012072 100644 --- a/activejob/lib/active_job/serializers/time_with_zone_serializer.rb +++ b/activejob/lib/active_job/serializers/time_with_zone_serializer.rb @@ -12,7 +12,6 @@ module ActiveJob end private - def klass ActiveSupport::TimeWithZone end diff --git a/activejob/test/cases/serializers_test.rb b/activejob/test/cases/serializers_test.rb index bee0c061bd..2b9ba75ae0 100644 --- a/activejob/test/cases/serializers_test.rb +++ b/activejob/test/cases/serializers_test.rb @@ -26,7 +26,6 @@ class SerializersTest < ActiveSupport::TestCase end private - def klass DummyValueObject end diff --git a/activejob/test/jobs/timezone_dependent_job.rb b/activejob/test/jobs/timezone_dependent_job.rb index 41f473d533..f63ff95b95 100644 --- a/activejob/test/jobs/timezone_dependent_job.rb +++ b/activejob/test/jobs/timezone_dependent_job.rb @@ -15,7 +15,6 @@ class TimezoneDependentJob < ActiveJob::Base end private - def localtime(*args) Time.zone ? Time.zone.local(*args) : Time.utc(*args) end diff --git a/activejob/test/support/integration/test_case_helpers.rb b/activejob/test/support/integration/test_case_helpers.rb index 973ee07764..d8931a74ed 100644 --- a/activejob/test/support/integration/test_case_helpers.rb +++ b/activejob/test/support/integration/test_case_helpers.rb @@ -19,7 +19,6 @@ module TestCaseHelpers end private - def jobs_manager JobsManager.current_manager end diff --git a/activemodel/lib/active_model.rb b/activemodel/lib/active_model.rb index c9140dc582..756473e38d 100644 --- a/activemodel/lib/active_model.rb +++ b/activemodel/lib/active_model.rb @@ -53,6 +53,7 @@ module ActiveModel eager_autoload do autoload :Errors + autoload :Error autoload :RangeError, "active_model/errors" autoload :StrictValidationFailed, "active_model/errors" autoload :UnknownAttributeError, "active_model/errors" diff --git a/activemodel/lib/active_model/attribute_assignment.rb b/activemodel/lib/active_model/attribute_assignment.rb index f0e3458f51..9bdec0dfda 100644 --- a/activemodel/lib/active_model/attribute_assignment.rb +++ b/activemodel/lib/active_model/attribute_assignment.rb @@ -38,7 +38,6 @@ module ActiveModel alias attributes= assign_attributes private - def _assign_attributes(attributes) attributes.each do |k, v| _assign_attribute(k, v) diff --git a/activemodel/lib/active_model/attribute_set.rb b/activemodel/lib/active_model/attribute_set.rb index 4679b33852..2f5437ceda 100644 --- a/activemodel/lib/active_model/attribute_set.rb +++ b/activemodel/lib/active_model/attribute_set.rb @@ -94,11 +94,9 @@ module ActiveModel end protected - attr_reader :attributes private - def initialized_attributes attributes.select { |_, attr| attr.initialized? } end diff --git a/activemodel/lib/active_model/attributes.rb b/activemodel/lib/active_model/attributes.rb index d176ea88d0..c586f52b78 100644 --- a/activemodel/lib/active_model/attributes.rb +++ b/activemodel/lib/active_model/attributes.rb @@ -42,7 +42,6 @@ module ActiveModel end private - def define_method_attribute=(name) ActiveModel::AttributeMethods::AttrNames.define_attribute_accessor_method( generated_attribute_methods, name, writer: true, @@ -114,7 +113,6 @@ module ActiveModel end private - def write_attribute(attr_name, value) name = attr_name.to_s name = self.class.attribute_aliases[name] || name diff --git a/activemodel/lib/active_model/callbacks.rb b/activemodel/lib/active_model/callbacks.rb index ea2ed7dff7..7a544395cb 100644 --- a/activemodel/lib/active_model/callbacks.rb +++ b/activemodel/lib/active_model/callbacks.rb @@ -126,7 +126,6 @@ module ActiveModel end private - def _define_before_model_callback(klass, callback) klass.define_singleton_method("before_#{callback}") do |*args, **options, &block| options.assert_valid_keys(:if, :unless, :prepend) diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb index 35a587658c..aaefe00c83 100644 --- a/activemodel/lib/active_model/dirty.rb +++ b/activemodel/lib/active_model/dirty.rb @@ -136,7 +136,7 @@ module ActiveModel @mutations_from_database = nil end - # Clears dirty data and moves +changes+ to +previously_changed+ and + # Clears dirty data and moves +changes+ to +previous_changes+ and # +mutations_from_database+ to +mutations_before_last_save+ respectively. def changes_applied unless defined?(@attributes) diff --git a/activemodel/lib/active_model/error.rb b/activemodel/lib/active_model/error.rb index 5a1298e27f..6deab3578d 100644 --- a/activemodel/lib/active_model/error.rb +++ b/activemodel/lib/active_model/error.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "active_support/core_ext/class/attribute" + module ActiveModel # == Active \Model \Error # @@ -8,6 +10,89 @@ module ActiveModel CALLBACKS_OPTIONS = [:if, :unless, :on, :allow_nil, :allow_blank, :strict] MESSAGE_OPTIONS = [:message] + class_attribute :i18n_customize_full_message, default: false + + def self.full_message(attribute, message, base_class) # :nodoc: + return message if attribute == :base + attribute = attribute.to_s + + if i18n_customize_full_message && base_class.respond_to?(:i18n_scope) + attribute = attribute.remove(/\[\d\]/) + parts = attribute.split(".") + attribute_name = parts.pop + namespace = parts.join("/") unless parts.empty? + attributes_scope = "#{base_class.i18n_scope}.errors.models" + + if namespace + defaults = base_class.lookup_ancestors.map do |klass| + [ + :"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.attributes.#{attribute_name}.format", + :"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.format", + ] + end + else + defaults = base_class.lookup_ancestors.map do |klass| + [ + :"#{attributes_scope}.#{klass.model_name.i18n_key}.attributes.#{attribute_name}.format", + :"#{attributes_scope}.#{klass.model_name.i18n_key}.format", + ] + end + end + + defaults.flatten! + else + defaults = [] + end + + defaults << :"errors.format" + defaults << "%{attribute} %{message}" + + attr_name = attribute.tr(".", "_").humanize + attr_name = base_class.human_attribute_name(attribute, default: attr_name) + + I18n.t(defaults.shift, + default: defaults, + attribute: attr_name, + message: message) + end + + def self.generate_message(attribute, type, base, options) # :nodoc: + type = options.delete(:message) if options[:message].is_a?(Symbol) + value = (attribute != :base ? base.send(:read_attribute_for_validation, attribute) : nil) + + options = { + model: base.model_name.human, + attribute: base.class.human_attribute_name(attribute), + value: value, + object: base + }.merge!(options) + + if base.class.respond_to?(:i18n_scope) + i18n_scope = base.class.i18n_scope.to_s + defaults = base.class.lookup_ancestors.flat_map do |klass| + [ :"#{i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}", + :"#{i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}" ] + end + defaults << :"#{i18n_scope}.errors.messages.#{type}" + + catch(:exception) do + translation = I18n.translate(defaults.first, options.merge(default: defaults.drop(1), throw: true)) + return translation unless translation.nil? + end unless options[:message] + else + defaults = [] + end + + defaults << :"errors.attributes.#{attribute}.#{type}" + defaults << :"errors.messages.#{type}" + + key = defaults.shift + defaults = options.delete(:message) if options[:message] + options[:default] = defaults + + I18n.translate(key, options) + end + def initialize(base, attribute, type = :invalid, **options) @base = base @attribute = attribute @@ -28,7 +113,7 @@ module ActiveModel def message case raw_type when Symbol - base.errors.generate_message(attribute, raw_type, options.except(*CALLBACKS_OPTIONS)) + self.class.generate_message(attribute, raw_type, @base, options.except(*CALLBACKS_OPTIONS)) else raw_type end @@ -39,7 +124,7 @@ module ActiveModel end def full_message - base.errors.full_message(attribute, message) + self.class.full_message(attribute, message, @base.class) end # See if error matches provided +attribute+, +type+ and +options+. @@ -58,9 +143,9 @@ module ActiveModel end def strict_match?(attribute, type, **options) - return false unless match?(attribute, type, **options) + return false unless match?(attribute, type) - full_message == Error.new(@base, attribute, type, **options).full_message + options == @options.except(*CALLBACKS_OPTIONS + MESSAGE_OPTIONS) end def ==(other) @@ -73,9 +158,8 @@ module ActiveModel end protected - def attributes_for_hash - [@base, @attribute, @raw_type, @options] + [@base, @attribute, @raw_type, @options.except(*CALLBACKS_OPTIONS)] end end end diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb index d7bcfacce3..42c004ce31 100644 --- a/activemodel/lib/active_model/errors.rb +++ b/activemodel/lib/active_model/errors.rb @@ -4,7 +4,6 @@ require "active_support/core_ext/array/conversions" require "active_support/core_ext/string/inflections" require "active_support/core_ext/object/deep_dup" require "active_support/core_ext/string/filters" -require "active_support/deprecation" require "active_model/error" require "active_model/nested_error" require "forwardable" @@ -70,11 +69,6 @@ module ActiveModel LEGACY_ATTRIBUTES = [:messages, :details].freeze - class << self - attr_accessor :i18n_customize_full_message # :nodoc: - end - self.i18n_customize_full_message = false - attr_reader :errors alias :objects :errors @@ -199,7 +193,7 @@ module ActiveModel matches.each do |error| @errors.delete(error) end - matches.map(&:message) + matches.map(&:message).presence end # When passed a symbol or a name of a method, returns an array of errors @@ -226,7 +220,7 @@ module ActiveModel # # then yield :name and "must be specified" # end def each(&block) - if block.arity == 1 + if block.arity <= 1 @errors.each(&block) else ActiveSupport::Deprecation.warn(<<~MSG) @@ -309,6 +303,16 @@ module ActiveModel hash end + def to_h + ActiveSupport::Deprecation.warn(<<~EOM) + ActiveModel::Errors#to_h is deprecated and will be removed in Rails 6.2 + Please use `ActiveModel::Errors.to_hash` instead. The values in the hash + returned by `ActiveModel::Errors.to_hash` is an array of error messages. + EOM + + to_hash.transform_values { |values| values.last } + end + def messages DeprecationHandlingMessageHash.new(self) end @@ -468,47 +472,7 @@ module ActiveModel # # person.errors.full_message(:name, 'is invalid') # => "Name is invalid" def full_message(attribute, message) - return message if attribute == :base - attribute = attribute.to_s - - if self.class.i18n_customize_full_message && @base.class.respond_to?(:i18n_scope) - attribute = attribute.remove(/\[\d\]/) - parts = attribute.split(".") - attribute_name = parts.pop - namespace = parts.join("/") unless parts.empty? - attributes_scope = "#{@base.class.i18n_scope}.errors.models" - - if namespace - defaults = @base.class.lookup_ancestors.map do |klass| - [ - :"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.attributes.#{attribute_name}.format", - :"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.format", - ] - end - else - defaults = @base.class.lookup_ancestors.map do |klass| - [ - :"#{attributes_scope}.#{klass.model_name.i18n_key}.attributes.#{attribute_name}.format", - :"#{attributes_scope}.#{klass.model_name.i18n_key}.format", - ] - end - end - - defaults.flatten! - else - defaults = [] - end - - defaults << :"errors.format" - defaults << "%{attribute} %{message}" - - attr_name = attribute.tr(".", "_").humanize - attr_name = @base.class.human_attribute_name(attribute, default: attr_name) - - I18n.t(defaults.shift, - default: defaults, - attribute: attr_name, - message: message) + Error.full_message(attribute, message, @base.class) end # Translates an error message in its default scope @@ -536,40 +500,7 @@ module ActiveModel # * <tt>errors.attributes.title.blank</tt> # * <tt>errors.messages.blank</tt> def generate_message(attribute, type = :invalid, options = {}) - type = options.delete(:message) if options[:message].is_a?(Symbol) - value = (attribute != :base ? @base.send(:read_attribute_for_validation, attribute) : nil) - - options = { - model: @base.model_name.human, - attribute: @base.class.human_attribute_name(attribute), - value: value, - object: @base - }.merge!(options) - - if @base.class.respond_to?(:i18n_scope) - i18n_scope = @base.class.i18n_scope.to_s - defaults = @base.class.lookup_ancestors.flat_map do |klass| - [ :"#{i18n_scope}.errors.models.#{klass.model_name.i18n_key}.attributes.#{attribute}.#{type}", - :"#{i18n_scope}.errors.models.#{klass.model_name.i18n_key}.#{type}" ] - end - defaults << :"#{i18n_scope}.errors.messages.#{type}" - - catch(:exception) do - translation = I18n.translate(defaults.first, options.merge(default: defaults.drop(1), throw: true)) - return translation unless translation.nil? - end unless options[:message] - else - defaults = [] - end - - defaults << :"errors.attributes.#{attribute}.#{type}" - defaults << :"errors.messages.#{type}" - - key = defaults.shift - defaults = options.delete(:message) if options[:message] - options[:default] = defaults - - I18n.translate(key, options) + Error.generate_message(attribute, type, @base, options) end def marshal_load(array) # :nodoc: @@ -594,7 +525,6 @@ module ActiveModel end private - def normalize_arguments(attribute, type, **options) # Evaluate proc first if type.respond_to?(:call) @@ -640,7 +570,6 @@ module ActiveModel end private - def prepare_content content = @errors.to_hash content.each do |attribute, value| diff --git a/activemodel/lib/active_model/naming.rb b/activemodel/lib/active_model/naming.rb index bf23fa3c05..6a02d5dbf7 100644 --- a/activemodel/lib/active_model/naming.rb +++ b/activemodel/lib/active_model/naming.rb @@ -207,7 +207,6 @@ module ActiveModel end private - def _singularize(string) ActiveSupport::Inflector.underscore(string).tr("/", "_") end diff --git a/activemodel/lib/active_model/railtie.rb b/activemodel/lib/active_model/railtie.rb index eb7901c7e9..65e20b9791 100644 --- a/activemodel/lib/active_model/railtie.rb +++ b/activemodel/lib/active_model/railtie.rb @@ -14,7 +14,7 @@ module ActiveModel end initializer "active_model.i18n_customize_full_message" do - ActiveModel::Errors.i18n_customize_full_message = config.active_model.delete(:i18n_customize_full_message) || false + ActiveModel::Error.i18n_customize_full_message = config.active_model.delete(:i18n_customize_full_message) || false end end end diff --git a/activemodel/lib/active_model/serialization.rb b/activemodel/lib/active_model/serialization.rb index c4b7b32291..168dfa0dd2 100644 --- a/activemodel/lib/active_model/serialization.rb +++ b/activemodel/lib/active_model/serialization.rb @@ -150,7 +150,6 @@ module ActiveModel end private - # Hook method defining how an attribute value should be retrieved for # serialization. By default this is assumed to be an instance named after # the attribute. Override this method in subclasses should you need to diff --git a/activemodel/lib/active_model/type/big_integer.rb b/activemodel/lib/active_model/type/big_integer.rb index 89e43bcc5f..b2c3ee50aa 100644 --- a/activemodel/lib/active_model/type/big_integer.rb +++ b/activemodel/lib/active_model/type/big_integer.rb @@ -6,7 +6,6 @@ module ActiveModel module Type class BigInteger < Integer # :nodoc: private - def max_value ::Float::INFINITY end diff --git a/activemodel/lib/active_model/type/boolean.rb b/activemodel/lib/active_model/type/boolean.rb index e64d2c793c..1214e9319b 100644 --- a/activemodel/lib/active_model/type/boolean.rb +++ b/activemodel/lib/active_model/type/boolean.rb @@ -34,7 +34,6 @@ module ActiveModel end private - def cast_value(value) if value == "" nil diff --git a/activemodel/lib/active_model/type/date.rb b/activemodel/lib/active_model/type/date.rb index c5fe926039..0e96d2c8a4 100644 --- a/activemodel/lib/active_model/type/date.rb +++ b/activemodel/lib/active_model/type/date.rb @@ -15,7 +15,6 @@ module ActiveModel end private - def cast_value(value) if value.is_a?(::String) return if value.empty? diff --git a/activemodel/lib/active_model/type/date_time.rb b/activemodel/lib/active_model/type/date_time.rb index 133410e821..ba705be9b2 100644 --- a/activemodel/lib/active_model/type/date_time.rb +++ b/activemodel/lib/active_model/type/date_time.rb @@ -14,7 +14,6 @@ module ActiveModel end private - def cast_value(value) return apply_seconds_precision(value) unless value.is_a?(::String) return if value.empty? diff --git a/activemodel/lib/active_model/type/decimal.rb b/activemodel/lib/active_model/type/decimal.rb index e8ee18c00e..6aa51ff2ac 100644 --- a/activemodel/lib/active_model/type/decimal.rb +++ b/activemodel/lib/active_model/type/decimal.rb @@ -17,7 +17,6 @@ module ActiveModel end private - def cast_value(value) casted_value = \ case value diff --git a/activemodel/lib/active_model/type/float.rb b/activemodel/lib/active_model/type/float.rb index ea1987df7c..36c7a5103c 100644 --- a/activemodel/lib/active_model/type/float.rb +++ b/activemodel/lib/active_model/type/float.rb @@ -19,7 +19,6 @@ module ActiveModel end private - def cast_value(value) case value when ::Float then value diff --git a/activemodel/lib/active_model/type/helpers/numeric.rb b/activemodel/lib/active_model/type/helpers/numeric.rb index 1d8171e25b..074316b559 100644 --- a/activemodel/lib/active_model/type/helpers/numeric.rb +++ b/activemodel/lib/active_model/type/helpers/numeric.rb @@ -24,7 +24,6 @@ module ActiveModel end private - def number_to_non_number?(old_value, new_value_before_type_cast) old_value != nil && non_numeric_string?(new_value_before_type_cast.to_s) end diff --git a/activemodel/lib/active_model/type/helpers/time_value.rb b/activemodel/lib/active_model/type/helpers/time_value.rb index dab196d653..075e906034 100644 --- a/activemodel/lib/active_model/type/helpers/time_value.rb +++ b/activemodel/lib/active_model/type/helpers/time_value.rb @@ -11,10 +11,10 @@ module ActiveModel value = apply_seconds_precision(value) if value.acts_like?(:time) - zone_conversion_method = is_utc? ? :getutc : :getlocal - - if value.respond_to?(zone_conversion_method) - value = value.send(zone_conversion_method) + if is_utc? + value = value.getutc if value.respond_to?(:getutc) && !value.utc? + else + value = value.getlocal if value.respond_to?(:getlocal) end end @@ -44,7 +44,6 @@ module ActiveModel end private - def new_time(year, mon, mday, hour, min, sec, microsec, offset = nil) # Treat 0000-00-00 00:00:00 as nil. return if year.nil? || (year == 0 && mon == 0 && mday == 0) diff --git a/activemodel/lib/active_model/type/immutable_string.rb b/activemodel/lib/active_model/type/immutable_string.rb index 826bd7038f..18e12c54d1 100644 --- a/activemodel/lib/active_model/type/immutable_string.rb +++ b/activemodel/lib/active_model/type/immutable_string.rb @@ -17,7 +17,6 @@ module ActiveModel end private - def cast_value(value) result = \ case value diff --git a/activemodel/lib/active_model/type/string.rb b/activemodel/lib/active_model/type/string.rb index a9c9bfadb6..0d9f4a63b4 100644 --- a/activemodel/lib/active_model/type/string.rb +++ b/activemodel/lib/active_model/type/string.rb @@ -12,7 +12,6 @@ module ActiveModel end private - def cast_value(value) case value when ::String then ::String.new(value) diff --git a/activemodel/lib/active_model/type/time.rb b/activemodel/lib/active_model/type/time.rb index 61847a4ce7..f230bd4257 100644 --- a/activemodel/lib/active_model/type/time.rb +++ b/activemodel/lib/active_model/type/time.rb @@ -29,7 +29,6 @@ module ActiveModel end private - def cast_value(value) return apply_seconds_precision(value) unless value.is_a?(::String) return if value.empty? diff --git a/activemodel/lib/active_model/type/value.rb b/activemodel/lib/active_model/type/value.rb index b6914dd63c..788ded3e96 100644 --- a/activemodel/lib/active_model/type/value.rb +++ b/activemodel/lib/active_model/type/value.rb @@ -110,11 +110,10 @@ module ActiveModel [self.class, precision, scale, limit].hash end - def assert_valid_value(*) + def assert_valid_value(_) end private - # Convenience method for types which do not need separate type casting # behavior for user and database inputs. Called by Value#cast for # values except +nil+. diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb index f18f9a601a..4a6b464131 100644 --- a/activemodel/lib/active_model/validations.rb +++ b/activemodel/lib/active_model/validations.rb @@ -402,7 +402,6 @@ module ActiveModel alias :read_attribute_for_validation :send private - def run_validations! _run_validate_callbacks errors.empty? diff --git a/activemodel/lib/active_model/validations/acceptance.rb b/activemodel/lib/active_model/validations/acceptance.rb index 6fd54270f2..1b96575a10 100644 --- a/activemodel/lib/active_model/validations/acceptance.rb +++ b/activemodel/lib/active_model/validations/acceptance.rb @@ -15,7 +15,6 @@ module ActiveModel end private - def setup!(klass) klass.include(LazilyDefineAttributes.new(AttributeDefinition.new(attributes))) end diff --git a/activemodel/lib/active_model/validations/callbacks.rb b/activemodel/lib/active_model/validations/callbacks.rb index 887d31ae2a..7178ba99e9 100644 --- a/activemodel/lib/active_model/validations/callbacks.rb +++ b/activemodel/lib/active_model/validations/callbacks.rb @@ -112,7 +112,6 @@ module ActiveModel end private - # Overwrite run validations to include callbacks. def run_validations! _run_validation_callbacks { super } diff --git a/activemodel/lib/active_model/validations/clusivity.rb b/activemodel/lib/active_model/validations/clusivity.rb index bafb8e2106..fb9f48301c 100644 --- a/activemodel/lib/active_model/validations/clusivity.rb +++ b/activemodel/lib/active_model/validations/clusivity.rb @@ -15,7 +15,6 @@ module ActiveModel end private - def include?(record, value) members = if delimiter.respond_to?(:call) delimiter.call(record) diff --git a/activemodel/lib/active_model/validations/format.rb b/activemodel/lib/active_model/validations/format.rb index 7c3f091473..bea57415b0 100644 --- a/activemodel/lib/active_model/validations/format.rb +++ b/activemodel/lib/active_model/validations/format.rb @@ -23,7 +23,6 @@ module ActiveModel end private - def option_call(record, name) option = options[name] option.respond_to?(:call) ? option.call(record) : option diff --git a/activemodel/lib/active_model/validations/numericality.rb b/activemodel/lib/active_model/validations/numericality.rb index 51e224d5cd..e7be668e9d 100644 --- a/activemodel/lib/active_model/validations/numericality.rb +++ b/activemodel/lib/active_model/validations/numericality.rb @@ -79,7 +79,6 @@ module ActiveModel end private - def is_number?(raw_value) !parse_as_number(raw_value).nil? rescue ArgumentError, TypeError diff --git a/activemodel/lib/active_model/validations/validates.rb b/activemodel/lib/active_model/validations/validates.rb index 21c4ce0dfe..97612d474d 100644 --- a/activemodel/lib/active_model/validations/validates.rb +++ b/activemodel/lib/active_model/validations/validates.rb @@ -150,7 +150,6 @@ module ActiveModel end private - # When creating custom validators, it might be useful to be able to specify # additional default keys. This can be done by overwriting this method. def _validates_default_keys diff --git a/activemodel/lib/active_model/validator.rb b/activemodel/lib/active_model/validator.rb index 94d53b8dd1..3ba6acea15 100644 --- a/activemodel/lib/active_model/validator.rb +++ b/activemodel/lib/active_model/validator.rb @@ -175,7 +175,6 @@ module ActiveModel end private - def validate_each(record, attribute, value) @block.call(record, attribute, value) end diff --git a/activemodel/test/cases/attribute_methods_test.rb b/activemodel/test/cases/attribute_methods_test.rb index 4e228032c3..e3b3b15f25 100644 --- a/activemodel/test/cases/attribute_methods_test.rb +++ b/activemodel/test/cases/attribute_methods_test.rb @@ -40,7 +40,6 @@ private end protected - def protected_method "O_o O_o" end diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb index baaf404f2e..a6cd1da717 100644 --- a/activemodel/test/cases/errors_test.rb +++ b/activemodel/test/cases/errors_test.rb @@ -44,6 +44,14 @@ class ErrorsTest < ActiveModel::TestCase assert_includes errors, "foo", "errors should include 'foo' as :foo" end + def test_each_when_arity_is_negative + errors = ActiveModel::Errors.new(Person.new) + errors.add(:name, :blank) + errors.add(:gender, :blank) + + assert_equal([:name, :gender], errors.map(&:attribute)) + end + def test_any? errors = ActiveModel::Errors.new(Person.new) errors.add(:name) @@ -274,6 +282,28 @@ class ErrorsTest < ActiveModel::TestCase assert_equal [msg], person.errors[:name] end + test "added? when attribute was added through a collection" do + person = Person.new + person.errors.add(:"family_members.name", :too_long, count: 25) + assert person.errors.added?(:"family_members.name", :too_long, count: 25) + assert_not person.errors.added?(:"family_members.name", :too_long) + assert_not person.errors.added?(:"family_members.name", :too_long, name: "hello") + end + + test "added? ignores callback option" do + person = Person.new + + person.errors.add(:name, :too_long, if: -> { true }) + assert person.errors.added?(:name, :too_long) + end + + test "added? ignores message option" do + person = Person.new + + person.errors.add(:name, :too_long, message: proc { "foo" }) + assert person.errors.added?(:name, :too_long) + end + test "added? detects indifferent if a specific error was added to the object" do person = Person.new person.errors.add(:name, "cannot be blank") @@ -444,6 +474,17 @@ class ErrorsTest < ActiveModel::TestCase assert_equal ["name cannot be blank", "name cannot be nil"], person.errors.to_a end + test "to_h is deprecated" do + person = Person.new + person.errors.add(:name, "cannot be blank") + person.errors.add(:name, "too long") + + expected_deprecation = "ActiveModel::Errors#to_h is deprecated" + assert_deprecated(expected_deprecation) do + assert_equal({ name: "too long" }, person.errors.to_h) + end + end + test "to_hash returns the error messages hash" do person = Person.new person.errors.add(:name, "cannot be blank") @@ -460,6 +501,27 @@ class ErrorsTest < ActiveModel::TestCase assert_nil person.errors.as_json.default_proc end + test "full_messages doesn't require the base object to respond to `:errors" do + model = Class.new do + def initialize + @errors = ActiveModel::Errors.new(self) + @errors.add(:name, "bar") + end + + def self.human_attribute_name(attr, options = {}) + "foo" + end + + def call + error_wrapper = Struct.new(:model_errors) + + error_wrapper.new(@errors) + end + end + + assert_equal(["foo bar"], model.new.call.model_errors.full_messages) + end + test "full_messages creates a list of error messages with the attribute name included" do person = Person.new person.errors.add(:name, "cannot be blank") @@ -573,6 +635,12 @@ class ErrorsTest < ActiveModel::TestCase assert_not_equal errors_dup.details, errors.details end + test "delete returns nil when no errors were deleted" do + errors = ActiveModel::Errors.new(Person.new) + + assert_nil(errors.delete(:name)) + end + test "delete removes details on given attribute" do errors = ActiveModel::Errors.new(Person.new) errors.add(:name, :invalid) diff --git a/activemodel/test/cases/railtie_test.rb b/activemodel/test/cases/railtie_test.rb index 95ee7cace3..f5ff1a3fd7 100644 --- a/activemodel/test/cases/railtie_test.rb +++ b/activemodel/test/cases/railtie_test.rb @@ -35,20 +35,20 @@ class RailtieTest < ActiveModel::TestCase test "i18n customize full message defaults to false" do @app.initialize! - assert_equal false, ActiveModel::Errors.i18n_customize_full_message + assert_equal false, ActiveModel::Error.i18n_customize_full_message end test "i18n customize full message can be disabled" do @app.config.active_model.i18n_customize_full_message = false @app.initialize! - assert_equal false, ActiveModel::Errors.i18n_customize_full_message + assert_equal false, ActiveModel::Error.i18n_customize_full_message end test "i18n customize full message can be enabled" do @app.config.active_model.i18n_customize_full_message = true @app.initialize! - assert_equal true, ActiveModel::Errors.i18n_customize_full_message + assert_equal true, ActiveModel::Error.i18n_customize_full_message end end diff --git a/activemodel/test/cases/type/date_time_test.rb b/activemodel/test/cases/type/date_time_test.rb index 74b47d1b4d..4a63eee0cf 100644 --- a/activemodel/test/cases/type/date_time_test.rb +++ b/activemodel/test/cases/type/date_time_test.rb @@ -37,7 +37,6 @@ module ActiveModel end private - def with_timezone_config(default:) old_zone_default = ::Time.zone_default ::Time.zone_default = ::Time.find_zone(default) diff --git a/activemodel/test/cases/validations/acceptance_validation_test.rb b/activemodel/test/cases/validations/acceptance_validation_test.rb index 72baf6e7a7..6bd3d292f8 100644 --- a/activemodel/test/cases/validations/acceptance_validation_test.rb +++ b/activemodel/test/cases/validations/acceptance_validation_test.rb @@ -92,7 +92,6 @@ class AcceptanceValidationTest < ActiveModel::TestCase end private - # Acceptance validator includes anonymous module into class, which cannot # be cleared, so to avoid multiple inclusions we use a named subclass which # we can remove in teardown. diff --git a/activemodel/test/cases/validations/i18n_validation_test.rb b/activemodel/test/cases/validations/i18n_validation_test.rb index b7ee50832c..c81649f493 100644 --- a/activemodel/test/cases/validations/i18n_validation_test.rb +++ b/activemodel/test/cases/validations/i18n_validation_test.rb @@ -13,8 +13,8 @@ class I18nValidationTest < ActiveModel::TestCase I18n.backend = I18n::Backend::Simple.new I18n.backend.store_translations("en", errors: { messages: { custom: nil } }) - @original_i18n_customize_full_message = ActiveModel::Errors.i18n_customize_full_message - ActiveModel::Errors.i18n_customize_full_message = true + @original_i18n_customize_full_message = ActiveModel::Error.i18n_customize_full_message + ActiveModel::Error.i18n_customize_full_message = true end def teardown @@ -24,7 +24,7 @@ class I18nValidationTest < ActiveModel::TestCase I18n.load_path.replace @old_load_path I18n.backend = @old_backend I18n.backend.reload! - ActiveModel::Errors.i18n_customize_full_message = @original_i18n_customize_full_message + ActiveModel::Error.i18n_customize_full_message = @original_i18n_customize_full_message end def test_full_message_encoding @@ -49,7 +49,7 @@ class I18nValidationTest < ActiveModel::TestCase end def test_errors_full_messages_doesnt_use_attribute_format_without_config - ActiveModel::Errors.i18n_customize_full_message = false + ActiveModel::Error.i18n_customize_full_message = false I18n.backend.store_translations("en", activemodel: { errors: { models: { person: { attributes: { name: { format: "%{message}" } } } } } }) @@ -59,8 +59,21 @@ class I18nValidationTest < ActiveModel::TestCase assert_equal "Name test cannot be blank", person.errors.full_message(:name_test, "cannot be blank") end + def test_errors_full_messages_on_nested_error_uses_attribute_format + ActiveModel::Error.i18n_customize_full_message = true + I18n.backend.store_translations("en", activemodel: { + errors: { models: { person: { attributes: { gender: "Gender" } } } }, + attributes: { "person/contacts": { gender: "Gender" } } + }) + + person = person_class.new + error = ActiveModel::Error.new(person, :gender, "can't be blank") + person.errors.import(error, attribute: "person[0].contacts.gender") + assert_equal ["Gender can't be blank"], person.errors.full_messages + end + def test_errors_full_messages_uses_attribute_format - ActiveModel::Errors.i18n_customize_full_message = true + ActiveModel::Error.i18n_customize_full_message = true I18n.backend.store_translations("en", activemodel: { errors: { models: { person: { attributes: { name: { format: "%{message}" } } } } } }) @@ -71,7 +84,7 @@ class I18nValidationTest < ActiveModel::TestCase end def test_errors_full_messages_uses_model_format - ActiveModel::Errors.i18n_customize_full_message = true + ActiveModel::Error.i18n_customize_full_message = true I18n.backend.store_translations("en", activemodel: { errors: { models: { person: { format: "%{message}" } } } }) @@ -82,7 +95,7 @@ class I18nValidationTest < ActiveModel::TestCase end def test_errors_full_messages_uses_deeply_nested_model_attributes_format - ActiveModel::Errors.i18n_customize_full_message = true + ActiveModel::Error.i18n_customize_full_message = true I18n.backend.store_translations("en", activemodel: { errors: { models: { 'person/contacts/addresses': { attributes: { street: { format: "%{message}" } } } } } }) @@ -93,7 +106,7 @@ class I18nValidationTest < ActiveModel::TestCase end def test_errors_full_messages_uses_deeply_nested_model_model_format - ActiveModel::Errors.i18n_customize_full_message = true + ActiveModel::Error.i18n_customize_full_message = true I18n.backend.store_translations("en", activemodel: { errors: { models: { 'person/contacts/addresses': { format: "%{message}" } } } }) @@ -104,7 +117,7 @@ class I18nValidationTest < ActiveModel::TestCase end def test_errors_full_messages_with_indexed_deeply_nested_attributes_and_attributes_format - ActiveModel::Errors.i18n_customize_full_message = true + ActiveModel::Error.i18n_customize_full_message = true I18n.backend.store_translations("en", activemodel: { errors: { models: { 'person/contacts/addresses': { attributes: { street: { format: "%{message}" } } } } } }) @@ -115,7 +128,7 @@ class I18nValidationTest < ActiveModel::TestCase end def test_errors_full_messages_with_indexed_deeply_nested_attributes_and_model_format - ActiveModel::Errors.i18n_customize_full_message = true + ActiveModel::Error.i18n_customize_full_message = true I18n.backend.store_translations("en", activemodel: { errors: { models: { 'person/contacts/addresses': { format: "%{message}" } } } }) @@ -126,7 +139,7 @@ class I18nValidationTest < ActiveModel::TestCase end def test_errors_full_messages_with_indexed_deeply_nested_attributes_and_i18n_attribute_name - ActiveModel::Errors.i18n_customize_full_message = true + ActiveModel::Error.i18n_customize_full_message = true I18n.backend.store_translations("en", activemodel: { attributes: { 'person/contacts/addresses': { country: "Country" } } @@ -138,7 +151,7 @@ class I18nValidationTest < ActiveModel::TestCase end def test_errors_full_messages_with_indexed_deeply_nested_attributes_without_i18n_config - ActiveModel::Errors.i18n_customize_full_message = false + ActiveModel::Error.i18n_customize_full_message = false I18n.backend.store_translations("en", activemodel: { errors: { models: { 'person/contacts/addresses': { attributes: { street: { format: "%{message}" } } } } } }) @@ -149,7 +162,7 @@ class I18nValidationTest < ActiveModel::TestCase end def test_errors_full_messages_with_i18n_attribute_name_without_i18n_config - ActiveModel::Errors.i18n_customize_full_message = false + ActiveModel::Error.i18n_customize_full_message = false I18n.backend.store_translations("en", activemodel: { attributes: { 'person/contacts[0]/addresses[0]': { country: "Country" } } @@ -178,8 +191,8 @@ class I18nValidationTest < ActiveModel::TestCase test "validates_confirmation_of on generated message #{name}" do person_class.validates_confirmation_of :title, validation_options @person.title_confirmation = "foo" - call = [:title_confirmation, :confirmation, generate_message_options.merge(attribute: "Title")] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title_confirmation, :confirmation, @person, generate_message_options.merge(attribute: "Title")] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -189,8 +202,8 @@ class I18nValidationTest < ActiveModel::TestCase COMMON_CASES.each do |name, validation_options, generate_message_options| test "validates_acceptance_of on generated message #{name}" do person_class.validates_acceptance_of :title, validation_options.merge(allow_nil: false) - call = [:title, :accepted, generate_message_options] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :accepted, @person, generate_message_options] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -200,8 +213,8 @@ class I18nValidationTest < ActiveModel::TestCase COMMON_CASES.each do |name, validation_options, generate_message_options| test "validates_presence_of on generated message #{name}" do person_class.validates_presence_of :title, validation_options - call = [:title, :blank, generate_message_options] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :blank, @person, generate_message_options] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -211,8 +224,8 @@ class I18nValidationTest < ActiveModel::TestCase COMMON_CASES.each do |name, validation_options, generate_message_options| test "validates_length_of for :within on generated message when too short #{name}" do person_class.validates_length_of :title, validation_options.merge(within: 3..5) - call = [:title, :too_short, generate_message_options.merge(count: 3)] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :too_short, @person, generate_message_options.merge(count: 3)] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -223,8 +236,8 @@ class I18nValidationTest < ActiveModel::TestCase test "validates_length_of for :too_long generated message #{name}" do person_class.validates_length_of :title, validation_options.merge(within: 3..5) @person.title = "this title is too long" - call = [:title, :too_long, generate_message_options.merge(count: 5)] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :too_long, @person, generate_message_options.merge(count: 5)] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -234,8 +247,8 @@ class I18nValidationTest < ActiveModel::TestCase COMMON_CASES.each do |name, validation_options, generate_message_options| test "validates_length_of for :is on generated message #{name}" do person_class.validates_length_of :title, validation_options.merge(is: 5) - call = [:title, :wrong_length, generate_message_options.merge(count: 5)] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :wrong_length, @person, generate_message_options.merge(count: 5)] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -246,8 +259,8 @@ class I18nValidationTest < ActiveModel::TestCase test "validates_format_of on generated message #{name}" do person_class.validates_format_of :title, validation_options.merge(with: /\A[1-9][0-9]*\z/) @person.title = "72x" - call = [:title, :invalid, generate_message_options.merge(value: "72x")] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :invalid, @person, generate_message_options.merge(value: "72x")] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -258,8 +271,8 @@ class I18nValidationTest < ActiveModel::TestCase test "validates_inclusion_of on generated message #{name}" do person_class.validates_inclusion_of :title, validation_options.merge(in: %w(a b c)) @person.title = "z" - call = [:title, :inclusion, generate_message_options.merge(value: "z")] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :inclusion, @person, generate_message_options.merge(value: "z")] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -270,8 +283,8 @@ class I18nValidationTest < ActiveModel::TestCase test "validates_inclusion_of using :within on generated message #{name}" do person_class.validates_inclusion_of :title, validation_options.merge(within: %w(a b c)) @person.title = "z" - call = [:title, :inclusion, generate_message_options.merge(value: "z")] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :inclusion, @person, generate_message_options.merge(value: "z")] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -282,8 +295,8 @@ class I18nValidationTest < ActiveModel::TestCase test "validates_exclusion_of generated message #{name}" do person_class.validates_exclusion_of :title, validation_options.merge(in: %w(a b c)) @person.title = "a" - call = [:title, :exclusion, generate_message_options.merge(value: "a")] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :exclusion, @person, generate_message_options.merge(value: "a")] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -294,8 +307,8 @@ class I18nValidationTest < ActiveModel::TestCase test "validates_exclusion_of using :within generated message #{name}" do person_class.validates_exclusion_of :title, validation_options.merge(within: %w(a b c)) @person.title = "a" - call = [:title, :exclusion, generate_message_options.merge(value: "a")] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :exclusion, @person, generate_message_options.merge(value: "a")] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -306,8 +319,8 @@ class I18nValidationTest < ActiveModel::TestCase test "validates_numericality_of generated message #{name}" do person_class.validates_numericality_of :title, validation_options @person.title = "a" - call = [:title, :not_a_number, generate_message_options.merge(value: "a")] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :not_a_number, @person, generate_message_options.merge(value: "a")] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -318,8 +331,8 @@ class I18nValidationTest < ActiveModel::TestCase test "validates_numericality_of for :only_integer on generated message #{name}" do person_class.validates_numericality_of :title, validation_options.merge(only_integer: true) @person.title = "0.0" - call = [:title, :not_an_integer, generate_message_options.merge(value: "0.0")] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :not_an_integer, @person, generate_message_options.merge(value: "0.0")] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -330,8 +343,8 @@ class I18nValidationTest < ActiveModel::TestCase test "validates_numericality_of for :odd on generated message #{name}" do person_class.validates_numericality_of :title, validation_options.merge(only_integer: true, odd: true) @person.title = 0 - call = [:title, :odd, generate_message_options.merge(value: 0)] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :odd, @person, generate_message_options.merge(value: 0)] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end @@ -342,8 +355,8 @@ class I18nValidationTest < ActiveModel::TestCase test "validates_numericality_of for :less_than on generated message #{name}" do person_class.validates_numericality_of :title, validation_options.merge(only_integer: true, less_than: 0) @person.title = 1 - call = [:title, :less_than, generate_message_options.merge(value: 1, count: 0)] - assert_called_with(@person.errors, :generate_message, call) do + call = [:title, :less_than, @person, generate_message_options.merge(value: 1, count: 0)] + assert_called_with(ActiveModel::Error, :generate_message, call) do @person.valid? @person.errors.messages end diff --git a/activemodel/test/cases/validations/numericality_validation_test.rb b/activemodel/test/cases/validations/numericality_validation_test.rb index 16c44762cb..191af033df 100644 --- a/activemodel/test/cases/validations/numericality_validation_test.rb +++ b/activemodel/test/cases/validations/numericality_validation_test.rb @@ -310,7 +310,6 @@ class NumericalityValidationTest < ActiveModel::TestCase end private - def invalid!(values, error = nil) with_each_topic_approved_value(values) do |topic, value| assert topic.invalid?, "#{value.inspect} not rejected as a number" diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 09fdc66788..727ddd6bb7 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,35 @@ +* Make currency symbols optional for money column type in PostgreSQL + + *Joel Schneider* + +* Add support for beginless ranges, introduced in Ruby 2.7. + + *Josh Goodall* + +* Add database_exists? method to connection adapters to check if a database exists. + + *Guilherme Mansur* + +* Loading the schema for a model that has no `table_name` raises a `TableNotSpecified` error. + + *Guilherme Mansur*, *Eugene Kenny* + +* PostgreSQL: Fix GROUP BY with ORDER BY virtual count attribute. + + Fixes #36022. + + *Ryuta Kamizono* + +* Make ActiveRecord `ConnectionPool.connections` method thread-safe. + + Fixes #36465. + + *Jeff Doering* + +* Add support for multiple databases to `rails db:abort_if_pending_migrations`. + + *Mark Lee* + * Fix sqlite3 collation parsing when using decimal columns. *Martin R. Schuster* diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb index 3250e29b82..aa08124158 100644 --- a/activerecord/lib/active_record/aggregations.rb +++ b/activerecord/lib/active_record/aggregations.rb @@ -14,7 +14,6 @@ module ActiveRecord end private - def clear_aggregation_cache @aggregation_cache.clear if persisted? end diff --git a/activerecord/lib/active_record/association_relation.rb b/activerecord/lib/active_record/association_relation.rb index 4c538ef2bd..de9892e48d 100644 --- a/activerecord/lib/active_record/association_relation.rb +++ b/activerecord/lib/active_record/association_relation.rb @@ -29,7 +29,6 @@ module ActiveRecord end private - def exec_queries super do |record| @association.set_inverse_instance_from_queries(record) diff --git a/activerecord/lib/active_record/associations/alias_tracker.rb b/activerecord/lib/active_record/associations/alias_tracker.rb index 272eede824..ac90ba0137 100644 --- a/activerecord/lib/active_record/associations/alias_tracker.rb +++ b/activerecord/lib/active_record/associations/alias_tracker.rb @@ -72,7 +72,6 @@ module ActiveRecord attr_reader :aliases private - def truncate(name) name.slice(0, @connection.table_alias_length - 2) end diff --git a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb index 0140aa15c8..6ad4c75fb5 100644 --- a/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb +++ b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb @@ -46,7 +46,6 @@ module ActiveRecord::Associations::Builder # :nodoc: end private - def self.suppress_composite_primary_key(pk) pk unless pk.is_a?(Array) end @@ -73,7 +72,6 @@ module ActiveRecord::Associations::Builder # :nodoc: end private - def middle_options(join_model) middle_options = {} middle_options[:class_name] = "#{lhs_model.name}::#{join_model.name}" diff --git a/activerecord/lib/active_record/associations/collection_proxy.rb b/activerecord/lib/active_record/associations/collection_proxy.rb index 797d647900..0db0ad8595 100644 --- a/activerecord/lib/active_record/associations/collection_proxy.rb +++ b/activerecord/lib/active_record/associations/collection_proxy.rb @@ -1101,7 +1101,6 @@ module ActiveRecord delegate(*delegate_methods, to: :scope) private - def find_nth_with_limit(index, limit) load_target if find_from_target? super diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index 5972846940..dd2ed55279 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -37,7 +37,6 @@ module ActiveRecord end private - # Returns the number of records in this collection. # # If the association has a counter cache it gets that value. Otherwise diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb index 6b57e5093a..d4e8b364e1 100644 --- a/activerecord/lib/active_record/associations/preloader.rb +++ b/activerecord/lib/active_record/associations/preloader.rb @@ -95,7 +95,6 @@ module ActiveRecord end private - # Loads all the given data into +records+ for the +association+. def preloaders_on(association, records, scope, polymorphic_parent = false) case association diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index 342d9e7a5a..4c7b0e6f07 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -27,7 +27,9 @@ module ActiveRecord end def records_by_owner - @records_by_owner ||= preloaded_records.each_with_object({}) do |record, result| + # owners can be duplicated when a relation has a collection association join + # #compare_by_identity makes such owners different hash keys + @records_by_owner ||= preloaded_records.each_with_object({}.compare_by_identity) do |record, result| owners_by_key[convert_key(record[association_key_name])].each do |owner| (result[owner] ||= []) << record end diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb index 929045f29b..acb8ba7e5a 100644 --- a/activerecord/lib/active_record/attribute_assignment.rb +++ b/activerecord/lib/active_record/attribute_assignment.rb @@ -7,7 +7,6 @@ module ActiveRecord include ActiveModel::AttributeAssignment private - def _assign_attributes(attributes) multi_parameter_attributes = {} nested_parameter_attributes = {} diff --git a/activerecord/lib/active_record/attribute_decorators.rb b/activerecord/lib/active_record/attribute_decorators.rb index 98b7805c0a..0b66043d2a 100644 --- a/activerecord/lib/active_record/attribute_decorators.rb +++ b/activerecord/lib/active_record/attribute_decorators.rb @@ -46,7 +46,6 @@ module ActiveRecord end private - def load_schema! super attribute_types.each do |name, type| @@ -75,7 +74,6 @@ module ActiveRecord end private - def decorators_for(name, type) matching(name, type).map(&:last) end diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index fd32eaaf3a..21f72bb6c7 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -159,59 +159,6 @@ module ActiveRecord end end - # Regexp for column names (with or without a table name prefix). Matches - # the following: - # "#{table_name}.#{column_name}" - # "#{column_name}" - COLUMN_NAME = /\A(?:\w+\.)?\w+\z/i - - # Regexp for column names with order (with or without a table name - # prefix, with or without various order modifiers). Matches the following: - # "#{table_name}.#{column_name}" - # "#{table_name}.#{column_name} #{direction}" - # "#{table_name}.#{column_name} #{direction} NULLS FIRST" - # "#{table_name}.#{column_name} NULLS LAST" - # "#{column_name}" - # "#{column_name} #{direction}" - # "#{column_name} #{direction} NULLS FIRST" - # "#{column_name} NULLS LAST" - COLUMN_NAME_WITH_ORDER = / - \A - (?:\w+\.)? - \w+ - (?:\s+asc|\s+desc)? - (?:\s+nulls\s+(?:first|last))? - \z - /ix - - def disallow_raw_sql!(args, permit: COLUMN_NAME) # :nodoc: - unexpected = nil - args.each do |arg| - next if arg.is_a?(Symbol) || Arel.arel_node?(arg) || - arg.to_s.split(/\s*,\s*/).all? { |part| permit.match?(part) } - (unexpected ||= []) << arg - end - - return unless unexpected - - if allow_unsafe_raw_sql == :deprecated - ActiveSupport::Deprecation.warn( - "Dangerous query method (method whose arguments are used as raw " \ - "SQL) called with non-attribute argument(s): " \ - "#{unexpected.map(&:inspect).join(", ")}. Non-attribute " \ - "arguments will be disallowed in Rails 6.1. This method should " \ - "not be called with user-provided values, such as request " \ - "parameters or model attributes. Known-safe values can be passed " \ - "by wrapping them in Arel.sql()." - ) - else - raise(ActiveRecord::UnknownAttributeReference, - "Query method called with non-attribute argument(s): " + - unexpected.map(&:inspect).join(", ") - ) - end - end - # Returns true if the given attribute exists, otherwise false. # # class Person < ActiveRecord::Base diff --git a/activerecord/lib/active_record/attribute_methods/before_type_cast.rb b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb index 3d917ec9b1..4a7b6c60e5 100644 --- a/activerecord/lib/active_record/attribute_methods/before_type_cast.rb +++ b/activerecord/lib/active_record/attribute_methods/before_type_cast.rb @@ -66,7 +66,6 @@ module ActiveRecord end private - # Dispatch target for <tt>*_before_type_cast</tt> attribute methods. def attribute_before_type_cast(attribute_name) read_attribute_before_type_cast(attribute_name) diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb index b4f5e6e75a..768c5f8c05 100644 --- a/activerecord/lib/active_record/attribute_methods/primary_key.rb +++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb @@ -45,7 +45,6 @@ module ActiveRecord end private - def attribute_method?(attr_name) attr_name == "id" || super end @@ -120,7 +119,6 @@ module ActiveRecord end private - def suppress_composite_primary_key(pk) return pk unless pk.is_a?(Array) diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb index 0562327a9a..0f0e721b24 100644 --- a/activerecord/lib/active_record/attribute_methods/read.rb +++ b/activerecord/lib/active_record/attribute_methods/read.rb @@ -7,7 +7,6 @@ module ActiveRecord module ClassMethods # :nodoc: private - def define_method_attribute(name) ActiveModel::AttributeMethods::AttrNames.define_attribute_accessor_method( generated_attribute_methods, name diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb index 6e0e90f39c..7bc03b9eed 100644 --- a/activerecord/lib/active_record/attribute_methods/serialization.rb +++ b/activerecord/lib/active_record/attribute_methods/serialization.rb @@ -79,7 +79,6 @@ module ActiveRecord end private - def type_incompatible_with_serialize?(type, class_name) type.is_a?(ActiveRecord::Type::Json) && class_name == ::JSON || type.respond_to?(:type_cast_array, true) && class_name == ::Array diff --git a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb index 294a3dc32c..fb44232dff 100644 --- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb +++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb @@ -25,7 +25,6 @@ module ActiveRecord end private - def convert_time_to_time_zone(value) return if value.nil? @@ -64,7 +63,6 @@ module ActiveRecord module ClassMethods # :nodoc: private - def inherited(subclass) super # We need to apply this decorator here, rather than on module inclusion. The closure diff --git a/activerecord/lib/active_record/attribute_methods/write.rb b/activerecord/lib/active_record/attribute_methods/write.rb index 1c63b553d0..66536a8ddf 100644 --- a/activerecord/lib/active_record/attribute_methods/write.rb +++ b/activerecord/lib/active_record/attribute_methods/write.rb @@ -11,7 +11,6 @@ module ActiveRecord module ClassMethods # :nodoc: private - def define_method_attribute=(name) ActiveModel::AttributeMethods::AttrNames.define_attribute_accessor_method( generated_attribute_methods, name, writer: true, diff --git a/activerecord/lib/active_record/attributes.rb b/activerecord/lib/active_record/attributes.rb index 7cf421c184..c7846dbe7a 100644 --- a/activerecord/lib/active_record/attributes.rb +++ b/activerecord/lib/active_record/attributes.rb @@ -255,7 +255,6 @@ module ActiveRecord end private - NO_DEFAULT_PROVIDED = Object.new # :nodoc: private_constant :NO_DEFAULT_PROVIDED diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index 8d89e7d84a..734ebb45ae 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -147,7 +147,6 @@ module ActiveRecord module ClassMethods # :nodoc: private - def define_non_cyclic_method(name, &block) return if instance_methods(false).include?(name) define_method(name) do |*args| @@ -267,7 +266,6 @@ module ActiveRecord end private - # Returns the record for an association collection that should be validated # or saved. If +autosave+ is +false+ only new records will be returned, # unless the parent is/was a new record itself. @@ -304,7 +302,7 @@ module ActiveRecord def validate_single_association(reflection) association = association_instance_get(reflection.name) record = association && association.reader - association_valid?(reflection, record) if record + association_valid?(reflection, record) if record && record.changed_for_autosave? end # Validate the associated records if <tt>:validate</tt> or @@ -411,7 +409,7 @@ module ActiveRecord saved = record.save(validate: false) end - raise ActiveRecord::Rollback unless saved + raise(RecordInvalid.new(association.owner)) unless saved end end end diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 2af6d09b53..282c9fcf30 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -12,7 +12,6 @@ require "active_support/core_ext/hash/slice" require "active_support/core_ext/string/behavior" require "active_support/core_ext/kernel/singleton_class" require "active_support/core_ext/module/introspection" -require "active_support/core_ext/object/duplicable" require "active_support/core_ext/class/subclasses" require "active_record/attribute_decorators" require "active_record/define_callbacks" diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index ef5444dfc3..a9ab9ab7a9 100644 --- a/activerecord/lib/active_record/callbacks.rb +++ b/activerecord/lib/active_record/callbacks.rb @@ -323,7 +323,6 @@ module ActiveRecord end private - def create_or_update(**) _run_save_callbacks { super } end diff --git a/activerecord/lib/active_record/coders/yaml_column.rb b/activerecord/lib/active_record/coders/yaml_column.rb index 11559141c7..881f0bcdb0 100644 --- a/activerecord/lib/active_record/coders/yaml_column.rb +++ b/activerecord/lib/active_record/coders/yaml_column.rb @@ -39,7 +39,6 @@ module ActiveRecord end private - def check_arity_of_constructor load(nil) rescue ArgumentError diff --git a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb index 7628ef5537..36001efdd5 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -20,6 +20,26 @@ module ActiveRecord end module ConnectionAdapters + module AbstractPool # :nodoc: + def get_schema_cache(connection) + @schema_cache ||= SchemaCache.new(connection) + @schema_cache.connection = connection + @schema_cache + end + + def set_schema_cache(cache) + @schema_cache = cache + end + end + + class NullPool # :nodoc: + include ConnectionAdapters::AbstractPool + + def initialize + @schema_cache = nil + end + end + # Connection pool base class for managing Active Record database # connections. # @@ -147,7 +167,6 @@ module ActiveRecord end private - def internal_poll(timeout) no_wait_poll || (timeout && wait_poll(timeout)) end @@ -310,7 +329,6 @@ module ActiveRecord end private - def spawn_thread(frequency) Thread.new(frequency) do |t| loop do @@ -336,9 +354,10 @@ module ActiveRecord include MonitorMixin include QueryCache::ConnectionPoolConfiguration + include ConnectionAdapters::AbstractPool attr_accessor :automatic_reconnect, :checkout_timeout, :schema_cache - attr_reader :spec, :connections, :size, :reaper + attr_reader :spec, :size, :reaper # Creates a new ConnectionPool object. +spec+ is a ConnectionSpecification # object which describes database connection information (e.g. adapter, @@ -407,7 +426,7 @@ module ActiveRecord # #connection can be called any number of times; the connection is # held in a cache keyed by a thread. def connection - @thread_cached_conns[connection_cache_key(@lock_thread || Thread.current)] ||= checkout + @thread_cached_conns[connection_cache_key(current_thread)] ||= checkout end # Returns true if there is an open connection being used for the current thread. @@ -416,7 +435,7 @@ module ActiveRecord # #connection or #with_connection methods. Connections obtained through # #checkout will not be detected by #active_connection? def active_connection? - @thread_cached_conns[connection_cache_key(Thread.current)] + @thread_cached_conns[connection_cache_key(current_thread)] end # Signal that the thread is finished with the current connection. @@ -451,6 +470,21 @@ module ActiveRecord synchronize { @connections.any? } end + # Returns an array containing the connections currently in the pool. + # Access to the array does not require synchronization on the pool because + # the array is newly created and not retained by the pool. + # + # However; this method bypasses the ConnectionPool's thread-safe connection + # access pattern. A returned connection may be owned by another thread, + # unowned, or by happen-stance owned by the calling thread. + # + # Calling methods on a connection without ownership is subject to the + # thread-safety guarantees of the underlying method. Many of the methods + # on connection adapter classes are inherently multi-thread unsafe. + def connections + synchronize { @connections.dup } + end + # Disconnects all connections in the pool, and clears the pool. # # Raises: @@ -696,6 +730,10 @@ module ActiveRecord thread end + def current_thread + @lock_thread || Thread.current + end + # Take control of all existing connections so a "group" action such as # reload/disconnect can be performed safely. It is no longer enough to # wrap it in +synchronize+ because some pool's actions are allowed @@ -837,7 +875,6 @@ module ActiveRecord def new_connection Base.send(spec.adapter_method, spec.config).tap do |conn| - conn.schema_cache = schema_cache.dup if schema_cache conn.check_version end end @@ -966,15 +1003,30 @@ module ActiveRecord end end + attr_reader :prevent_writes + def initialize # These caches are keyed by spec.name (ConnectionSpecification#name). @owner_to_pool = ConnectionHandler.create_owner_to_pool + @prevent_writes = false # Backup finalizer: if the forked child never needed a pool, the above # early discard has not occurred ObjectSpace.define_finalizer self, ConnectionHandler.unowned_pool_finalizer(@owner_to_pool) end + # Prevent writing to the database regardless of role. + # + # In some cases you may want to prevent writes to the database + # even if you are on a database that can write. `while_preventing_writes` + # will prevent writes to the database for the duration of the block. + def while_preventing_writes + original, @prevent_writes = @prevent_writes, true + yield + ensure + @prevent_writes = original + end + def connection_pool_list owner_to_pool.values.compact end @@ -1092,7 +1144,6 @@ module ActiveRecord end private - def owner_to_pool @owner_to_pool[Process.pid] end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb index 75e959045e..d932f068f2 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_limits.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require "active_support/deprecation" - module ActiveRecord module ConnectionAdapters # :nodoc: module DatabaseLimits diff --git a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb index a7753e3e9c..768122b4d2 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/query_cache.rb @@ -33,17 +33,17 @@ module ActiveRecord end def enable_query_cache! - @query_cache_enabled[connection_cache_key(Thread.current)] = true + @query_cache_enabled[connection_cache_key(current_thread)] = true connection.enable_query_cache! if active_connection? end def disable_query_cache! - @query_cache_enabled.delete connection_cache_key(Thread.current) + @query_cache_enabled.delete connection_cache_key(current_thread) connection.disable_query_cache! if active_connection? end def query_cache_enabled - @query_cache_enabled[connection_cache_key(Thread.current)] + @query_cache_enabled[connection_cache_key(current_thread)] end end @@ -109,7 +109,6 @@ module ActiveRecord end private - def cache_sql(sql, name, binds) @lock.synchronize do result = diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb index 2877530917..93273f6cf6 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb @@ -114,16 +114,16 @@ module ActiveRecord # if the value is a Time responding to usec. def quoted_date(value) if value.acts_like?(:time) - zone_conversion_method = ActiveRecord::Base.default_timezone == :utc ? :getutc : :getlocal - - if value.respond_to?(zone_conversion_method) - value = value.send(zone_conversion_method) + if ActiveRecord::Base.default_timezone == :utc + value = value.getutc if value.respond_to?(:getutc) && !value.utc? + else + value = value.getlocal if value.respond_to?(:getlocal) end end result = value.to_s(:db) if value.respond_to?(:usec) && value.usec > 0 - "#{result}.#{sprintf("%06d", value.usec)}" + result << "." << sprintf("%06d", value.usec) else result end @@ -142,6 +142,59 @@ module ActiveRecord value.to_s.gsub(%r{ (/ (?: | \g<1>) \*) \+? \s* | \s* (\* (?: | \g<2>) /) }x, "") end + def column_name_matcher # :nodoc: + COLUMN_NAME + end + + def column_name_with_order_matcher # :nodoc: + COLUMN_NAME_WITH_ORDER + end + + # Regexp for column names (with or without a table name prefix). + # Matches the following: + # + # "#{table_name}.#{column_name}" + # "#{column_name}" + COLUMN_NAME = / + \A + ( + (?: + # table_name.column_name | function(one or no argument) + ((?:\w+\.)?\w+) | \w+\((?:|\g<2>)\) + ) + (?:(?:\s+AS)?\s+\w+)? + ) + (?:\s*,\s*\g<1>)* + \z + /ix + + # Regexp for column names with order (with or without a table name prefix, + # with or without various order modifiers). Matches the following: + # + # "#{table_name}.#{column_name}" + # "#{table_name}.#{column_name} #{direction}" + # "#{table_name}.#{column_name} #{direction} NULLS FIRST" + # "#{table_name}.#{column_name} NULLS LAST" + # "#{column_name}" + # "#{column_name} #{direction}" + # "#{column_name} #{direction} NULLS FIRST" + # "#{column_name} NULLS LAST" + COLUMN_NAME_WITH_ORDER = / + \A + ( + (?: + # table_name.column_name | function(one or no argument) + ((?:\w+\.)?\w+) | \w+\((?:|\g<2>)\) + ) + (?:\s+ASC|\s+DESC)? + (?:\s+NULLS\s+(?:FIRST|LAST))? + ) + (?:\s*,\s*\g<1>)* + \z + /ix + + private_constant :COLUMN_NAME, :COLUMN_NAME_WITH_ORDER + private def type_casted_binds(binds) if binds.first.is_a?(Array) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb index 7d20825a75..23c993cfc3 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb @@ -19,7 +19,6 @@ module ActiveRecord to: :@conn, private: true private - def visit_AlterTable(o) sql = +"ALTER TABLE #{quote_table_name(o.name)} " sql << o.adds.map { |col| accept col }.join(" ") diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb index cf57af5473..88367c79a1 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -2,7 +2,6 @@ require "active_record/migration/join_table" require "active_support/core_ext/string/access" -require "active_support/deprecation" require "digest/sha2" module ActiveRecord @@ -101,7 +100,7 @@ module ActiveRecord def index_exists?(table_name, column_name, options = {}) column_names = Array(column_name).map(&:to_s) checks = [] - checks << lambda { |i| i.columns == column_names } + checks << lambda { |i| Array(i.columns) == column_names } checks << lambda { |i| i.unique } if options[:unique] checks << lambda { |i| i.name == options[:name].to_s } if options[:name] @@ -310,6 +309,8 @@ module ActiveRecord if force drop_table(table_name, force: force, if_exists: true) + else + schema_cache.clear_data_source_cache!(table_name.to_s) end result = execute schema_creation.accept td @@ -499,6 +500,7 @@ module ActiveRecord # it can be helpful to provide these in a migration's +change+ method so it can be reverted. # In that case, +options+ and the block will be used by #create_table. def drop_table(table_name, options = {}) + schema_cache.clear_data_source_cache!(table_name.to_s) execute "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}" end @@ -1061,8 +1063,8 @@ module ActiveRecord options end - def dump_schema_information #:nodoc: - versions = ActiveRecord::SchemaMigration.all_versions + def dump_schema_information # :nodoc: + versions = schema_migration.all_versions insert_versions_sql(versions) if versions.any? end @@ -1078,7 +1080,7 @@ module ActiveRecord end version = version.to_i - sm_table = quote_table_name(ActiveRecord::SchemaMigration.table_name) + sm_table = quote_table_name(schema_migration.table_name) migrated = migration_context.get_all_versions versions = migration_context.migrations.map(&:version) @@ -1451,7 +1453,7 @@ module ActiveRecord end def insert_versions_sql(versions) - sm_table = quote_table_name(ActiveRecord::SchemaMigration.table_name) + sm_table = quote_table_name(schema_migration.table_name) if versions.is_a?(Array) sql = +"INSERT INTO #{sm_table} (version) VALUES\n" diff --git a/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb index 7b6321d83b..53ce8df491 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/transaction.rb @@ -5,10 +5,11 @@ module ActiveRecord class TransactionState def initialize(state = nil) @state = state - @children = [] + @children = nil end def add_child(state) + @children ||= [] @children << state end @@ -41,12 +42,12 @@ module ActiveRecord end def rollback! - @children.each { |c| c.rollback! } + @children&.each { |c| c.rollback! } @state = :rolledback end def full_rollback! - @children.each { |c| c.rollback! } + @children&.each { |c| c.rollback! } @state = :fully_rolledback end @@ -75,18 +76,19 @@ module ActiveRecord class Transaction #:nodoc: attr_reader :connection, :state, :records, :savepoint_name, :isolation_level - def initialize(connection, options, run_commit_callbacks: false) + def initialize(connection, isolation: nil, joinable: true, run_commit_callbacks: false) @connection = connection @state = TransactionState.new - @records = [] - @isolation_level = options[:isolation] + @records = nil + @isolation_level = isolation @materialized = false - @joinable = options.fetch(:joinable, true) + @joinable = joinable @run_commit_callbacks = run_commit_callbacks end def add_record(record) - records << record + @records ||= [] + @records << record end def materialize! @@ -98,6 +100,7 @@ module ActiveRecord end def rollback_records + return unless records ite = records.uniq(&:object_id) already_run_callbacks = {} while record = ite.shift @@ -107,16 +110,17 @@ module ActiveRecord record.rolledback!(force_restore_state: full_rollback?, should_run_callbacks: should_run_callbacks) end ensure - ite.each do |i| + ite&.each do |i| i.rolledback!(force_restore_state: full_rollback?, should_run_callbacks: false) end end def before_commit_records - records.uniq.each(&:before_committed!) if @run_commit_callbacks + records.uniq.each(&:before_committed!) if records && @run_commit_callbacks end def commit_records + return unless records ite = records.uniq(&:object_id) already_run_callbacks = {} while record = ite.shift @@ -131,7 +135,7 @@ module ActiveRecord end end ensure - ite.each { |i| i.committed!(should_run_callbacks: false) } + ite&.each { |i| i.committed!(should_run_callbacks: false) } end def full_rollback?; true; end @@ -141,8 +145,8 @@ module ActiveRecord end class SavepointTransaction < Transaction - def initialize(connection, savepoint_name, parent_transaction, *args) - super(connection, *args) + def initialize(connection, savepoint_name, parent_transaction, **options) + super(connection, options) parent_transaction.state.add_child(@state) @@ -202,18 +206,29 @@ module ActiveRecord @lazy_transactions_enabled = true end - def begin_transaction(options = {}) + def begin_transaction(isolation: nil, joinable: true, _lazy: true) @connection.lock.synchronize do run_commit_callbacks = !current_transaction.joinable? transaction = if @stack.empty? - RealTransaction.new(@connection, options, run_commit_callbacks: run_commit_callbacks) + RealTransaction.new( + @connection, + isolation: isolation, + joinable: joinable, + run_commit_callbacks: run_commit_callbacks + ) else - SavepointTransaction.new(@connection, "active_record_#{@stack.size}", @stack.last, options, - run_commit_callbacks: run_commit_callbacks) + SavepointTransaction.new( + @connection, + "active_record_#{@stack.size}", + @stack.last, + isolation: isolation, + joinable: joinable, + run_commit_callbacks: run_commit_callbacks + ) end - if @connection.supports_lazy_transactions? && lazy_transactions_enabled? && options[:_lazy] != false + if @connection.supports_lazy_transactions? && lazy_transactions_enabled? && _lazy @has_unmaterialized_transactions = true else transaction.materialize! @@ -274,9 +289,9 @@ module ActiveRecord end end - def within_new_transaction(options = {}) + def within_new_transaction(isolation: nil, joinable: true) @connection.lock.synchronize do - transaction = begin_transaction options + transaction = begin_transaction(isolation: isolation, joinable: joinable) yield rescue Exception => error if transaction @@ -309,7 +324,6 @@ module ActiveRecord end private - NULL_TRANSACTION = NullTransaction.new # Deallocate invalidated prepared statements outside of the transaction diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index bf0bb84c93..dc970c384b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -6,7 +6,6 @@ require "active_record/connection_adapters/sql_type_metadata" require "active_record/connection_adapters/abstract/schema_dumper" require "active_record/connection_adapters/abstract/schema_creation" require "active_support/concurrency/load_interlock_aware_monitor" -require "active_support/deprecation" require "arel/collectors/bind" require "arel/collectors/composite" require "arel/collectors/sql_string" @@ -78,7 +77,7 @@ module ActiveRecord SIMPLE_INT = /\A\d+\z/ attr_accessor :pool - attr_reader :schema_cache, :visitor, :owner, :logger, :lock, :prepared_statements, :prevent_writes + attr_reader :visitor, :owner, :logger, :lock, :prepared_statements alias :in_use? :owner set_callback :checkin, :after, :enable_lazy_transactions! @@ -106,6 +105,14 @@ module ActiveRecord Regexp.union(*parts) end + def self.quoted_column_names # :nodoc: + @quoted_column_names ||= {} + end + + def self.quoted_table_names # :nodoc: + @quoted_table_names ||= {} + end + def initialize(connection, logger = nil, config = {}) # :nodoc: super() @@ -114,11 +121,8 @@ module ActiveRecord @instrumenter = ActiveSupport::Notifications.instrumenter @logger = logger @config = config - @pool = nil + @pool = ActiveRecord::ConnectionAdapters::NullPool.new @idle_since = Concurrent.monotonic_time - @schema_cache = SchemaCache.new self - @quoted_column_names, @quoted_table_names = {}, {} - @prevent_writes = false @visitor = arel_visitor @statements = build_statement_pool @lock = ActiveSupport::Concurrency::LoadInterlockAwareMonitor.new @@ -144,19 +148,7 @@ module ActiveRecord # Returns true if the connection is a replica, or if +prevent_writes+ # is set to true. def preventing_writes? - replica? || prevent_writes - end - - # Prevent writing to the database regardless of role. - # - # In some cases you may want to prevent writes to the database - # even if you are on a database that can write. `while_preventing_writes` - # will prevent writes to the database for the duration of the block. - def while_preventing_writes - original, @prevent_writes = @prevent_writes, true - yield - ensure - @prevent_writes = original + replica? || ActiveRecord::Base.connection_handler.prevent_writes end def migrations_paths # :nodoc: @@ -164,7 +156,22 @@ module ActiveRecord end def migration_context # :nodoc: - MigrationContext.new(migrations_paths) + MigrationContext.new(migrations_paths, schema_migration) + end + + def schema_migration # :nodoc: + @schema_migration ||= begin + conn = self + spec_name = conn.pool.spec.name + name = "#{spec_name}::SchemaMigration" + + Class.new(ActiveRecord::SchemaMigration) do + define_singleton_method(:name) { name } + define_singleton_method(:to_s) { name } + + self.connection_specification_name = spec_name + end + end end class Version @@ -206,9 +213,13 @@ module ActiveRecord @owner = Thread.current end + def schema_cache + @pool.get_schema_cache(self) + end + def schema_cache=(cache) cache.connection = self - @schema_cache = cache + @pool.set_schema_cache(cache) end # this method must only be called while holding connection pool's mutex @@ -259,6 +270,11 @@ module ActiveRecord self.class::ADAPTER_NAME end + # Does the database for this adapter exist? + def self.database_exists?(config) + raise NotImplementedError + end + # Does this adapter support DDL rollbacks in transactions? That is, would # CREATE TABLE or ALTER TABLE get rolled back by a transaction? def supports_ddl_transactions? @@ -487,6 +503,9 @@ module ActiveRecord # # Prevent @connection's finalizer from touching the socket, or # otherwise communicating with its server, when it is collected. + if schema_cache.connection == self + schema_cache.connection = nil + end end # Reset the state of this connection, directing the DBMS to clear @@ -587,7 +606,6 @@ module ActiveRecord end private - def type_map @type_map ||= Type::TypeMap.new.tap do |mapping| initialize_type_map(mapping) diff --git a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb index 59e58d5d35..ef1eef6b69 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -45,7 +45,6 @@ module ActiveRecord class StatementPool < ConnectionAdapters::StatementPool # :nodoc: private - def dealloc(stmt) stmt.close end @@ -289,6 +288,8 @@ module ActiveRecord # Example: # rename_table('octopuses', 'octopi') def rename_table(table_name, new_name) + schema_cache.clear_data_source_cache!(table_name.to_s) + schema_cache.clear_data_source_cache!(new_name.to_s) execute "RENAME TABLE #{quote_table_name(table_name)} TO #{quote_table_name(new_name)}" rename_table_indexes(table_name, new_name) end @@ -309,6 +310,7 @@ module ActiveRecord # it can be helpful to provide these in a migration's +change+ method so it can be reverted. # In that case, +options+ and the block will be used by create_table. def drop_table(table_name, options = {}) + schema_cache.clear_data_source_cache!(table_name.to_s) execute "DROP#{' TEMPORARY' if options[:temporary]} TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}" end @@ -513,7 +515,6 @@ module ActiveRecord end private - def initialize_type_map(m = type_map) super @@ -618,7 +619,11 @@ module ActiveRecord when ER_QUERY_INTERRUPTED QueryCanceled.new(message, sql: sql, binds: binds) else - super + if exception.is_a?(Mysql2::Error::TimeoutError) + ActiveRecord::AdapterTimeout.new(message, sql: sql, binds: binds) + else + super + end end end @@ -736,7 +741,7 @@ module ActiveRecord end.compact.join(", ") # ...and send them all in one query - execute "SET #{encoding} #{sql_mode_assignment} #{variable_assignments}" + execute("SET #{encoding} #{sql_mode_assignment} #{variable_assignments}", "SCHEMA") end def column_definitions(table_name) # :nodoc: @@ -795,7 +800,6 @@ module ActiveRecord end private - def cast_value(value) case value when true then "1" diff --git a/activerecord/lib/active_record/connection_adapters/column.rb b/activerecord/lib/active_record/connection_adapters/column.rb index 279d0b9e84..2708d2756b 100644 --- a/activerecord/lib/active_record/connection_adapters/column.rb +++ b/activerecord/lib/active_record/connection_adapters/column.rb @@ -5,6 +5,8 @@ module ActiveRecord module ConnectionAdapters # An abstract definition of a column in a table. class Column + include Deduplicable + attr_reader :name, :default, :sql_type_metadata, :null, :default_function, :collation, :comment delegate :precision, :scale, :limit, :type, :sql_type, to: :sql_type_metadata, allow_nil: true @@ -76,6 +78,7 @@ module ActiveRecord def hash Column.hash ^ name.hash ^ + name.encoding.hash ^ default.hash ^ sql_type_metadata.hash ^ null.hash ^ @@ -83,6 +86,17 @@ module ActiveRecord collation.hash ^ comment.hash end + + private + def deduplicated + @name = -name + @sql_type_metadata = sql_type_metadata.deduplicate if sql_type_metadata + @default = -default if default + @default_function = -default_function if default_function + @collation = -collation if collation + @comment = -comment if comment + super + end end class NullColumn < Column diff --git a/activerecord/lib/active_record/connection_adapters/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/connection_specification.rb index 2c768298e6..0732b69f81 100644 --- a/activerecord/lib/active_record/connection_adapters/connection_specification.rb +++ b/activerecord/lib/active_record/connection_adapters/connection_specification.rb @@ -56,7 +56,6 @@ module ActiveRecord end private - attr_reader :uri def uri_parser diff --git a/activerecord/lib/active_record/connection_adapters/deduplicable.rb b/activerecord/lib/active_record/connection_adapters/deduplicable.rb new file mode 100644 index 0000000000..fb2fd60bbc --- /dev/null +++ b/activerecord/lib/active_record/connection_adapters/deduplicable.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +module ActiveRecord + module ConnectionAdapters # :nodoc: + module Deduplicable + extend ActiveSupport::Concern + + module ClassMethods + def registry + @registry ||= {} + end + + def new(*) + super.deduplicate + end + end + + def deduplicate + self.class.registry[self] ||= deduplicated + end + alias :-@ :deduplicate + + private + def deduplicated + freeze + end + end + end +end diff --git a/activerecord/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb b/activerecord/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb index 1df4dea2d8..97d74df529 100644 --- a/activerecord/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb +++ b/activerecord/lib/active_record/connection_adapters/determine_if_preparable_visitor.rb @@ -5,7 +5,7 @@ module ActiveRecord module DetermineIfPreparableVisitor attr_accessor :preparable - def accept(*) + def accept(object, collector) @preparable = true super end @@ -20,7 +20,7 @@ module ActiveRecord super end - def visit_Arel_Nodes_SqlLiteral(*) + def visit_Arel_Nodes_SqlLiteral(o, collector) @preparable = false super end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb b/activerecord/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb index 20c3c83664..edd5ea0542 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/explain_pretty_printer.rb @@ -37,7 +37,6 @@ module ActiveRecord end private - def compute_column_widths(result) [].tap do |widths| result.columns.each_with_index do |column, i| diff --git a/activerecord/lib/active_record/connection_adapters/mysql/quoting.rb b/activerecord/lib/active_record/connection_adapters/mysql/quoting.rb index 75564a61d6..0069f5871c 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/quoting.rb @@ -5,11 +5,11 @@ module ActiveRecord module MySQL module Quoting # :nodoc: def quote_column_name(name) - @quoted_column_names[name] ||= "`#{super.gsub('`', '``')}`" + self.class.quoted_column_names[name] ||= "`#{super.gsub('`', '``')}`" end def quote_table_name(name) - @quoted_table_names[name] ||= super.gsub(".", "`.`").freeze + self.class.quoted_table_names[name] ||= super.gsub(".", "`.`").freeze end def unquoted_true @@ -32,12 +32,49 @@ module ActiveRecord "x'#{value.hex}'" end - def _type_cast(value) - case value - when Date, Time then value - else super - end + def column_name_matcher + COLUMN_NAME + end + + def column_name_with_order_matcher + COLUMN_NAME_WITH_ORDER end + + COLUMN_NAME = / + \A + ( + (?: + # `table_name`.`column_name` | function(one or no argument) + ((?:\w+\.|`\w+`\.)?(?:\w+|`\w+`)) | \w+\((?:|\g<2>)\) + ) + (?:(?:\s+AS)?\s+(?:\w+|`\w+`))? + ) + (?:\s*,\s*\g<1>)* + \z + /ix + + COLUMN_NAME_WITH_ORDER = / + \A + ( + (?: + # `table_name`.`column_name` | function(one or no argument) + ((?:\w+\.|`\w+`\.)?(?:\w+|`\w+`)) | \w+\((?:|\g<2>)\) + ) + (?:\s+ASC|\s+DESC)? + ) + (?:\s*,\s*\g<1>)* + \z + /ix + + private_constant :COLUMN_NAME, :COLUMN_NAME_WITH_ORDER + + private + def _type_cast(value) + case value + when Date, Time then value + else super + end + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/schema_creation.rb b/activerecord/lib/active_record/connection_adapters/mysql/schema_creation.rb index 82ed320617..0f5ab7562a 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/schema_creation.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/schema_creation.rb @@ -7,7 +7,6 @@ module ActiveRecord delegate :add_sql_comment!, :mariadb?, to: :@conn, private: true private - def visit_DropForeignKey(name) "DROP FOREIGN KEY #{name}" end diff --git a/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb index 234fb25fdf..bcd300f3db 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/schema_dumper.rb @@ -41,13 +41,15 @@ module ActiveRecord case column.sql_type when /\Atimestamp\b/ :timestamp + when /\A(?:enum|set)\b/ + column.sql_type else super end end def schema_limit(column) - super unless /\A(?:tiny|medium|long)?(?:text|blob)/.match?(column.sql_type) + super unless /\A(?:enum|set|(?:tiny|medium|long)?(?:text|blob))\b/.match?(column.sql_type) end def schema_precision(column) diff --git a/activerecord/lib/active_record/connection_adapters/mysql/type_metadata.rb b/activerecord/lib/active_record/connection_adapters/mysql/type_metadata.rb index 9167593064..a7232fa249 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql/type_metadata.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql/type_metadata.rb @@ -6,9 +6,11 @@ module ActiveRecord class TypeMetadata < DelegateClass(SqlTypeMetadata) # :nodoc: undef to_yaml if method_defined?(:to_yaml) + include Deduplicable + attr_reader :extra - def initialize(type_metadata, extra: "") + def initialize(type_metadata, extra: nil) super(type_metadata) @extra = extra end @@ -25,6 +27,13 @@ module ActiveRecord __getobj__.hash ^ extra.hash end + + private + def deduplicated + __setobj__(__getobj__.deduplicate) + @extra = -extra if extra + super + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb index 5b0335c22b..1df9ac32c9 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb @@ -8,6 +8,8 @@ require "mysql2" module ActiveRecord module ConnectionHandling # :nodoc: + ER_BAD_DB_ERROR = 1049 + # Establishes a connection to the database that's used by all Active Record objects. def mysql2_connection(config) config = config.symbolize_keys @@ -22,7 +24,7 @@ module ActiveRecord client = Mysql2::Client.new(config) ConnectionAdapters::Mysql2Adapter.new(client, logger, nil, config) rescue Mysql2::Error => error - if error.message.include?("Unknown database") + if error.error_number == ER_BAD_DB_ERROR raise ActiveRecord::NoDatabaseError else raise @@ -42,6 +44,12 @@ module ActiveRecord configure_connection end + def self.database_exists?(config) + !!ActiveRecord::Base.mysql2_connection(config) + rescue ActiveRecord::NoDatabaseError + false + end + def supports_json? !mariadb? && database_version >= "5.7.8" end @@ -109,12 +117,12 @@ module ActiveRecord end def discard! # :nodoc: + super @connection.automatic_close = false @connection = nil end private - def connect @connection = Mysql2::Client.new(@config) configure_connection diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/column.rb b/activerecord/lib/active_record/connection_adapters/postgresql/column.rb index ec25bb1e19..f1ecf6df30 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/column.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/column.rb @@ -23,6 +23,29 @@ module ActiveRecord def sql_type super.sub(/\[\]\z/, "") end + + def init_with(coder) + @serial = coder["serial"] + super + end + + def encode_with(coder) + coder["serial"] = @serial + super + end + + def ==(other) + other.is_a?(Column) && + super && + serial? == other.serial? + end + alias :eql? :== + + def hash + Column.hash ^ + super.hash ^ + serial?.hash + end end end PostgreSQLColumn = PostgreSQL::Column # :nodoc: diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb index b1dfbde86e..0bbe98145a 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb @@ -77,7 +77,6 @@ module ActiveRecord end private - def type_cast_array(value, method) if value.is_a?(::Array) value.map { |item| type_cast_array(item, method) } diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/enum.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/enum.rb index f70f09ad95..bae34472e1 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/enum.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/enum.rb @@ -10,7 +10,6 @@ module ActiveRecord end private - def cast_value(value) value.to_s end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb index 7b42677101..8d4dacbd64 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/hstore.rb @@ -46,7 +46,6 @@ module ActiveRecord end private - HstorePair = begin quoted_string = /"[^"\\]*(?:\\.[^"\\]*)*"/ unquoted_string = /(?:\\.|[^\s,])[^\s=,\\]*(?:\\.[^\s=,\\]*|=[^,>])*/ diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb index 7f6adc351c..e52d4385ef 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/legacy_point.rb @@ -34,7 +34,6 @@ module ActiveRecord end private - def number_for_point(number) number.to_s.gsub(/\.0$/, "") end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/money.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/money.rb index 6434377b57..357493dfc0 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/money.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/money.rb @@ -26,9 +26,9 @@ module ActiveRecord value = value.sub(/^\((.+)\)$/, '-\1') # (4) case value - when /^-?\D+[\d,]+\.\d{2}$/ # (1) + when /^-?\D*[\d,]+\.\d{2}$/ # (1) value.gsub!(/[^-\d.]/, "") - when /^-?\D+[\d.]+,\d{2}$/ # (2) + when /^-?\D*[\d.]+,\d{2}$/ # (2) value.gsub!(/[^-\d,]/, "").sub!(/,/, ".") end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/point.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/point.rb index 8c74cecc4d..e81e18ff70 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/point.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/point.rb @@ -50,7 +50,6 @@ module ActiveRecord end private - def number_for_point(number) number.to_s.gsub(/\.0$/, "") end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb index aa7701e038..d19f1f9cf8 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb @@ -58,7 +58,6 @@ module ActiveRecord end private - def type_cast_single(value) infinity?(value) ? value : @subtype.deserialize(value) end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/uuid.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/uuid.rb index 28abdbd073..74a28eef58 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/uuid.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/uuid.rb @@ -14,7 +14,6 @@ module ActiveRecord end private - def cast_value(value) casted = value.to_s casted if casted.match?(ACCEPTABLE_UUID) diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb index d40e0ef1f0..07b66de366 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb @@ -30,7 +30,7 @@ module ActiveRecord # - "schema.name".table_name # - "schema.name"."table.name" def quote_table_name(name) # :nodoc: - @quoted_table_names[name] ||= Utils.extract_schema_qualified_name(name.to_s).quoted.freeze + self.class.quoted_table_names[name] ||= Utils.extract_schema_qualified_name(name.to_s).quoted.freeze end # Quotes schema names for use in SQL queries. @@ -44,7 +44,7 @@ module ActiveRecord # Quotes column names for use in SQL queries. def quote_column_name(name) # :nodoc: - @quoted_column_names[name] ||= PG::Connection.quote_ident(super).freeze + self.class.quoted_column_names[name] ||= PG::Connection.quote_ident(super).freeze end # Quote date/time values for use in SQL input. @@ -78,6 +78,43 @@ module ActiveRecord type_map.lookup(column.oid, column.fmod, column.sql_type) end + def column_name_matcher + COLUMN_NAME + end + + def column_name_with_order_matcher + COLUMN_NAME_WITH_ORDER + end + + COLUMN_NAME = / + \A + ( + (?: + # "table_name"."column_name"::type_name | function(one or no argument)::type_name + ((?:\w+\.|"\w+"\.)?(?:\w+|"\w+")(?:::\w+)?) | \w+\((?:|\g<2>)\)(?:::\w+)? + ) + (?:(?:\s+AS)?\s+(?:\w+|"\w+"))? + ) + (?:\s*,\s*\g<1>)* + \z + /ix + + COLUMN_NAME_WITH_ORDER = / + \A + ( + (?: + # "table_name"."column_name"::type_name | function(one or no argument)::type_name + ((?:\w+\.|"\w+"\.)?(?:\w+|"\w+")(?:::\w+)?) | \w+\((?:|\g<2>)\)(?:::\w+)? + ) + (?:\s+ASC|\s+DESC)? + (?:\s+NULLS\s+(?:FIRST|LAST))? + ) + (?:\s*,\s*\g<1>)* + \z + /ix + + private_constant :COLUMN_NAME, :COLUMN_NAME_WITH_ORDER + private def lookup_cast_type(sql_type) super(query_value("SELECT #{quote(sql_type)}::regtype::oid", "SCHEMA").to_i) diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb index 84643d20da..d201e40190 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb @@ -5,7 +5,6 @@ module ActiveRecord module PostgreSQL class SchemaDumper < ConnectionAdapters::SchemaDumper # :nodoc: private - def extensions(stream) extensions = @connection.extensions if extensions.any? diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb index f9e3dccb64..628a609521 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -55,6 +55,7 @@ module ActiveRecord end def drop_table(table_name, options = {}) # :nodoc: + schema_cache.clear_data_source_cache!(table_name.to_s) execute "DROP TABLE#{' IF EXISTS' if options[:if_exists]} #{quote_table_name(table_name)}#{' CASCADE' if options[:force] == :cascade}" end @@ -376,6 +377,8 @@ module ActiveRecord # rename_table('octopuses', 'octopi') def rename_table(table_name, new_name) clear_cache! + schema_cache.clear_data_source_cache!(table_name.to_s) + schema_cache.clear_data_source_cache!(new_name.to_s) execute "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}" pk, seq = pk_and_sequence_for(new_name) if pk diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/type_metadata.rb b/activerecord/lib/active_record/connection_adapters/postgresql/type_metadata.rb index 8bdec623af..b7f6479357 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/type_metadata.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/type_metadata.rb @@ -7,6 +7,8 @@ module ActiveRecord class TypeMetadata < DelegateClass(SqlTypeMetadata) undef to_yaml if method_defined?(:to_yaml) + include Deduplicable + attr_reader :oid, :fmod def initialize(type_metadata, oid: nil, fmod: nil) @@ -29,6 +31,12 @@ module ActiveRecord oid.hash ^ fmod.hash end + + private + def deduplicated + __setobj__(__getobj__.deduplicate) + super + end end end PostgreSQLTypeMetadata = PostgreSQL::TypeMetadata diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb b/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb index f2f4701500..e8caeb8132 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb @@ -37,7 +37,6 @@ module ActiveRecord end protected - def parts @parts ||= [@schema, @identifier].compact end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 91318a0af1..0a7c6d8ac4 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -46,7 +46,7 @@ module ActiveRecord conn = PG.connect(conn_params) ConnectionAdapters::PostgreSQLAdapter.new(conn, logger, conn_params, config) rescue ::PG::Error => error - if error.message.include?("does not exist") + if error.message.include?(conn_params[:dbname]) raise ActiveRecord::NoDatabaseError else raise @@ -259,6 +259,12 @@ module ActiveRecord @use_insert_returning = @config.key?(:insert_returning) ? self.class.type_cast_config_to_boolean(@config[:insert_returning]) : true end + def self.database_exists?(config) + !!ActiveRecord::Base.postgresql_connection(config) + rescue ActiveRecord::NoDatabaseError + false + end + # Is this connection alive and ready for queries? def active? @lock.synchronize do @@ -302,6 +308,7 @@ module ActiveRecord end def discard! # :nodoc: + super @connection.socket_io.reopen(IO::NULL) rescue nil @connection = nil end @@ -452,7 +459,6 @@ module ActiveRecord end private - # See https://www.postgresql.org/docs/current/static/errcodes-appendix.html VALUE_LIMIT_VIOLATION = "22001" NUMERIC_VALUE_OUT_OF_RANGE = "22003" diff --git a/activerecord/lib/active_record/connection_adapters/schema_cache.rb b/activerecord/lib/active_record/connection_adapters/schema_cache.rb index dbfe1e4a34..5e30304864 100644 --- a/activerecord/lib/active_record/connection_adapters/schema_cache.rb +++ b/activerecord/lib/active_record/connection_adapters/schema_cache.rb @@ -27,7 +27,6 @@ module ActiveRecord def encode_with(coder) coder["columns"] = @columns - coder["columns_hash"] = @columns_hash coder["primary_keys"] = @primary_keys coder["data_sources"] = @data_sources coder["indexes"] = @indexes @@ -37,16 +36,21 @@ module ActiveRecord def init_with(coder) @columns = coder["columns"] - @columns_hash = coder["columns_hash"] @primary_keys = coder["primary_keys"] @data_sources = coder["data_sources"] @indexes = coder["indexes"] || {} @version = coder["version"] @database_version = coder["database_version"] + + derive_columns_hash_and_deduplicate_values end def primary_keys(table_name) - @primary_keys[table_name] ||= data_source_exists?(table_name) ? connection.primary_key(table_name) : nil + @primary_keys.fetch(table_name) do + if data_source_exists?(table_name) + @primary_keys[deep_deduplicate(table_name)] = deep_deduplicate(connection.primary_key(table_name)) + end + end end # A cached lookup for table existence. @@ -54,7 +58,7 @@ module ActiveRecord prepare_data_sources if @data_sources.empty? return @data_sources[name] if @data_sources.key? name - @data_sources[name] = connection.data_source_exists?(name) + @data_sources[deep_deduplicate(name)] = connection.data_source_exists?(name) end # Add internal cache for table with +table_name+. @@ -73,15 +77,17 @@ module ActiveRecord # Get the columns for a table def columns(table_name) - @columns[table_name] ||= connection.columns(table_name) + @columns.fetch(table_name) do + @columns[deep_deduplicate(table_name)] = deep_deduplicate(connection.columns(table_name)) + end end # Get the columns for a table as a hash, key is the column name # value is the column object. def columns_hash(table_name) - @columns_hash[table_name] ||= Hash[columns(table_name).map { |col| - [col.name, col] - }] + @columns_hash.fetch(table_name) do + @columns_hash[deep_deduplicate(table_name)] = columns(table_name).index_by(&:name) + end end # Checks whether the columns hash is already cached for a table. @@ -90,7 +96,9 @@ module ActiveRecord end def indexes(table_name) - @indexes[table_name] ||= connection.indexes(table_name) + @indexes.fetch(table_name) do + @indexes[deep_deduplicate(table_name)] = deep_deduplicate(connection.indexes(table_name)) + end end def database_version # :nodoc: @@ -124,15 +132,38 @@ module ActiveRecord def marshal_dump # if we get current version during initialization, it happens stack over flow. @version = connection.migration_context.current_version - [@version, @columns, @columns_hash, @primary_keys, @data_sources, @indexes, database_version] + [@version, @columns, {}, @primary_keys, @data_sources, @indexes, database_version] end def marshal_load(array) - @version, @columns, @columns_hash, @primary_keys, @data_sources, @indexes, @database_version = array - @indexes = @indexes || {} + @version, @columns, _columns_hash, @primary_keys, @data_sources, @indexes, @database_version = array + @indexes ||= {} + + derive_columns_hash_and_deduplicate_values end private + def derive_columns_hash_and_deduplicate_values + @columns = deep_deduplicate(@columns) + @columns_hash = @columns.transform_values { |columns| columns.index_by(&:name) } + @primary_keys = deep_deduplicate(@primary_keys) + @data_sources = deep_deduplicate(@data_sources) + @indexes = deep_deduplicate(@indexes) + end + + def deep_deduplicate(value) + case value + when Hash + value.transform_keys { |k| deep_deduplicate(k) }.transform_values { |v| deep_deduplicate(v) } + when Array + value.map { |i| deep_deduplicate(i) } + when String, Deduplicable + -value + else + value + end + end + def prepare_data_sources connection.data_sources.each { |source| @data_sources[source] = true } end diff --git a/activerecord/lib/active_record/connection_adapters/sql_type_metadata.rb b/activerecord/lib/active_record/connection_adapters/sql_type_metadata.rb index df28df7a7c..969867e70f 100644 --- a/activerecord/lib/active_record/connection_adapters/sql_type_metadata.rb +++ b/activerecord/lib/active_record/connection_adapters/sql_type_metadata.rb @@ -1,9 +1,13 @@ # frozen_string_literal: true +require "active_record/connection_adapters/deduplicable" + module ActiveRecord # :stopdoc: module ConnectionAdapters class SqlTypeMetadata + include Deduplicable + attr_reader :sql_type, :type, :limit, :precision, :scale def initialize(sql_type: nil, type: nil, limit: nil, precision: nil, scale: nil) @@ -32,6 +36,12 @@ module ActiveRecord precision.hash >> 1 ^ scale.hash >> 2 end + + private + def deduplicated + @sql_type = -sql_type + super + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3/quoting.rb b/activerecord/lib/active_record/connection_adapters/sqlite3/quoting.rb index cb9d32a577..9b74a774e5 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3/quoting.rb @@ -13,11 +13,11 @@ module ActiveRecord end def quote_table_name(name) - @quoted_table_names[name] ||= super.gsub(".", "\".\"").freeze + self.class.quoted_table_names[name] ||= super.gsub(".", "\".\"").freeze end def quote_column_name(name) - @quoted_column_names[name] ||= %Q("#{super.gsub('"', '""')}") + self.class.quoted_column_names[name] ||= %Q("#{super.gsub('"', '""')}") end def quoted_time(value) @@ -45,8 +45,43 @@ module ActiveRecord 0 end - private + def column_name_matcher + COLUMN_NAME + end + + def column_name_with_order_matcher + COLUMN_NAME_WITH_ORDER + end + COLUMN_NAME = / + \A + ( + (?: + # "table_name"."column_name" | function(one or no argument) + ((?:\w+\.|"\w+"\.)?(?:\w+|"\w+")) | \w+\((?:|\g<2>)\) + ) + (?:(?:\s+AS)?\s+(?:\w+|"\w+"))? + ) + (?:\s*,\s*\g<1>)* + \z + /ix + + COLUMN_NAME_WITH_ORDER = / + \A + ( + (?: + # "table_name"."column_name" | function(one or no argument) + ((?:\w+\.|"\w+"\.)?(?:\w+|"\w+")) | \w+\((?:|\g<2>)\) + ) + (?:\s+ASC|\s+DESC)? + ) + (?:\s*,\s*\g<1>)* + \z + /ix + + private_constant :COLUMN_NAME, :COLUMN_NAME_WITH_ORDER + + private def _type_cast(value) case value when BigDecimal diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb index 9fc5ee3ab4..f4847eb6c0 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb @@ -98,6 +98,16 @@ module ActiveRecord configure_connection end + def self.database_exists?(config) + config = config.symbolize_keys + if config[:database] == ":memory:" + return true + else + database_file = defined?(Rails.root) ? File.expand_path(config[:database], Rails.root) : config[:database] + File.exist?(database_file) + end + end + def supports_ddl_transactions? true end @@ -218,6 +228,8 @@ module ActiveRecord # Example: # rename_table('octopuses', 'octopi') def rename_table(table_name, new_name) + schema_cache.clear_data_source_cache!(table_name.to_s) + schema_cache.clear_data_source_cache!(new_name.to_s) exec_query "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}" rename_table_indexes(table_name, new_name) end @@ -381,6 +393,7 @@ module ActiveRecord if from_primary_key.is_a?(Array) @definition.primary_keys from_primary_key end + columns(from).each do |column| column_name = options[:rename] ? (options[:rename][column.name] || diff --git a/activerecord/lib/active_record/connection_adapters/statement_pool.rb b/activerecord/lib/active_record/connection_adapters/statement_pool.rb index 46bd831da7..0960feed84 100644 --- a/activerecord/lib/active_record/connection_adapters/statement_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/statement_pool.rb @@ -48,7 +48,6 @@ module ActiveRecord end private - def cache @cache[Process.pid] end diff --git a/activerecord/lib/active_record/connection_handling.rb b/activerecord/lib/active_record/connection_handling.rb index 040ebdb960..c8cefa9906 100644 --- a/activerecord/lib/active_record/connection_handling.rb +++ b/activerecord/lib/active_record/connection_handling.rb @@ -173,7 +173,7 @@ module ActiveRecord raise "Anonymous class is not allowed." unless name config_or_env ||= DEFAULT_ENV.call.to_sym - pool_name = self == Base ? "primary" : name + pool_name = primary_class? ? "primary" : name self.connection_specification_name = pool_name resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new(Base.configurations) @@ -204,11 +204,15 @@ module ActiveRecord # Return the specification name from the current class or its parent. def connection_specification_name if !defined?(@connection_specification_name) || @connection_specification_name.nil? - return self == Base ? "primary" : superclass.connection_specification_name + return primary_class? ? "primary" : superclass.connection_specification_name end @connection_specification_name end + def primary_class? # :nodoc: + self == Base || defined?(ApplicationRecord) && self == ApplicationRecord + end + # Returns the configuration of the associated connection as a hash: # # ActiveRecord::Base.connection_config @@ -252,7 +256,6 @@ module ActiveRecord :clear_all_connections!, :flush_idle_connections!, to: :connection_handler private - def swap_connection_handler(handler, &blk) # :nodoc: old_handler, ActiveRecord::Base.connection_handler = ActiveRecord::Base.connection_handler, handler yield diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index dfd33d3dd7..595ef4ee25 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -286,7 +286,6 @@ module ActiveRecord end private - def cached_find_by_statement(key, &block) cache = @find_by_statement_cache[connection.prepared_statements] cache.compute_if_absent(key) { StatementCache.create(connection, &block) } @@ -554,7 +553,6 @@ module ActiveRecord end private - # +Array#flatten+ will call +#to_ary+ (recursively) on each of the elements of # the array, and then rescues from the possible +NoMethodError+. If those elements are # +ActiveRecord::Base+'s, then this triggers the various +method_missing+'s that we have, diff --git a/activerecord/lib/active_record/database_configurations.rb b/activerecord/lib/active_record/database_configurations.rb index 44b5cfc738..e122628b05 100644 --- a/activerecord/lib/active_record/database_configurations.rb +++ b/activerecord/lib/active_record/database_configurations.rb @@ -104,18 +104,28 @@ module ActiveRecord return configs.configurations if configs.is_a?(DatabaseConfigurations) return configs if configs.is_a?(Array) - build_db_config = configs.each_pair.flat_map do |env_name, config| - walk_configs(env_name.to_s, "primary", config) - end.flatten.compact + db_configs = configs.flat_map do |env_name, config| + if config.is_a?(Hash) && config.all? { |k, v| v.is_a?(Hash) } + walk_configs(env_name.to_s, config) + else + build_db_config_from_raw_config(env_name.to_s, "primary", config) + end + end.compact if url = ENV["DATABASE_URL"] - build_url_config(url, build_db_config) + merge_url_with_configs(url, db_configs) else - build_db_config + db_configs + end + end + + def walk_configs(env_name, config) + config.map do |spec_name, sub_config| + build_db_config_from_raw_config(env_name, spec_name.to_s, sub_config) end end - def walk_configs(env_name, spec_name, config) + def build_db_config_from_raw_config(env_name, spec_name, config) case config when String build_db_config_from_string(env_name, spec_name, config) @@ -141,23 +151,19 @@ module ActiveRecord config_without_url.delete "url" ActiveRecord::DatabaseConfigurations::UrlConfig.new(env_name, spec_name, url, config_without_url) - elsif config["database"] || (config.size == 1 && config.values.all? { |v| v.is_a? String }) - ActiveRecord::DatabaseConfigurations::HashConfig.new(env_name, spec_name, config) else - config.each_pair.map do |sub_spec_name, sub_config| - walk_configs(env_name, sub_spec_name, sub_config) - end + ActiveRecord::DatabaseConfigurations::HashConfig.new(env_name, spec_name, config) end end - def build_url_config(url, configs) + def merge_url_with_configs(url, configs) env = ActiveRecord::ConnectionHandling::DEFAULT_ENV.call.to_s - if original_config = configs.find(&:for_current_env?) - if original_config.url_config? - configs - else - configs.map do |config| + if configs.find(&:for_current_env?) + configs.map do |config| + if config.url_config? + config + else ActiveRecord::DatabaseConfigurations::UrlConfig.new(config.env_name, config.spec_name, url, config.config) end end diff --git a/activerecord/lib/active_record/database_configurations/url_config.rb b/activerecord/lib/active_record/database_configurations/url_config.rb index e2d30ae416..e6b4acc647 100644 --- a/activerecord/lib/active_record/database_configurations/url_config.rb +++ b/activerecord/lib/active_record/database_configurations/url_config.rb @@ -56,7 +56,6 @@ module ActiveRecord end private - def build_url_hash(url) if url.nil? || /^jdbc:/.match?(url) { "url" => url } diff --git a/activerecord/lib/active_record/dynamic_matchers.rb b/activerecord/lib/active_record/dynamic_matchers.rb index 398a029068..7d9e221faa 100644 --- a/activerecord/lib/active_record/dynamic_matchers.rb +++ b/activerecord/lib/active_record/dynamic_matchers.rb @@ -69,7 +69,6 @@ module ActiveRecord end private - def body "#{finder}(#{attributes_hash})" end diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb index 60cf9818c1..20cc987d6e 100644 --- a/activerecord/lib/active_record/errors.rb +++ b/activerecord/lib/active_record/errors.rb @@ -38,6 +38,10 @@ module ActiveRecord class AdapterNotSpecified < ActiveRecordError end + # Raised when a model makes a query but it has not specified an associated table. + class TableNotSpecified < ActiveRecordError + end + # Raised when Active Record cannot find database adapter specified in # +config/database.yml+ or programmatically. class AdapterNotFound < ActiveRecordError @@ -349,16 +353,24 @@ module ActiveRecord class IrreversibleOrderError < ActiveRecordError end + # Superclass for errors that have been aborted (either by client or server). + class QueryAborted < StatementInvalid + end + # LockWaitTimeout will be raised when lock wait timeout exceeded. class LockWaitTimeout < StatementInvalid end # StatementTimeout will be raised when statement timeout exceeded. - class StatementTimeout < StatementInvalid + class StatementTimeout < QueryAborted end # QueryCanceled will be raised when canceling statement due to user request. - class QueryCanceled < StatementInvalid + class QueryCanceled < QueryAborted + end + + # AdapterTimeout will be raised when database clients times out while waiting from the server. + class AdapterTimeout < QueryAborted end # UnknownAttributeReference is raised when an unknown and potentially unsafe diff --git a/activerecord/lib/active_record/explain.rb b/activerecord/lib/active_record/explain.rb index 919e96cd7a..5dca75c539 100644 --- a/activerecord/lib/active_record/explain.rb +++ b/activerecord/lib/active_record/explain.rb @@ -36,7 +36,6 @@ module ActiveRecord end private - def render_bind(attr) value = if attr.type.binary? && attr.value "<#{attr.value_for_database.to_s.bytesize} bytes of binary data>" diff --git a/activerecord/lib/active_record/fixture_set/table_row.rb b/activerecord/lib/active_record/fixture_set/table_row.rb index cb4726f1ee..f65329f91d 100644 --- a/activerecord/lib/active_record/fixture_set/table_row.rb +++ b/activerecord/lib/active_record/fixture_set/table_row.rb @@ -48,7 +48,6 @@ module ActiveRecord end private - def model_metadata @table_rows.model_metadata end diff --git a/activerecord/lib/active_record/fixture_set/table_rows.rb b/activerecord/lib/active_record/fixture_set/table_rows.rb index 23814b6cb5..df1cd63963 100644 --- a/activerecord/lib/active_record/fixture_set/table_rows.rb +++ b/activerecord/lib/active_record/fixture_set/table_rows.rb @@ -29,7 +29,6 @@ module ActiveRecord end private - def build_table_rows_from(table_name, fixtures, config) now = config.default_timezone == :utc ? Time.now.utc : Time.now diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 327121a2a2..046ed0e95c 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -464,7 +464,6 @@ module ActiveRecord end private - def insert_class(class_names, name, klass) # We only want to deal with AR objects. if klass && klass < ActiveRecord::Base @@ -570,7 +569,6 @@ module ActiveRecord end private - def read_and_insert(fixtures_directory, fixture_files, class_names, connection) # :nodoc: fixtures_map = {} fixture_sets = fixture_files.map do |fixture_set_name| @@ -661,7 +659,6 @@ module ActiveRecord end private - def model_class=(class_name) if class_name.is_a?(Class) # TODO: Should be an AR::Base type class, or any? @model_class = class_name diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb index 9570bc6f86..5ca48fa18c 100644 --- a/activerecord/lib/active_record/inheritance.rb +++ b/activerecord/lib/active_record/inheritance.rb @@ -176,7 +176,6 @@ module ActiveRecord end protected - # Returns the class type of the record using the current module as a prefix. So descendants of # MyApp::Business::Account would appear as MyApp::Business::AccountSubclass. def compute_type(type_name) @@ -208,7 +207,6 @@ module ActiveRecord end private - # Called by +instantiate+ to decide which class to use for a new # record instance. For single-table inheritance, we check the record # for a +type+ column and return the corresponding class. @@ -272,7 +270,6 @@ module ActiveRecord end private - def initialize_internals_callback super ensure_proper_type diff --git a/activerecord/lib/active_record/internal_metadata.rb b/activerecord/lib/active_record/internal_metadata.rb index e6166581f1..8f3c6d0ee3 100644 --- a/activerecord/lib/active_record/internal_metadata.rb +++ b/activerecord/lib/active_record/internal_metadata.rb @@ -28,10 +28,6 @@ module ActiveRecord where(key: key).pluck(:value).first end - def table_exists? - connection.table_exists?(table_name) - end - # Creates an internal metadata table with columns +key+ and +value+ def create_table unless table_exists? diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb index 6711ee9bf4..c2a083bf3b 100644 --- a/activerecord/lib/active_record/locking/optimistic.rb +++ b/activerecord/lib/active_record/locking/optimistic.rb @@ -156,7 +156,6 @@ module ActiveRecord end private - # We need to apply this decorator here, rather than on module inclusion. The closure # created by the matcher would otherwise evaluate for `ActiveRecord::Base`, not the # sub class being decorated. As such, changes to `lock_optimistically`, or diff --git a/activerecord/lib/active_record/middleware/database_selector.rb b/activerecord/lib/active_record/middleware/database_selector.rb index 93a1a39c3e..7374107048 100644 --- a/activerecord/lib/active_record/middleware/database_selector.rb +++ b/activerecord/lib/active_record/middleware/database_selector.rb @@ -55,7 +55,6 @@ module ActiveRecord end private - def select_database(request, &blk) context = context_klass.call(request) resolver = resolver_klass.call(context, options) diff --git a/activerecord/lib/active_record/middleware/database_selector/resolver.rb b/activerecord/lib/active_record/middleware/database_selector/resolver.rb index 80b8cd7cae..3eb1039c50 100644 --- a/activerecord/lib/active_record/middleware/database_selector/resolver.rb +++ b/activerecord/lib/active_record/middleware/database_selector/resolver.rb @@ -44,10 +44,9 @@ module ActiveRecord end private - def read_from_primary(&blk) - ActiveRecord::Base.connection.while_preventing_writes do - ActiveRecord::Base.connected_to(role: ActiveRecord::Base.writing_role) do + ActiveRecord::Base.connected_to(role: ActiveRecord::Base.writing_role) do + ActiveRecord::Base.connection_handler.while_preventing_writes do instrumenter.instrument("database_selector.active_record.read_from_primary") do yield end diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index f20edbeb93..7edfec9903 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -494,9 +494,9 @@ module ActiveRecord # This migration will create the horses table for you on the way up, and # automatically figure out how to drop the table on the way down. # - # Some commands like +remove_column+ cannot be reversed. If you care to - # define how to move up and down in these cases, you should define the +up+ - # and +down+ methods as before. + # Some commands cannot be reversed. If you care to define how to move up + # and down in these cases, you should define the +up+ and +down+ methods + # as before. # # If a command cannot be reversed, an # <tt>ActiveRecord::IrreversibleMigration</tt> exception will be raised when @@ -568,7 +568,6 @@ module ActiveRecord end private - def connection ActiveRecord::Base.connection end @@ -885,13 +884,14 @@ module ActiveRecord def copy(destination, sources, options = {}) copied = [] + schema_migration = options[:schema_migration] || ActiveRecord::SchemaMigration FileUtils.mkdir_p(destination) unless File.exist?(destination) - destination_migrations = ActiveRecord::MigrationContext.new(destination).migrations + destination_migrations = ActiveRecord::MigrationContext.new(destination, schema_migration).migrations last = destination_migrations.last sources.each do |scope, path| - source_migrations = ActiveRecord::MigrationContext.new(path).migrations + source_migrations = ActiveRecord::MigrationContext.new(path, schema_migration).migrations source_migrations.each do |migration| source = File.binread(migration.filename) @@ -992,7 +992,6 @@ module ActiveRecord delegate :migrate, :announce, :write, :disable_ddl_transaction, to: :migration private - def migration @migration ||= load_migration end @@ -1014,10 +1013,11 @@ module ActiveRecord end class MigrationContext #:nodoc: - attr_reader :migrations_paths + attr_reader :migrations_paths, :schema_migration - def initialize(migrations_paths) + def initialize(migrations_paths, schema_migration) @migrations_paths = migrations_paths + @schema_migration = schema_migration end def migrate(target_version = nil, &block) @@ -1048,7 +1048,7 @@ module ActiveRecord migrations end - Migrator.new(:up, selected_migrations, target_version).migrate + Migrator.new(:up, selected_migrations, schema_migration, target_version).migrate end def down(target_version = nil) @@ -1058,20 +1058,20 @@ module ActiveRecord migrations end - Migrator.new(:down, selected_migrations, target_version).migrate + Migrator.new(:down, selected_migrations, schema_migration, target_version).migrate end def run(direction, target_version) - Migrator.new(direction, migrations, target_version).run + Migrator.new(direction, migrations, schema_migration, target_version).run end def open - Migrator.new(:up, migrations, nil) + Migrator.new(:up, migrations, schema_migration) end def get_all_versions - if SchemaMigration.table_exists? - SchemaMigration.all_versions.map(&:to_i) + if schema_migration.table_exists? + schema_migration.all_versions.map(&:to_i) else [] end @@ -1108,12 +1108,12 @@ module ActiveRecord end def migrations_status - db_list = ActiveRecord::SchemaMigration.normalized_versions + db_list = schema_migration.normalized_versions file_list = migration_files.map do |file| version, name, scope = parse_migration_filename(file) raise IllegalMigrationNameError.new(file) unless version - version = ActiveRecord::SchemaMigration.normalize_migration_number(version) + version = schema_migration.normalize_migration_number(version) status = db_list.delete(version) ? "up" : "down" [status, version, (name + scope).humanize] end.compact @@ -1153,7 +1153,7 @@ module ActiveRecord end def move(direction, steps) - migrator = Migrator.new(direction, migrations) + migrator = Migrator.new(direction, migrations, schema_migration) if current_version != 0 && !migrator.current_migration raise UnknownMigrationVersionError.new(current_version) @@ -1172,27 +1172,28 @@ module ActiveRecord end end - class Migrator #:nodoc: + class Migrator # :nodoc: class << self attr_accessor :migrations_paths # For cases where a table doesn't exist like loading from schema cache def current_version - MigrationContext.new(migrations_paths).current_version + MigrationContext.new(migrations_paths, SchemaMigration).current_version end end self.migrations_paths = ["db/migrate"] - def initialize(direction, migrations, target_version = nil) + def initialize(direction, migrations, schema_migration, target_version = nil) @direction = direction @target_version = target_version @migrated_versions = nil @migrations = migrations + @schema_migration = schema_migration validate(@migrations) - ActiveRecord::SchemaMigration.create_table + @schema_migration.create_table ActiveRecord::InternalMetadata.create_table end @@ -1246,11 +1247,10 @@ module ActiveRecord end def load_migrated - @migrated_versions = Set.new(Base.connection.migration_context.get_all_versions) + @migrated_versions = Set.new(@schema_migration.all_versions.map(&:to_i)) end private - # Used for running a specific migration. def run_without_lock migration = migrations.detect { |m| m.version == @target_version } @@ -1330,10 +1330,10 @@ module ActiveRecord def record_version_state_after_migrating(version) if down? migrated.delete(version) - ActiveRecord::SchemaMigration.delete_by(version: version.to_s) + @schema_migration.delete_by(version: version.to_s) else migrated << version - ActiveRecord::SchemaMigration.create!(version: version.to_s) + @schema_migration.create!(version: version.to_s) end end diff --git a/activerecord/lib/active_record/migration/command_recorder.rb b/activerecord/lib/active_record/migration/command_recorder.rb index efed4b0e26..67172ef395 100644 --- a/activerecord/lib/active_record/migration/command_recorder.rb +++ b/activerecord/lib/active_record/migration/command_recorder.rb @@ -118,7 +118,6 @@ module ActiveRecord end private - module StraightReversions # :nodoc: private { diff --git a/activerecord/lib/active_record/migration/join_table.rb b/activerecord/lib/active_record/migration/join_table.rb index 9abb289bb0..45169617c1 100644 --- a/activerecord/lib/active_record/migration/join_table.rb +++ b/activerecord/lib/active_record/migration/join_table.rb @@ -4,7 +4,6 @@ module ActiveRecord class Migration module JoinTable #:nodoc: private - def find_join_table_name(table_1, table_2, options = {}) options.delete(:table_name) || join_table_name(table_1, table_2) end diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb index 55fc58e339..18f19af6be 100644 --- a/activerecord/lib/active_record/model_schema.rb +++ b/activerecord/lib/active_record/model_schema.rb @@ -456,13 +456,11 @@ module ActiveRecord end protected - def initialize_load_schema_monitor @load_schema_monitor = Monitor.new end private - def inherited(child_class) super child_class.initialize_load_schema_monitor @@ -484,6 +482,9 @@ module ActiveRecord end def load_schema! + unless table_name + raise ActiveRecord::TableNotSpecified, "#{self} has no table configured. Set one with #{self}.table_name=" + end @columns_hash = connection.schema_cache.columns_hash(table_name).except(*ignored_columns) @columns_hash.each do |name, column| define_attribute( diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb index 8b9098df6c..ab107742ed 100644 --- a/activerecord/lib/active_record/nested_attributes.rb +++ b/activerecord/lib/active_record/nested_attributes.rb @@ -2,7 +2,6 @@ require "active_support/core_ext/hash/except" require "active_support/core_ext/module/redefine_method" -require "active_support/core_ext/object/try" require "active_support/core_ext/hash/indifferent_access" module ActiveRecord @@ -354,7 +353,6 @@ module ActiveRecord end private - # Generates a writer method for this association. Serves as a point for # accessing the objects in the association. For example, this method # could generate the following: @@ -386,7 +384,6 @@ module ActiveRecord end private - # Attribute hash keys that should not be assigned as normal attributes. # These hash keys are nested attributes implementation details. UNASSIGNABLE_KEYS = %w( id _destroy ) diff --git a/activerecord/lib/active_record/null_relation.rb b/activerecord/lib/active_record/null_relation.rb index cf0de0fdeb..bee5b5f24a 100644 --- a/activerecord/lib/active_record/null_relation.rb +++ b/activerecord/lib/active_record/null_relation.rb @@ -60,7 +60,6 @@ module ActiveRecord end private - def exec_queries @records = [].freeze end diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index b7bc4b3b8e..323b01ab2d 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -865,7 +865,6 @@ module ActiveRecord end private - # A hook to be overridden by association modules. def destroy_associations end diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb index a1d7c893bf..d5375390c7 100644 --- a/activerecord/lib/active_record/railtie.rb +++ b/activerecord/lib/active_record/railtie.rb @@ -134,7 +134,6 @@ end_error cache = YAML.load(File.read(filename)) if cache.version == current_version - connection.schema_cache = cache connection_pool.schema_cache = cache.dup else warn "Ignoring db/schema_cache.yml because it has expired. The current schema version is #{current_version}, but the one in the cache is #{cache.version}." diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index e0bc5180c0..4d9acc911b 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -2,6 +2,8 @@ require "active_record" +databases = ActiveRecord::Tasks::DatabaseTasks.setup_initial_database_yaml + db_namespace = namespace :db do desc "Set the environment value for the database" task "environment:set" => :load_config do @@ -23,7 +25,7 @@ db_namespace = namespace :db do ActiveRecord::Tasks::DatabaseTasks.create_all end - ActiveRecord::Tasks::DatabaseTasks.for_each do |spec_name| + ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |spec_name| desc "Create #{spec_name} database for current environment" task spec_name => :load_config do db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name) @@ -42,7 +44,7 @@ db_namespace = namespace :db do ActiveRecord::Tasks::DatabaseTasks.drop_all end - ActiveRecord::Tasks::DatabaseTasks.for_each do |spec_name| + ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |spec_name| desc "Drop #{spec_name} database for current environment" task spec_name => [:load_config, :check_protected_environments] do db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name) @@ -101,7 +103,7 @@ db_namespace = namespace :db do end namespace :migrate do - ActiveRecord::Tasks::DatabaseTasks.for_each do |spec_name| + ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |spec_name| desc "Migrate #{spec_name} database for current environment" task spec_name => :load_config do db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name) @@ -110,7 +112,7 @@ db_namespace = namespace :db do end end - # desc 'Rollbacks the database one migration and re migrate up (options: STEP=x, VERSION=x).' + desc "Rolls back the database one migration and re-migrates up (options: STEP=x, VERSION=x)." task redo: :load_config do raise "Empty VERSION provided" if ENV["VERSION"] && ENV["VERSION"].empty? @@ -126,7 +128,7 @@ db_namespace = namespace :db do # desc 'Resets your database using your migrations for the current environment' task reset: ["db:drop", "db:create", "db:migrate"] - # desc 'Runs the "up" for a given migration VERSION.' + desc 'Runs the "up" for a given migration VERSION.' task up: :load_config do ActiveRecord::Tasks::DatabaseTasks.raise_for_multi_db(command: "db:migrate:up") @@ -142,7 +144,7 @@ db_namespace = namespace :db do end namespace :up do - ActiveRecord::Tasks::DatabaseTasks.for_each do |spec_name| + ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |spec_name| task spec_name => :load_config do raise "VERSION is required" if !ENV["VERSION"] || ENV["VERSION"].empty? @@ -160,7 +162,7 @@ db_namespace = namespace :db do end end - # desc 'Runs the "down" for a given migration VERSION.' + desc 'Runs the "down" for a given migration VERSION.' task down: :load_config do ActiveRecord::Tasks::DatabaseTasks.raise_for_multi_db(command: "db:migrate:down") @@ -176,7 +178,7 @@ db_namespace = namespace :db do end namespace :down do - ActiveRecord::Tasks::DatabaseTasks.for_each do |spec_name| + ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |spec_name| task spec_name => :load_config do raise "VERSION is required" if !ENV["VERSION"] || ENV["VERSION"].empty? @@ -203,7 +205,7 @@ db_namespace = namespace :db do end namespace :status do - ActiveRecord::Tasks::DatabaseTasks.for_each do |spec_name| + ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |spec_name| desc "Display status of migrations for #{spec_name} database" task spec_name => :load_config do db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name) @@ -228,7 +230,7 @@ db_namespace = namespace :db do db_namespace["_dump"].invoke end - # desc 'Drops and recreates the database from db/schema.rb for the current environment and loads the seeds.' + desc "Drops and recreates the database from db/schema.rb for the current environment and loads the seeds." task reset: [ "db:drop", "db:setup" ] # desc "Retrieves the charset for the current environment's database" @@ -250,7 +252,11 @@ db_namespace = namespace :db do # desc "Raises an error if there are pending migrations" task abort_if_pending_migrations: :load_config do - pending_migrations = ActiveRecord::Base.connection.migration_context.open.pending_migrations + pending_migrations = ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).flat_map do |db_config| + ActiveRecord::Base.establish_connection(db_config.config) + + ActiveRecord::Base.connection.migration_context.open.pending_migrations + end if pending_migrations.any? puts "You have #{pending_migrations.size} pending #{pending_migrations.size > 1 ? 'migrations:' : 'migration:'}" @@ -261,17 +267,57 @@ db_namespace = namespace :db do end end + namespace :abort_if_pending_migrations do + ActiveRecord::Tasks::DatabaseTasks.for_each(databases) do |spec_name| + # desc "Raises an error if there are pending migrations for #{spec_name} database" + task spec_name => :load_config do + db_config = ActiveRecord::Base.configurations.configs_for(env_name: Rails.env, spec_name: spec_name) + ActiveRecord::Base.establish_connection(db_config.config) + + pending_migrations = ActiveRecord::Base.connection.migration_context.open.pending_migrations + + if pending_migrations.any? + puts "You have #{pending_migrations.size} pending #{pending_migrations.size > 1 ? 'migrations:' : 'migration:'}" + pending_migrations.each do |pending_migration| + puts " %4d %s" % [pending_migration.version, pending_migration.name] + end + abort %{Run `rails db:migrate:#{spec_name}` to update your database then try again.} + end + end + end + end + desc "Creates the database, loads the schema, and initializes with the seed data (use db:reset to also drop the database first)" task setup: ["db:schema:load_if_ruby", "db:structure:load_if_sql", :seed] desc "Runs setup if database does not exist, or runs migrations if it does" task prepare: :load_config do + seed = false + ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config| ActiveRecord::Base.establish_connection(db_config.config) - db_namespace["migrate"].invoke + + # Skipped when no database + ActiveRecord::Tasks::DatabaseTasks.migrate + if ActiveRecord::Base.dump_schema_after_migration + ActiveRecord::Tasks::DatabaseTasks.dump_schema(db_config.config, ActiveRecord::Base.schema_format, db_config.spec_name) + end + rescue ActiveRecord::NoDatabaseError - db_namespace["setup"].invoke + ActiveRecord::Tasks::DatabaseTasks.create_current(db_config.env_name, db_config.spec_name) + ActiveRecord::Tasks::DatabaseTasks.load_schema( + db_config.config, + ActiveRecord::Base.schema_format, + nil, + db_config.env_name, + db_config.spec_name + ) + + seed = true end + + ActiveRecord::Base.establish_connection + ActiveRecord::Tasks::DatabaseTasks.load_seed if seed end desc "Loads the seed data from db/seeds.rb" @@ -336,13 +382,9 @@ db_namespace = namespace :db do namespace :schema do desc "Creates a db/schema.rb file that is portable against any DB supported by Active Record" task dump: :load_config do - require "active_record/schema_dumper" ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config| - filename = ActiveRecord::Tasks::DatabaseTasks.dump_filename(db_config.spec_name, :ruby) - File.open(filename, "w:utf-8") do |file| - ActiveRecord::Base.establish_connection(db_config.config) - ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file) - end + ActiveRecord::Base.establish_connection(db_config.config) + ActiveRecord::Tasks::DatabaseTasks.dump_schema(db_config.config, :ruby, db_config.spec_name) end db_namespace["schema:dump"].reenable @@ -385,14 +427,7 @@ db_namespace = namespace :db do task dump: :load_config do ActiveRecord::Base.configurations.configs_for(env_name: ActiveRecord::Tasks::DatabaseTasks.env).each do |db_config| ActiveRecord::Base.establish_connection(db_config.config) - filename = ActiveRecord::Tasks::DatabaseTasks.dump_filename(db_config.spec_name, :sql) - ActiveRecord::Tasks::DatabaseTasks.structure_dump(db_config.config, filename) - if ActiveRecord::SchemaMigration.table_exists? - File.open(filename, "a") do |f| - f.puts ActiveRecord::Base.connection.dump_schema_information - f.print "\n" - end - end + ActiveRecord::Tasks::DatabaseTasks.dump_schema(db_config.config, :sql, db_config.spec_name) end db_namespace["structure:dump"].reenable diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb index eefda2b8f4..cbfa60d4d9 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -590,7 +590,6 @@ module ActiveRecord end private - def calculate_constructable(macro, options) true end @@ -704,7 +703,6 @@ module ActiveRecord end private - def calculate_constructable(macro, options) !options[:through] end diff --git a/activerecord/lib/active_record/relation/batches.rb b/activerecord/lib/active_record/relation/batches.rb index 9c579843b1..30b8edd0bd 100644 --- a/activerecord/lib/active_record/relation/batches.rb +++ b/activerecord/lib/active_record/relation/batches.rb @@ -258,7 +258,6 @@ module ActiveRecord end private - def apply_limits(relation, start, finish) relation = apply_start_limit(relation, start) if start relation = apply_finish_limit(relation, finish) if finish diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index 0be9ba7d7b..0a14a33c1d 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -340,7 +340,7 @@ module ActiveRecord } relation = except(:group).distinct!(false) - relation.group_values = group_aliases + relation.group_values = group_fields relation.select_values = select_values calculated_data = skip_query_cache_if_necessary { @klass.connection.select_all(relation.arel, nil) } diff --git a/activerecord/lib/active_record/relation/delegation.rb b/activerecord/lib/active_record/relation/delegation.rb index d59331053e..2f61c05eca 100644 --- a/activerecord/lib/active_record/relation/delegation.rb +++ b/activerecord/lib/active_record/relation/delegation.rb @@ -99,7 +99,6 @@ module ActiveRecord end private - def method_missing(method, *args, &block) if @klass.respond_to?(method) @klass.generate_relation_method(method) @@ -116,7 +115,6 @@ module ActiveRecord end private - def relation_class_for(klass) klass.relation_delegate_class(self) end diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 9c7ac80447..1dbf4808fd 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -346,7 +346,6 @@ module ActiveRecord end private - def offset_index offset_value || 0 end @@ -355,7 +354,7 @@ module ActiveRecord conditions = sanitize_forbidden_attributes(conditions) if distinct_value && offset_value - relation = limit(1) + relation = except(:order).limit!(1) else relation = except(:select, :distinct, :order)._select!(ONE_AS_ONE).limit!(1) end diff --git a/activerecord/lib/active_record/relation/merger.rb b/activerecord/lib/active_record/relation/merger.rb index 84fe424ef0..e1735c0522 100644 --- a/activerecord/lib/active_record/relation/merger.rb +++ b/activerecord/lib/active_record/relation/merger.rb @@ -89,7 +89,6 @@ module ActiveRecord end private - def merge_preloads return if other.preload_values.empty? && other.includes_values.empty? diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 464274fb24..6957ba052b 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -952,7 +952,7 @@ module ActiveRecord def optimizer_hints!(*args) # :nodoc: args.flatten! - self.optimizer_hints_values += args + self.optimizer_hints_values |= args self end @@ -1159,8 +1159,9 @@ module ActiveRecord columns.flat_map do |field| case field when Symbol - field = field.to_s - arel_column(field, &connection.method(:quote_table_name)) + arel_column(field.to_s) do |attr_name| + connection.quote_table_name(attr_name) + end when String arel_column(field, &:itself) when Proc @@ -1247,6 +1248,7 @@ module ActiveRecord end def preprocess_order_args(order_args) + order_args.reject!(&:blank?) order_args.map! do |arg| klass.sanitize_sql_for_order(arg) end @@ -1254,7 +1256,7 @@ module ActiveRecord @klass.disallow_raw_sql!( order_args.flat_map { |a| a.is_a?(Hash) ? a.keys : a }, - permit: AttributeMethods::ClassMethods::COLUMN_NAME_WITH_ORDER + permit: connection.column_name_with_order_matcher ) validate_order_args(order_args) @@ -1267,20 +1269,14 @@ module ActiveRecord order_args.map! do |arg| case arg when Symbol - arg = arg.to_s - arel_column(arg) { - Arel.sql(connection.quote_table_name(arg)) - }.asc + order_column(arg.to_s).asc when Hash arg.map { |field, dir| case field when Arel::Nodes::SqlLiteral field.send(dir.downcase) else - field = field.to_s - arel_column(field) { - Arel.sql(connection.quote_table_name(field)) - }.send(dir.downcase) + order_column(field.to_s).send(dir.downcase) end } else @@ -1289,6 +1285,16 @@ module ActiveRecord end.flatten! end + def order_column(field) + arel_column(field) do |attr_name| + if attr_name == "count" && !group_values.empty? + arel_attribute(attr_name) + else + Arel.sql(connection.quote_table_name(attr_name)) + end + end + end + # Checks to make sure that the arguments are not blank. Note that if some # blank-like object were initially passed into the query method, then this # method will not raise an error. diff --git a/activerecord/lib/active_record/relation/spawn_methods.rb b/activerecord/lib/active_record/relation/spawn_methods.rb index efc4b447aa..3f6dd50139 100644 --- a/activerecord/lib/active_record/relation/spawn_methods.rb +++ b/activerecord/lib/active_record/relation/spawn_methods.rb @@ -67,7 +67,6 @@ module ActiveRecord end private - def relation_with(values) result = Relation.create(klass, values: values) result.extend(*extending_values) if extending_values.any? diff --git a/activerecord/lib/active_record/relation/where_clause.rb b/activerecord/lib/active_record/relation/where_clause.rb index b91b135867..8fae380b0a 100644 --- a/activerecord/lib/active_record/relation/where_clause.rb +++ b/activerecord/lib/active_record/relation/where_clause.rb @@ -87,7 +87,6 @@ module ActiveRecord end protected - attr_reader :predicates def referenced_columns diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb index da6d10b6ec..3b615f29a3 100644 --- a/activerecord/lib/active_record/result.rb +++ b/activerecord/lib/active_record/result.rb @@ -132,7 +132,6 @@ module ActiveRecord end private - def column_type(name, type_overrides = {}) type_overrides.fetch(name) do column_types.fetch(name, Type.default_value) diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb index 750766714d..b16cbb0f84 100644 --- a/activerecord/lib/active_record/sanitization.rb +++ b/activerecord/lib/active_record/sanitization.rb @@ -61,8 +61,9 @@ module ActiveRecord # # => "id ASC" def sanitize_sql_for_order(condition) if condition.is_a?(Array) && condition.first.to_s.include?("?") - disallow_raw_sql!([condition.first], - permit: AttributeMethods::ClassMethods::COLUMN_NAME_WITH_ORDER + disallow_raw_sql!( + [condition.first], + permit: connection.column_name_with_order_matcher ) # Ensure we aren't dealing with a subclass of String that might @@ -133,6 +134,33 @@ module ActiveRecord end end + def disallow_raw_sql!(args, permit: connection.column_name_matcher) # :nodoc: + unexpected = nil + args.each do |arg| + next if arg.is_a?(Symbol) || Arel.arel_node?(arg) || permit.match?(arg.to_s) + (unexpected ||= []) << arg + end + + return unless unexpected + + if allow_unsafe_raw_sql == :deprecated + ActiveSupport::Deprecation.warn( + "Dangerous query method (method whose arguments are used as raw " \ + "SQL) called with non-attribute argument(s): " \ + "#{unexpected.map(&:inspect).join(", ")}. Non-attribute " \ + "arguments will be disallowed in Rails 6.1. This method should " \ + "not be called with user-provided values, such as request " \ + "parameters or model attributes. Known-safe values can be passed " \ + "by wrapping them in Arel.sql()." + ) + else + raise(ActiveRecord::UnknownAttributeReference, + "Query method called with non-attribute argument(s): " + + unexpected.map(&:inspect).join(", ") + ) + end + end + private def replace_bind_variables(statement, values) raise_if_bind_arity_mismatch(statement, statement.count("?"), values.size) diff --git a/activerecord/lib/active_record/schema.rb b/activerecord/lib/active_record/schema.rb index 76bf53387d..aba25fb375 100644 --- a/activerecord/lib/active_record/schema.rb +++ b/activerecord/lib/active_record/schema.rb @@ -50,7 +50,7 @@ module ActiveRecord instance_eval(&block) if info[:version].present? - ActiveRecord::SchemaMigration.create_table + connection.schema_migration.create_table connection.assume_migrated_upto_version(info[:version]) end diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index 2f7cc07221..f4b1f536b3 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -146,7 +146,11 @@ HEADER raise StandardError, "Unknown type '#{column.sql_type}' for column '#{column.name}'" unless @connection.valid_type?(column.type) next if column.name == pk type, colspec = column_spec(column) - tbl.print " t.#{type} #{column.name.inspect}" + if type.is_a?(Symbol) + tbl.print " t.#{type} #{column.name.inspect}" + else + tbl.print " t.column #{column.name.inspect}, #{type.inspect}" + end tbl.print ", #{format_colspec(colspec)}" if colspec.present? tbl.puts end diff --git a/activerecord/lib/active_record/schema_migration.rb b/activerecord/lib/active_record/schema_migration.rb index 74547de862..dec7fee986 100644 --- a/activerecord/lib/active_record/schema_migration.rb +++ b/activerecord/lib/active_record/schema_migration.rb @@ -22,10 +22,6 @@ module ActiveRecord "#{table_name_prefix}#{schema_migrations_table_name}#{table_name_suffix}" end - def table_exists? - connection.table_exists?(table_name) - end - def create_table unless table_exists? version_options = connection.internal_string_options_for_primary_key diff --git a/activerecord/lib/active_record/scoping.rb b/activerecord/lib/active_record/scoping.rb index 35e9dcbffc..62c7988bd8 100644 --- a/activerecord/lib/active_record/scoping.rb +++ b/activerecord/lib/active_record/scoping.rb @@ -95,7 +95,6 @@ module ActiveRecord end private - def raise_invalid_scope_type!(scope_type) if !VALID_SCOPE_TYPES.include?(scope_type) raise ArgumentError, "Invalid scope type '#{scope_type}' sent to the registry. Scope types must be included in VALID_SCOPE_TYPES" diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb index 87bcfd5181..151eef362b 100644 --- a/activerecord/lib/active_record/scoping/default.rb +++ b/activerecord/lib/active_record/scoping/default.rb @@ -44,7 +44,6 @@ module ActiveRecord end private - # Use this macro in your model to set a default scope for all operations on # the model. # diff --git a/activerecord/lib/active_record/scoping/named.rb b/activerecord/lib/active_record/scoping/named.rb index cd9801b7a0..7baef99e83 100644 --- a/activerecord/lib/active_record/scoping/named.rb +++ b/activerecord/lib/active_record/scoping/named.rb @@ -204,7 +204,6 @@ module ActiveRecord end private - def valid_scope_name?(name) if respond_to?(name, true) && logger logger.warn "Creating scope :#{name}. " \ diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb index c79ed8db60..5d1ce19829 100644 --- a/activerecord/lib/active_record/tasks/database_tasks.rb +++ b/activerecord/lib/active_record/tasks/database_tasks.rb @@ -141,10 +141,21 @@ module ActiveRecord end end - def for_each + def setup_initial_database_yaml + return {} unless defined?(Rails) + + begin + Rails.application.config.load_database_yaml + rescue + $stderr.puts "Rails couldn't infer whether you are using multiple databases from your database.yml and can't generate the tasks for the non-primary databases. If you'd like to use this feature, please simplify your ERB." + + {} + end + end + + def for_each(databases) return {} unless defined?(Rails) - databases = Rails.application.config.load_database_yaml database_configs = ActiveRecord::DatabaseConfigurations.new(databases).configs_for(env_name: Rails.env) # if this is a single database application we don't want tasks for each primary database @@ -169,8 +180,8 @@ module ActiveRecord end end - def create_current(environment = env) - each_current_configuration(environment) { |configuration| + def create_current(environment = env, spec_name = nil) + each_current_configuration(environment, spec_name) { |configuration| create configuration } ActiveRecord::Base.establish_connection(environment.to_sym) @@ -200,9 +211,10 @@ module ActiveRecord def truncate_tables(configuration) ActiveRecord::Base.connected_to(database: { truncation: configuration }) do - table_names = ActiveRecord::Base.connection.tables + conn = ActiveRecord::Base.connection + table_names = conn.tables table_names -= [ - SchemaMigration.table_name, + conn.schema_migration.table_name, InternalMetadata.table_name ] @@ -233,7 +245,7 @@ module ActiveRecord end def migrate_status - unless ActiveRecord::SchemaMigration.table_exists? + unless ActiveRecord::Base.connection.schema_migration.table_exists? Kernel.abort "Schema migrations table does not exist yet." end @@ -325,6 +337,27 @@ module ActiveRecord Migration.verbose = verbose_was end + def dump_schema(configuration, format = ActiveRecord::Base.schema_format, spec_name = "primary") # :nodoc: + require "active_record/schema_dumper" + filename = dump_filename(spec_name, format) + connection = ActiveRecord::Base.connection + + case format + when :ruby + File.open(filename, "w:utf-8") do |file| + ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file) + end + when :sql + structure_dump(configuration, filename) + if connection.schema_migration.table_exists? + File.open(filename, "a") do |f| + f.puts connection.dump_schema_information + f.print "\n" + end + end + end + end + def schema_file(format = ActiveRecord::Base.schema_format) File.join(db_dir, schema_file_type(format)) end @@ -406,12 +439,14 @@ module ActiveRecord task.is_a?(String) ? task.constantize : task end - def each_current_configuration(environment) + def each_current_configuration(environment, spec_name = nil) environments = [environment] environments << "test" if environment == "development" environments.each do |env| ActiveRecord::Base.configurations.configs_for(env_name: env).each do |db_config| + next if spec_name && spec_name != db_config.spec_name + yield db_config.config, db_config.spec_name, env end end diff --git a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb index 1c1b29b5e1..a7e04007a9 100644 --- a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb @@ -3,6 +3,8 @@ module ActiveRecord module Tasks # :nodoc: class MySQLDatabaseTasks # :nodoc: + ER_DB_CREATE_EXISTS = 1007 + delegate :connection, :establish_connection, to: ActiveRecord::Base def initialize(configuration) @@ -14,7 +16,7 @@ module ActiveRecord connection.create_database configuration["database"], creation_options establish_connection configuration rescue ActiveRecord::StatementInvalid => error - if error.message.include?("database exists") + if error.cause.error_number == ER_DB_CREATE_EXISTS raise DatabaseAlreadyExists else raise @@ -67,7 +69,6 @@ module ActiveRecord end private - attr_reader :configuration def configuration_without_database diff --git a/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb index 8acb11f75f..626ffdfdf9 100644 --- a/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/postgresql_database_tasks.rb @@ -89,7 +89,6 @@ module ActiveRecord end private - attr_reader :configuration def encoding diff --git a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb index a82cea80ca..f67a3498b6 100644 --- a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb @@ -59,7 +59,6 @@ module ActiveRecord end private - attr_reader :configuration, :root def run_cmd(cmd, args, out) diff --git a/activerecord/lib/active_record/test_fixtures.rb b/activerecord/lib/active_record/test_fixtures.rb index 8c60d71669..1d6fef1eb9 100644 --- a/activerecord/lib/active_record/test_fixtures.rb +++ b/activerecord/lib/active_record/test_fixtures.rb @@ -179,7 +179,6 @@ module ActiveRecord end private - # Shares the writing connection pool with connections on # other handlers. # diff --git a/activerecord/lib/active_record/timestamp.rb b/activerecord/lib/active_record/timestamp.rb index a5862ae06b..c883d368b5 100644 --- a/activerecord/lib/active_record/timestamp.rb +++ b/activerecord/lib/active_record/timestamp.rb @@ -96,7 +96,6 @@ module ActiveRecord end private - def _create_record if record_timestamps current_time = current_time_from_proper_timezone diff --git a/activerecord/lib/active_record/touch_later.rb b/activerecord/lib/active_record/touch_later.rb index bc63c8d987..3981bd46ad 100644 --- a/activerecord/lib/active_record/touch_later.rb +++ b/activerecord/lib/active_record/touch_later.rb @@ -36,7 +36,6 @@ module ActiveRecord end private - def surreptitiously_touch(attrs) attrs.each { |attr| write_attribute attr, @_touch_time } clear_attribute_changes attrs diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb index cbb970ac98..5113e08e8e 100644 --- a/activerecord/lib/active_record/transactions.rb +++ b/activerecord/lib/active_record/transactions.rb @@ -282,7 +282,6 @@ module ActiveRecord end private - def set_options_for_callbacks!(args, enforced_options = {}) options = args.extract_options!.merge!(enforced_options) args << options diff --git a/activerecord/lib/active_record/type.rb b/activerecord/lib/active_record/type.rb index 03d00006b7..4c1ef1a7e4 100644 --- a/activerecord/lib/active_record/type.rb +++ b/activerecord/lib/active_record/type.rb @@ -47,7 +47,6 @@ module ActiveRecord end private - def current_adapter_name ActiveRecord::Base.connection.adapter_name.downcase.to_sym end diff --git a/activerecord/lib/active_record/type/adapter_specific_registry.rb b/activerecord/lib/active_record/type/adapter_specific_registry.rb index b300fdfa05..c8c16635b1 100644 --- a/activerecord/lib/active_record/type/adapter_specific_registry.rb +++ b/activerecord/lib/active_record/type/adapter_specific_registry.rb @@ -11,7 +11,6 @@ module ActiveRecord end private - def registration_klass Registration end @@ -53,7 +52,6 @@ module ActiveRecord end protected - attr_reader :name, :block, :adapter, :override def priority @@ -72,7 +70,6 @@ module ActiveRecord end private - def matches_adapter?(adapter: nil, **) (self.adapter.nil? || adapter == self.adapter) end diff --git a/activerecord/lib/active_record/type/hash_lookup_type_map.rb b/activerecord/lib/active_record/type/hash_lookup_type_map.rb index db9853fbcc..b260464df5 100644 --- a/activerecord/lib/active_record/type/hash_lookup_type_map.rb +++ b/activerecord/lib/active_record/type/hash_lookup_type_map.rb @@ -16,7 +16,6 @@ module ActiveRecord end private - def perform_fetch(type, *args, &block) @mapping.fetch(type, block).call(type, *args) end diff --git a/activerecord/lib/active_record/type/serialized.rb b/activerecord/lib/active_record/type/serialized.rb index 0a2f6cb9fb..a34b2fe702 100644 --- a/activerecord/lib/active_record/type/serialized.rb +++ b/activerecord/lib/active_record/type/serialized.rb @@ -56,7 +56,6 @@ module ActiveRecord end private - def default_value?(value) value == coder.load(nil) end diff --git a/activerecord/lib/active_record/type/type_map.rb b/activerecord/lib/active_record/type/type_map.rb index fc40b460f0..58f25ba075 100644 --- a/activerecord/lib/active_record/type/type_map.rb +++ b/activerecord/lib/active_record/type/type_map.rb @@ -45,7 +45,6 @@ module ActiveRecord end private - def perform_fetch(lookup_key, *args) matching_pair = @mapping.reverse_each.detect do |key, _| key === lookup_key diff --git a/activerecord/lib/active_record/type/unsigned_integer.rb b/activerecord/lib/active_record/type/unsigned_integer.rb index 4619528f81..535369e630 100644 --- a/activerecord/lib/active_record/type/unsigned_integer.rb +++ b/activerecord/lib/active_record/type/unsigned_integer.rb @@ -4,7 +4,6 @@ module ActiveRecord module Type class UnsignedInteger < ActiveModel::Type::Integer # :nodoc: private - def max_value super * 2 end diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index ca27a3f0ab..23e8d53168 100644 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -71,7 +71,6 @@ module ActiveRecord alias_method :validate, :valid? private - def default_validation_context new_record? ? :create : :update end diff --git a/activerecord/lib/active_record/validations/associated.rb b/activerecord/lib/active_record/validations/associated.rb index 3538aeec22..dc89df4be7 100644 --- a/activerecord/lib/active_record/validations/associated.rb +++ b/activerecord/lib/active_record/validations/associated.rb @@ -10,7 +10,6 @@ module ActiveRecord end private - def valid_object?(record) (record.respond_to?(:marked_for_destruction?) && record.marked_for_destruction?) || record.valid? end diff --git a/activerecord/lib/arel.rb b/activerecord/lib/arel.rb index 361cd915cc..0fc07e1ede 100644 --- a/activerecord/lib/arel.rb +++ b/activerecord/lib/arel.rb @@ -12,7 +12,7 @@ require "arel/math" require "arel/alias_predication" require "arel/order_predications" require "arel/table" -require "arel/attributes" +require "arel/attributes/attribute" require "arel/visitors" require "arel/collectors/sql_string" diff --git a/activerecord/lib/arel/attributes.rb b/activerecord/lib/arel/attributes.rb deleted file mode 100644 index 35d586c948..0000000000 --- a/activerecord/lib/arel/attributes.rb +++ /dev/null @@ -1,22 +0,0 @@ -# frozen_string_literal: true - -require "arel/attributes/attribute" - -module Arel # :nodoc: all - module Attributes - ### - # Factory method to wrap a raw database +column+ to an Arel Attribute. - def self.for(column) - case column.type - when :string, :text, :binary then String - when :integer then Integer - when :float then Float - when :decimal then Decimal - when :date, :datetime, :timestamp, :time then Time - when :boolean then Boolean - else - Undefined - end - end - end -end diff --git a/activerecord/lib/arel/nodes/node.rb b/activerecord/lib/arel/nodes/node.rb index 8086102bde..0416ff58de 100644 --- a/activerecord/lib/arel/nodes/node.rb +++ b/activerecord/lib/arel/nodes/node.rb @@ -6,7 +6,6 @@ module Arel # :nodoc: all # Abstract base class for all AST nodes class Node include Arel::FactoryMethods - include Enumerable ### # Factory method to create a Nodes::Not node that has the recipient of @@ -38,13 +37,6 @@ module Arel # :nodoc: all collector = engine.connection.visitor.accept self, collector collector.value end - - # Iterate through AST, nodes will be yielded depth-first - def each(&block) - return enum_for(:each) unless block_given? - - ::Arel::Visitors::DepthFirst.new(block).accept self - end end end end diff --git a/activerecord/lib/arel/predications.rb b/activerecord/lib/arel/predications.rb index 7dafde4952..895d394363 100644 --- a/activerecord/lib/arel/predications.rb +++ b/activerecord/lib/arel/predications.rb @@ -37,7 +37,7 @@ module Arel # :nodoc: all def between(other) if unboundable?(other.begin) == 1 || unboundable?(other.end) == -1 self.in([]) - elsif open_ended?(other.begin) + elsif other.begin.nil? || open_ended?(other.begin) if other.end.nil? || open_ended?(other.end) not_in([]) elsif other.exclude_end? @@ -85,7 +85,7 @@ Passing a range to `#in` is deprecated. Call `#between`, instead. def not_between(other) if unboundable?(other.begin) == 1 || unboundable?(other.end) == -1 not_in([]) - elsif open_ended?(other.begin) + elsif other.begin.nil? || open_ended?(other.begin) if other.end.nil? || open_ended?(other.end) self.in([]) elsif other.exclude_end? @@ -221,7 +221,6 @@ Passing a range to `#not_in` is deprecated. Call `#not_between`, instead. end private - def grouping_any(method_id, others, *extras) nodes = others.map { |expr| send(method_id, expr, *extras) } Nodes::Grouping.new nodes.inject { |memo, node| diff --git a/activerecord/lib/arel/visitors.rb b/activerecord/lib/arel/visitors.rb index e350f52e65..a1097f6750 100644 --- a/activerecord/lib/arel/visitors.rb +++ b/activerecord/lib/arel/visitors.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true require "arel/visitors/visitor" -require "arel/visitors/depth_first" require "arel/visitors/to_sql" require "arel/visitors/sqlite" require "arel/visitors/postgresql" diff --git a/activerecord/lib/arel/visitors/depth_first.rb b/activerecord/lib/arel/visitors/depth_first.rb deleted file mode 100644 index d696edc507..0000000000 --- a/activerecord/lib/arel/visitors/depth_first.rb +++ /dev/null @@ -1,204 +0,0 @@ -# frozen_string_literal: true - -module Arel # :nodoc: all - module Visitors - class DepthFirst < Arel::Visitors::Visitor - def initialize(block = nil) - @block = block || Proc.new - super() - end - - private - - def visit(o) - super - @block.call o - end - - def unary(o) - visit o.expr - end - alias :visit_Arel_Nodes_Else :unary - alias :visit_Arel_Nodes_Group :unary - alias :visit_Arel_Nodes_Cube :unary - alias :visit_Arel_Nodes_RollUp :unary - alias :visit_Arel_Nodes_GroupingSet :unary - alias :visit_Arel_Nodes_GroupingElement :unary - alias :visit_Arel_Nodes_Grouping :unary - alias :visit_Arel_Nodes_Having :unary - alias :visit_Arel_Nodes_Lateral :unary - alias :visit_Arel_Nodes_Limit :unary - alias :visit_Arel_Nodes_Not :unary - alias :visit_Arel_Nodes_Offset :unary - alias :visit_Arel_Nodes_On :unary - alias :visit_Arel_Nodes_Ordering :unary - alias :visit_Arel_Nodes_Ascending :unary - alias :visit_Arel_Nodes_Descending :unary - alias :visit_Arel_Nodes_UnqualifiedColumn :unary - alias :visit_Arel_Nodes_OptimizerHints :unary - alias :visit_Arel_Nodes_ValuesList :unary - - def function(o) - visit o.expressions - visit o.alias - visit o.distinct - end - alias :visit_Arel_Nodes_Avg :function - alias :visit_Arel_Nodes_Exists :function - alias :visit_Arel_Nodes_Max :function - alias :visit_Arel_Nodes_Min :function - alias :visit_Arel_Nodes_Sum :function - - def visit_Arel_Nodes_NamedFunction(o) - visit o.name - visit o.expressions - visit o.distinct - visit o.alias - end - - def visit_Arel_Nodes_Count(o) - visit o.expressions - visit o.alias - visit o.distinct - end - - def visit_Arel_Nodes_Case(o) - visit o.case - visit o.conditions - visit o.default - end - - def nary(o) - o.children.each { |child| visit child } - end - alias :visit_Arel_Nodes_And :nary - - def binary(o) - visit o.left - visit o.right - end - alias :visit_Arel_Nodes_As :binary - alias :visit_Arel_Nodes_Assignment :binary - alias :visit_Arel_Nodes_Between :binary - alias :visit_Arel_Nodes_Concat :binary - alias :visit_Arel_Nodes_DeleteStatement :binary - alias :visit_Arel_Nodes_DoesNotMatch :binary - alias :visit_Arel_Nodes_Equality :binary - alias :visit_Arel_Nodes_FullOuterJoin :binary - alias :visit_Arel_Nodes_GreaterThan :binary - alias :visit_Arel_Nodes_GreaterThanOrEqual :binary - alias :visit_Arel_Nodes_In :binary - alias :visit_Arel_Nodes_InfixOperation :binary - alias :visit_Arel_Nodes_JoinSource :binary - alias :visit_Arel_Nodes_InnerJoin :binary - alias :visit_Arel_Nodes_LessThan :binary - alias :visit_Arel_Nodes_LessThanOrEqual :binary - alias :visit_Arel_Nodes_Matches :binary - alias :visit_Arel_Nodes_NotEqual :binary - alias :visit_Arel_Nodes_NotIn :binary - alias :visit_Arel_Nodes_NotRegexp :binary - alias :visit_Arel_Nodes_IsNotDistinctFrom :binary - alias :visit_Arel_Nodes_IsDistinctFrom :binary - alias :visit_Arel_Nodes_Or :binary - alias :visit_Arel_Nodes_OuterJoin :binary - alias :visit_Arel_Nodes_Regexp :binary - alias :visit_Arel_Nodes_RightOuterJoin :binary - alias :visit_Arel_Nodes_TableAlias :binary - alias :visit_Arel_Nodes_When :binary - - def visit_Arel_Nodes_StringJoin(o) - visit o.left - end - - def visit_Arel_Attribute(o) - visit o.relation - visit o.name - end - alias :visit_Arel_Attributes_Integer :visit_Arel_Attribute - alias :visit_Arel_Attributes_Float :visit_Arel_Attribute - alias :visit_Arel_Attributes_String :visit_Arel_Attribute - alias :visit_Arel_Attributes_Time :visit_Arel_Attribute - alias :visit_Arel_Attributes_Boolean :visit_Arel_Attribute - alias :visit_Arel_Attributes_Attribute :visit_Arel_Attribute - alias :visit_Arel_Attributes_Decimal :visit_Arel_Attribute - - def visit_Arel_Table(o) - visit o.name - end - - def terminal(o) - end - alias :visit_ActiveSupport_Multibyte_Chars :terminal - alias :visit_ActiveSupport_StringInquirer :terminal - alias :visit_Arel_Nodes_Lock :terminal - alias :visit_Arel_Nodes_Node :terminal - alias :visit_Arel_Nodes_SqlLiteral :terminal - alias :visit_Arel_Nodes_BindParam :terminal - alias :visit_Arel_Nodes_Window :terminal - alias :visit_Arel_Nodes_True :terminal - alias :visit_Arel_Nodes_False :terminal - alias :visit_BigDecimal :terminal - alias :visit_Class :terminal - alias :visit_Date :terminal - alias :visit_DateTime :terminal - alias :visit_FalseClass :terminal - alias :visit_Float :terminal - alias :visit_Integer :terminal - alias :visit_NilClass :terminal - alias :visit_String :terminal - alias :visit_Symbol :terminal - alias :visit_Time :terminal - alias :visit_TrueClass :terminal - - def visit_Arel_Nodes_InsertStatement(o) - visit o.relation - visit o.columns - visit o.values - end - - def visit_Arel_Nodes_SelectCore(o) - visit o.projections - visit o.source - visit o.wheres - visit o.groups - visit o.windows - visit o.havings - end - - def visit_Arel_Nodes_SelectStatement(o) - visit o.cores - visit o.orders - visit o.limit - visit o.lock - visit o.offset - end - - def visit_Arel_Nodes_UpdateStatement(o) - visit o.relation - visit o.values - visit o.wheres - visit o.orders - visit o.limit - end - - def visit_Arel_Nodes_Comment(o) - visit o.values - end - - def visit_Array(o) - o.each { |i| visit i } - end - alias :visit_Set :visit_Array - - def visit_Hash(o) - o.each { |k, v| visit(k); visit(v) } - end - - DISPATCH = dispatch_cache - - def get_dispatch_cache - DISPATCH - end - end - end -end diff --git a/activerecord/lib/arel/visitors/dot.rb b/activerecord/lib/arel/visitors/dot.rb index ecc386de07..c4ea07bcfe 100644 --- a/activerecord/lib/arel/visitors/dot.rb +++ b/activerecord/lib/arel/visitors/dot.rb @@ -31,7 +31,6 @@ module Arel # :nodoc: all end private - def visit_Arel_Nodes_Ordering(o) visit_edge o, "expr" end diff --git a/activerecord/lib/arel/visitors/mssql.rb b/activerecord/lib/arel/visitors/mssql.rb index 8475139870..92eb94f802 100644 --- a/activerecord/lib/arel/visitors/mssql.rb +++ b/activerecord/lib/arel/visitors/mssql.rb @@ -11,7 +11,6 @@ module Arel # :nodoc: all end private - def visit_Arel_Nodes_IsNotDistinctFrom(o, collector) right = o.right diff --git a/activerecord/lib/arel/visitors/oracle.rb b/activerecord/lib/arel/visitors/oracle.rb index f96bf65ee5..aab66301ef 100644 --- a/activerecord/lib/arel/visitors/oracle.rb +++ b/activerecord/lib/arel/visitors/oracle.rb @@ -4,7 +4,6 @@ module Arel # :nodoc: all module Visitors class Oracle < Arel::Visitors::ToSql private - def visit_Arel_Nodes_SelectStatement(o, collector) o = order_hacks(o) diff --git a/activerecord/lib/arel/visitors/oracle12.rb b/activerecord/lib/arel/visitors/oracle12.rb index 6269bc3907..36783243b5 100644 --- a/activerecord/lib/arel/visitors/oracle12.rb +++ b/activerecord/lib/arel/visitors/oracle12.rb @@ -4,7 +4,6 @@ module Arel # :nodoc: all module Visitors class Oracle12 < Arel::Visitors::ToSql private - def visit_Arel_Nodes_SelectStatement(o, collector) # Oracle does not allow LIMIT clause with select for update if o.limit && o.lock diff --git a/activerecord/lib/arel/visitors/postgresql.rb b/activerecord/lib/arel/visitors/postgresql.rb index 8296f1cdc1..d4f21ff93e 100644 --- a/activerecord/lib/arel/visitors/postgresql.rb +++ b/activerecord/lib/arel/visitors/postgresql.rb @@ -4,7 +4,6 @@ module Arel # :nodoc: all module Visitors class PostgreSQL < Arel::Visitors::ToSql private - def visit_Arel_Nodes_Matches(o, collector) op = o.case_sensitive ? " LIKE " : " ILIKE " collector = infix_value o, collector, op diff --git a/activerecord/lib/arel/visitors/sqlite.rb b/activerecord/lib/arel/visitors/sqlite.rb index af6f7e856a..62ec74ad82 100644 --- a/activerecord/lib/arel/visitors/sqlite.rb +++ b/activerecord/lib/arel/visitors/sqlite.rb @@ -4,7 +4,6 @@ module Arel # :nodoc: all module Visitors class SQLite < Arel::Visitors::ToSql private - # Locks are not supported in SQLite def visit_Arel_Nodes_Lock(o, collector) collector diff --git a/activerecord/lib/arel/visitors/to_sql.rb b/activerecord/lib/arel/visitors/to_sql.rb index 4740e6d94f..eff7a0d036 100644 --- a/activerecord/lib/arel/visitors/to_sql.rb +++ b/activerecord/lib/arel/visitors/to_sql.rb @@ -19,7 +19,6 @@ module Arel # :nodoc: all end private - def visit_Arel_Nodes_DeleteStatement(o, collector) o = prepare_delete_statement(o) @@ -52,10 +51,14 @@ module Arel # :nodoc: all def visit_Arel_Nodes_InsertStatement(o, collector) collector << "INSERT INTO " collector = visit o.relation, collector - if o.columns.any? - collector << " (#{o.columns.map { |x| - quote_column_name x.name - }.join ', '})" + + unless o.columns.empty? + collector << " (" + o.columns.each_with_index do |x, i| + collector << ", " unless i == 0 + collector << quote_column_name(x.name) + end + collector << ")" end if o.values @@ -97,22 +100,20 @@ module Arel # :nodoc: all def visit_Arel_Nodes_ValuesList(o, collector) collector << "VALUES " - len = o.rows.length - 1 - o.rows.each_with_index { |row, i| + o.rows.each_with_index do |row, i| + collector << ", " unless i == 0 collector << "(" - row_len = row.length - 1 row.each_with_index do |value, k| + collector << ", " unless k == 0 case value when Nodes::SqlLiteral, Nodes::BindParam collector = visit(value, collector) else collector << quote(value).to_s end - collector << ", " unless k == row_len end collector << ")" - collector << ", " unless i == len - } + end collector end @@ -128,11 +129,10 @@ module Arel # :nodoc: all unless o.orders.empty? collector << " ORDER BY " - len = o.orders.length - 1 - o.orders.each_with_index { |x, i| + o.orders.each_with_index do |x, i| + collector << ", " unless i == 0 collector = visit(x, collector) - collector << ", " unless len == i - } + end end visit_Arel_Nodes_SelectOptions(o, collector) @@ -506,7 +506,7 @@ module Arel # :nodoc: all def visit_Arel_Table(o, collector) if o.table_alias - collector << "#{quote_table_name o.name} #{quote_table_name o.table_alias}" + collector << quote_table_name(o.name) << " " << quote_table_name(o.table_alias) else collector << quote_table_name(o.name) end @@ -682,20 +682,13 @@ module Arel # :nodoc: all end def visit_Arel_Nodes_UnqualifiedColumn(o, collector) - collector << "#{quote_column_name o.name}" - collector + collector << quote_column_name(o.name) end def visit_Arel_Attributes_Attribute(o, collector) join_name = o.relation.table_alias || o.relation.name - collector << "#{quote_table_name join_name}.#{quote_column_name o.name}" + collector << quote_table_name(join_name) << "." << quote_column_name(o.name) end - alias :visit_Arel_Attributes_Integer :visit_Arel_Attributes_Attribute - alias :visit_Arel_Attributes_Float :visit_Arel_Attributes_Attribute - alias :visit_Arel_Attributes_Decimal :visit_Arel_Attributes_Attribute - alias :visit_Arel_Attributes_String :visit_Arel_Attributes_Attribute - alias :visit_Arel_Attributes_Time :visit_Arel_Attributes_Attribute - alias :visit_Arel_Attributes_Boolean :visit_Arel_Attributes_Attribute def literal(o, collector); collector << o.to_s; end @@ -785,14 +778,11 @@ module Arel # :nodoc: all end def inject_join(list, collector, join_str) - len = list.length - 1 - list.each_with_index.inject(collector) { |c, (x, i)| - if i == len - visit x, c - else - visit(x, c) << join_str - end - } + list.each_with_index do |x, i| + collector << join_str unless i == 0 + collector = visit(x, collector) + end + collector end def unboundable?(value) diff --git a/activerecord/lib/arel/visitors/visitor.rb b/activerecord/lib/arel/visitors/visitor.rb index 1c17184e86..9066307aed 100644 --- a/activerecord/lib/arel/visitors/visitor.rb +++ b/activerecord/lib/arel/visitors/visitor.rb @@ -7,16 +7,15 @@ module Arel # :nodoc: all @dispatch = get_dispatch_cache end - def accept(object, *args) - visit object, *args + def accept(object, collector = nil) + visit object, collector end private - attr_reader :dispatch def self.dispatch_cache - Hash.new do |hash, klass| + @dispatch_cache ||= Hash.new do |hash, klass| hash[klass] = "visit_#{(klass.name || '').gsub('::', '_')}" end end @@ -25,9 +24,13 @@ module Arel # :nodoc: all self.class.dispatch_cache end - def visit(object, *args) + def visit(object, collector = nil) dispatch_method = dispatch[object.class] - send dispatch_method, object, *args + if collector + send dispatch_method, object, collector + else + send dispatch_method, object + end rescue NoMethodError => e raise e if respond_to?(dispatch_method, true) superklass = object.class.ancestors.find { |klass| diff --git a/activerecord/lib/arel/visitors/where_sql.rb b/activerecord/lib/arel/visitors/where_sql.rb index c6caf5e7c9..8fb299d1c8 100644 --- a/activerecord/lib/arel/visitors/where_sql.rb +++ b/activerecord/lib/arel/visitors/where_sql.rb @@ -9,7 +9,6 @@ module Arel # :nodoc: all end private - def visit_Arel_Nodes_SelectCore(o, collector) collector << "WHERE " wheres = o.wheres.map do |where| diff --git a/activerecord/lib/rails/generators/active_record/application_record/application_record_generator.rb b/activerecord/lib/rails/generators/active_record/application_record/application_record_generator.rb index 35d5664400..56b9628a92 100644 --- a/activerecord/lib/rails/generators/active_record/application_record/application_record_generator.rb +++ b/activerecord/lib/rails/generators/active_record/application_record/application_record_generator.rb @@ -13,7 +13,6 @@ module ActiveRecord end private - def application_record_file_name @application_record_file_name ||= if namespaced? diff --git a/activerecord/lib/rails/generators/active_record/migration.rb b/activerecord/lib/rails/generators/active_record/migration.rb index cbb88d571d..af753071a9 100644 --- a/activerecord/lib/rails/generators/active_record/migration.rb +++ b/activerecord/lib/rails/generators/active_record/migration.rb @@ -17,7 +17,6 @@ module ActiveRecord end private - def primary_key_type key_type = options[:primary_key_type] ", id: :#{key_type}" if key_type diff --git a/activerecord/lib/rails/generators/active_record/model/model_generator.rb b/activerecord/lib/rails/generators/active_record/model/model_generator.rb index c71bbdcab8..d4733f948f 100644 --- a/activerecord/lib/rails/generators/active_record/model/model_generator.rb +++ b/activerecord/lib/rails/generators/active_record/model/model_generator.rb @@ -35,7 +35,6 @@ module ActiveRecord hook_for :test_framework private - def attributes_with_index attributes.select { |a| !a.reference? && a.has_index? } end diff --git a/activerecord/test/active_record/connection_adapters/fake_adapter.rb b/activerecord/test/active_record/connection_adapters/fake_adapter.rb index f977b2997b..f1f457aedd 100644 --- a/activerecord/test/active_record/connection_adapters/fake_adapter.rb +++ b/activerecord/test/active_record/connection_adapters/fake_adapter.rb @@ -32,7 +32,8 @@ module ActiveRecord name.to_s, options[:default], fetch_type_metadata(sql_type), - options[:null]) + options[:null], + ) end def columns(table_name) diff --git a/activerecord/test/cases/adapter_test.rb b/activerecord/test/cases/adapter_test.rb index ce2ed06c1d..0bc617edbe 100644 --- a/activerecord/test/cases/adapter_test.rb +++ b/activerecord/test/cases/adapter_test.rb @@ -12,6 +12,7 @@ module ActiveRecord def setup @connection = ActiveRecord::Base.connection @connection.materialize_transactions + @connection_handler = ActiveRecord::Base.connection_handler end ## @@ -166,7 +167,7 @@ module ActiveRecord def test_preventing_writes_predicate assert_not_predicate @connection, :preventing_writes? - @connection.while_preventing_writes do + @connection_handler.while_preventing_writes do assert_predicate @connection, :preventing_writes? end @@ -176,7 +177,7 @@ module ActiveRecord def test_errors_when_an_insert_query_is_called_while_preventing_writes assert_no_queries do assert_raises(ActiveRecord::ReadOnlyError) do - @connection.while_preventing_writes do + @connection_handler.while_preventing_writes do @connection.transaction do @connection.insert("INSERT INTO subscribers(nick) VALUES ('138853948594')", nil, false) end @@ -190,7 +191,7 @@ module ActiveRecord assert_no_queries do assert_raises(ActiveRecord::ReadOnlyError) do - @connection.while_preventing_writes do + @connection_handler.while_preventing_writes do @connection.transaction do @connection.update("UPDATE subscribers SET nick = '9989' WHERE nick = '138853948594'") end @@ -204,7 +205,7 @@ module ActiveRecord assert_no_queries do assert_raises(ActiveRecord::ReadOnlyError) do - @connection.while_preventing_writes do + @connection_handler.while_preventing_writes do @connection.transaction do @connection.delete("DELETE FROM subscribers WHERE nick = '138853948594'") end @@ -216,7 +217,7 @@ module ActiveRecord def test_doesnt_error_when_a_select_query_is_called_while_preventing_writes @connection.insert("INSERT INTO subscribers(nick) VALUES ('138853948594')") - @connection.while_preventing_writes do + @connection_handler.while_preventing_writes do result = @connection.select_all("SELECT subscribers.* FROM subscribers WHERE nick = '138853948594'") assert_equal 1, result.length end @@ -559,7 +560,6 @@ module ActiveRecord end private - def reset_fixtures(*fixture_names) ActiveRecord::FixtureSet.reset_cache diff --git a/activerecord/test/cases/adapters/mysql2/annotate_test.rb b/activerecord/test/cases/adapters/mysql2/annotate_test.rb deleted file mode 100644 index b512540073..0000000000 --- a/activerecord/test/cases/adapters/mysql2/annotate_test.rb +++ /dev/null @@ -1,37 +0,0 @@ -# frozen_string_literal: true - -require "cases/helper" -require "models/post" - -class Mysql2AnnotateTest < ActiveRecord::Mysql2TestCase - fixtures :posts - - def test_annotate_wraps_content_in_an_inline_comment - assert_sql(%r{\ASELECT `posts`\.`id` FROM `posts` /\* foo \*/}) do - posts = Post.select(:id).annotate("foo") - assert posts.first - end - end - - def test_annotate_is_sanitized - assert_sql(%r{\ASELECT `posts`\.`id` FROM `posts` /\* foo \*/}) do - posts = Post.select(:id).annotate("*/foo/*") - assert posts.first - end - - assert_sql(%r{\ASELECT `posts`\.`id` FROM `posts` /\* foo \*/}) do - posts = Post.select(:id).annotate("**//foo//**") - assert posts.first - end - - assert_sql(%r{\ASELECT `posts`\.`id` FROM `posts` /\* foo \*/ /\* bar \*/}) do - posts = Post.select(:id).annotate("*/foo/*").annotate("*/bar") - assert posts.first - end - - assert_sql(%r{\ASELECT `posts`\.`id` FROM `posts` /\* \+ MAX_EXECUTION_TIME\(1\) \*/}) do - posts = Post.select(:id).annotate("+ MAX_EXECUTION_TIME(1)") - assert posts.first - end - end -end diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb index 9c6566106a..cb7461a8d5 100644 --- a/activerecord/test/cases/adapters/mysql2/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb @@ -197,7 +197,6 @@ class Mysql2ConnectionTest < ActiveRecord::Mysql2TestCase end private - def test_lock_free(lock_name) @connection.select_value("SELECT IS_FREE_LOCK(#{@connection.quote(lock_name)})") == 1 end diff --git a/activerecord/test/cases/adapters/mysql2/enum_test.rb b/activerecord/test/cases/adapters/mysql2/enum_test.rb index 832f5d61d1..1168b3677e 100644 --- a/activerecord/test/cases/adapters/mysql2/enum_test.rb +++ b/activerecord/test/cases/adapters/mysql2/enum_test.rb @@ -1,11 +1,20 @@ # frozen_string_literal: true require "cases/helper" +require "support/schema_dumping_helper" class Mysql2EnumTest < ActiveRecord::Mysql2TestCase + include SchemaDumpingHelper + class EnumTest < ActiveRecord::Base end + def setup + EnumTest.connection.create_table :enum_tests, id: false, force: true do |t| + t.column :enum_column, "enum('text','blob','tiny','medium','long','unsigned','bigint')" + end + end + def test_enum_limit column = EnumTest.columns_hash["enum_column"] assert_equal 8, column.limit @@ -20,4 +29,9 @@ class Mysql2EnumTest < ActiveRecord::Mysql2TestCase column = EnumTest.columns_hash["enum_column"] assert_not_predicate column, :bigint? end + + def test_schema_dumping + schema = dump_table_schema "enum_tests" + assert_match %r{t\.column "enum_column", "enum\('text','blob','tiny','medium','long','unsigned','bigint'\)"$}, schema + end end diff --git a/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb b/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb index 6ade2eec24..cfc1823773 100644 --- a/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb +++ b/activerecord/test/cases/adapters/mysql2/mysql2_adapter_test.rb @@ -8,6 +8,7 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase def setup @conn = ActiveRecord::Base.connection + @connection_handler = ActiveRecord::Base.connection_handler end def test_exec_query_nothing_raises_with_no_result_queries @@ -19,6 +20,18 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase end end + def test_database_exists_returns_false_if_database_does_not_exist + config = ActiveRecord::Base.configurations["arunit"].merge(database: "inexistent_activerecord_unittest") + assert_not ActiveRecord::ConnectionAdapters::Mysql2Adapter.database_exists?(config), + "expected database to not exist" + end + + def test_database_exists_returns_true_when_the_database_exists + config = ActiveRecord::Base.configurations["arunit"] + assert ActiveRecord::ConnectionAdapters::Mysql2Adapter.database_exists?(config), + "expected database #{config[:database]} to exist" + end + def test_columns_for_distinct_zero_orders assert_equal "posts.id", @conn.columns_for_distinct("posts.id", []) @@ -148,7 +161,7 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase def test_errors_when_an_insert_query_is_called_while_preventing_writes assert_raises(ActiveRecord::ReadOnlyError) do - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do @conn.insert("INSERT INTO `engines` (`car_id`) VALUES ('138853948594')") end end @@ -158,7 +171,7 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase @conn.insert("INSERT INTO `engines` (`car_id`) VALUES ('138853948594')") assert_raises(ActiveRecord::ReadOnlyError) do - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do @conn.update("UPDATE `engines` SET `engines`.`car_id` = '9989' WHERE `engines`.`car_id` = '138853948594'") end end @@ -168,7 +181,7 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase @conn.execute("INSERT INTO `engines` (`car_id`) VALUES ('138853948594')") assert_raises(ActiveRecord::ReadOnlyError) do - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do @conn.execute("DELETE FROM `engines` where `engines`.`car_id` = '138853948594'") end end @@ -178,7 +191,7 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase @conn.execute("INSERT INTO `engines` (`car_id`) VALUES ('138853948594')") assert_raises(ActiveRecord::ReadOnlyError) do - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do @conn.execute("REPLACE INTO `engines` SET `engines`.`car_id` = '249823948'") end end @@ -187,19 +200,19 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase def test_doesnt_error_when_a_select_query_is_called_while_preventing_writes @conn.execute("INSERT INTO `engines` (`car_id`) VALUES ('138853948594')") - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do assert_equal 1, @conn.execute("SELECT `engines`.* FROM `engines` WHERE `engines`.`car_id` = '138853948594'").entries.count end end def test_doesnt_error_when_a_show_query_is_called_while_preventing_writes - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do assert_equal 2, @conn.execute("SHOW FULL FIELDS FROM `engines`").entries.count end end def test_doesnt_error_when_a_set_query_is_called_while_preventing_writes - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do assert_nil @conn.execute("SET NAMES utf8mb4 COLLATE utf8mb4_unicode_ci") end end @@ -207,13 +220,27 @@ class Mysql2AdapterTest < ActiveRecord::Mysql2TestCase def test_doesnt_error_when_a_read_query_with_leading_chars_is_called_while_preventing_writes @conn.execute("INSERT INTO `engines` (`car_id`) VALUES ('138853948594')") - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do assert_equal 1, @conn.execute("(\n( SELECT `engines`.* FROM `engines` WHERE `engines`.`car_id` = '138853948594' ) )").entries.count end end - private + def test_read_timeout_exception + ActiveRecord::Base.establish_connection( + ActiveRecord::Base.configurations[:arunit].merge("read_timeout" => 1) + ) + error = assert_raises(ActiveRecord::AdapterTimeout) do + ActiveRecord::Base.connection.execute("SELECT SLEEP(2)") + end + assert_kind_of ActiveRecord::QueryAborted, error + + assert_equal Mysql2::Error::TimeoutError, error.cause.class + ensure + ActiveRecord::Base.establish_connection :arunit + end + + private def with_example_table(definition = "id int auto_increment primary key, number int, data varchar(255)", &block) super(@conn, "ex", definition, &block) end diff --git a/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb b/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb index d7d9a2d732..182d5a3e58 100644 --- a/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb +++ b/activerecord/test/cases/adapters/mysql2/schema_migrations_test.rb @@ -40,7 +40,6 @@ class SchemaMigrationsTest < ActiveRecord::Mysql2TestCase end private - def with_encoding_utf8mb4 database_name = connection.current_database database_info = connection.select_one("SELECT * FROM information_schema.schemata WHERE schema_name = '#{database_name}'") diff --git a/activerecord/test/cases/adapters/mysql2/set_test.rb b/activerecord/test/cases/adapters/mysql2/set_test.rb new file mode 100644 index 0000000000..89107e142f --- /dev/null +++ b/activerecord/test/cases/adapters/mysql2/set_test.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +require "cases/helper" +require "support/schema_dumping_helper" + +class Mysql2SetTest < ActiveRecord::Mysql2TestCase + include SchemaDumpingHelper + + class SetTest < ActiveRecord::Base + end + + def setup + SetTest.connection.create_table :set_tests, id: false, force: true do |t| + t.column :set_column, "set('text','blob','tiny','medium','long','unsigned','bigint')" + end + end + + def test_should_not_be_unsigned + column = SetTest.columns_hash["set_column"] + assert_not_predicate column, :unsigned? + end + + def test_should_not_be_bigint + column = SetTest.columns_hash["set_column"] + assert_not_predicate column, :bigint? + end + + def test_schema_dumping + schema = dump_table_schema "set_tests" + assert_match %r{t\.column "set_column", "set\('text','blob','tiny','medium','long','unsigned','bigint'\)"$}, schema + end +end diff --git a/activerecord/test/cases/adapters/mysql2/table_options_test.rb b/activerecord/test/cases/adapters/mysql2/table_options_test.rb index 1c92df940f..13cf1daa08 100644 --- a/activerecord/test/cases/adapters/mysql2/table_options_test.rb +++ b/activerecord/test/cases/adapters/mysql2/table_options_test.rb @@ -73,7 +73,7 @@ class Mysql2DefaultEngineOptionSchemaDumpTest < ActiveRecord::Mysql2TestCase end end.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], ActiveRecord::Base.connection.schema_migration).migrate output = dump_table_schema("mysql_table_options") options = %r{create_table "mysql_table_options", options: "(?<options>.*)"}.match(output)[:options] @@ -112,7 +112,7 @@ class Mysql2DefaultEngineOptionSqlOutputTest < ActiveRecord::Mysql2TestCase end end.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], ActiveRecord::Base.connection.schema_migration).migrate assert_match %r{ENGINE=InnoDB}, @log.string end diff --git a/activerecord/test/cases/adapters/mysql2/transaction_test.rb b/activerecord/test/cases/adapters/mysql2/transaction_test.rb index 52e283f247..2041cc308f 100644 --- a/activerecord/test/cases/adapters/mysql2/transaction_test.rb +++ b/activerecord/test/cases/adapters/mysql2/transaction_test.rb @@ -92,7 +92,7 @@ module ActiveRecord test "raises StatementTimeout when statement timeout exceeded" do skip unless ActiveRecord::Base.connection.show_variable("max_execution_time") - assert_raises(ActiveRecord::StatementTimeout) do + error = assert_raises(ActiveRecord::StatementTimeout) do s = Sample.create!(value: 1) latch1 = Concurrent::CountDownLatch.new latch2 = Concurrent::CountDownLatch.new @@ -117,10 +117,11 @@ module ActiveRecord thread.join end end + assert_kind_of ActiveRecord::QueryAborted, error end test "raises QueryCanceled when canceling statement due to user request" do - assert_raises(ActiveRecord::QueryCanceled) do + error = assert_raises(ActiveRecord::QueryCanceled) do s = Sample.create!(value: 1) latch = Concurrent::CountDownLatch.new @@ -144,6 +145,7 @@ module ActiveRecord thread.join end end + assert_kind_of ActiveRecord::QueryAborted, error end end end diff --git a/activerecord/test/cases/adapters/postgresql/annotate_test.rb b/activerecord/test/cases/adapters/postgresql/annotate_test.rb deleted file mode 100644 index 42a2861511..0000000000 --- a/activerecord/test/cases/adapters/postgresql/annotate_test.rb +++ /dev/null @@ -1,37 +0,0 @@ -# frozen_string_literal: true - -require "cases/helper" -require "models/post" - -class PostgresqlAnnotateTest < ActiveRecord::PostgreSQLTestCase - fixtures :posts - - def test_annotate_wraps_content_in_an_inline_comment - assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* foo \*/}) do - posts = Post.select(:id).annotate("foo") - assert posts.first - end - end - - def test_annotate_is_sanitized - assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* foo \*/}) do - posts = Post.select(:id).annotate("*/foo/*") - assert posts.first - end - - assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* foo \*/}) do - posts = Post.select(:id).annotate("**//foo//**") - assert posts.first - end - - assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* foo \*/ /\* bar \*/}) do - posts = Post.select(:id).annotate("*/foo/*").annotate("*/bar") - assert posts.first - end - - assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* \+ MAX_EXECUTION_TIME\(1\) \*/}) do - posts = Post.select(:id).annotate("+ MAX_EXECUTION_TIME(1)") - assert posts.first - end - end -end diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb index 9494863a75..dcee4fd22d 100644 --- a/activerecord/test/cases/adapters/postgresql/connection_test.rb +++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb @@ -239,7 +239,6 @@ module ActiveRecord end private - def with_warning_suppression log_level = @connection.client_min_messages @connection.client_min_messages = "error" diff --git a/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb b/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb index 0fd7b2c6ed..16baa8933d 100644 --- a/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb +++ b/activerecord/test/cases/adapters/postgresql/extension_migration_test.rb @@ -27,20 +27,20 @@ class PostgresqlExtensionMigrationTest < ActiveRecord::PostgreSQLTestCase ActiveRecord::Base.table_name_prefix = "p_" ActiveRecord::Base.table_name_suffix = "_s" - ActiveRecord::SchemaMigration.reset_table_name + @connection.schema_migration.reset_table_name ActiveRecord::InternalMetadata.reset_table_name - ActiveRecord::SchemaMigration.delete_all rescue nil + @connection.schema_migration.delete_all rescue nil ActiveRecord::Migration.verbose = false end def teardown - ActiveRecord::SchemaMigration.delete_all rescue nil + @connection.schema_migration.delete_all rescue nil ActiveRecord::Migration.verbose = true ActiveRecord::Base.table_name_prefix = @old_table_name_prefix ActiveRecord::Base.table_name_suffix = @old_table_name_suffix - ActiveRecord::SchemaMigration.reset_table_name + @connection.schema_migration.reset_table_name ActiveRecord::InternalMetadata.reset_table_name super @@ -50,7 +50,7 @@ class PostgresqlExtensionMigrationTest < ActiveRecord::PostgreSQLTestCase @connection.disable_extension("hstore") migrations = [EnableHstore.new(nil, 1)] - ActiveRecord::Migrator.new(:up, migrations).migrate + ActiveRecord::Migrator.new(:up, migrations, ActiveRecord::Base.connection.schema_migration).migrate assert @connection.extension_enabled?("hstore"), "extension hstore should be enabled" end @@ -58,7 +58,7 @@ class PostgresqlExtensionMigrationTest < ActiveRecord::PostgreSQLTestCase @connection.enable_extension("hstore") migrations = [DisableHstore.new(nil, 1)] - ActiveRecord::Migrator.new(:up, migrations).migrate + ActiveRecord::Migrator.new(:up, migrations, ActiveRecord::Base.connection.schema_migration).migrate assert_not @connection.extension_enabled?("hstore"), "extension hstore should not be enabled" end end diff --git a/activerecord/test/cases/adapters/postgresql/geometric_test.rb b/activerecord/test/cases/adapters/postgresql/geometric_test.rb index 14c262f4ce..f312b6e23d 100644 --- a/activerecord/test/cases/adapters/postgresql/geometric_test.rb +++ b/activerecord/test/cases/adapters/postgresql/geometric_test.rb @@ -361,7 +361,6 @@ class PostgreSQLGeometricTypesTest < ActiveRecord::PostgreSQLTestCase end private - def assert_column_exists(column_name) assert connection.column_exists?(table_name, column_name) end diff --git a/activerecord/test/cases/adapters/postgresql/money_test.rb b/activerecord/test/cases/adapters/postgresql/money_test.rb index 1aa0348879..ff2ab22a80 100644 --- a/activerecord/test/cases/adapters/postgresql/money_test.rb +++ b/activerecord/test/cases/adapters/postgresql/money_test.rb @@ -54,8 +54,12 @@ class PostgresqlMoneyTest < ActiveRecord::PostgreSQLTestCase type = PostgresqlMoney.type_for_attribute("wealth") assert_equal(12345678.12, type.cast(+"$12,345,678.12")) assert_equal(12345678.12, type.cast(+"$12.345.678,12")) + assert_equal(12345678.12, type.cast(+"12,345,678.12")) + assert_equal(12345678.12, type.cast(+"12.345.678,12")) assert_equal(-1.15, type.cast(+"-$1.15")) assert_equal(-2.25, type.cast(+"($2.25)")) + assert_equal(-1.15, type.cast(+"-1.15")) + assert_equal(-2.25, type.cast(+"(2.25)")) end def test_schema_dumping diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb index fbd3cbf90f..830c0892d3 100644 --- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb +++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb @@ -13,6 +13,7 @@ module ActiveRecord def setup @connection = ActiveRecord::Base.connection + @connection_handler = ActiveRecord::Base.connection_handler end def test_bad_connection @@ -23,6 +24,18 @@ module ActiveRecord end end + def test_database_exists_returns_false_when_the_database_does_not_exist + config = { database: "non_extant_database", adapter: "postgresql" } + assert_not ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.database_exists?(config), + "expected database #{config[:database]} to not exist" + end + + def test_database_exists_returns_true_when_the_database_exists + config = ActiveRecord::Base.configurations["arunit"] + assert ActiveRecord::ConnectionAdapters::PostgreSQLAdapter.database_exists?(config), + "expected database #{config[:database]} to exist" + end + def test_primary_key with_example_table do assert_equal "id", @connection.primary_key("ex") @@ -240,9 +253,11 @@ module ActiveRecord def test_expression_index with_example_table do - @connection.add_index "ex", "mod(id, 10), abs(number)", name: "expression" + expr = "mod(id, 10), abs(number)" + @connection.add_index "ex", expr, name: "expression" index = @connection.indexes("ex").find { |idx| idx.name == "expression" } - assert_equal "mod(id, 10), abs(number)", index.columns + assert_equal expr, index.columns + assert_equal true, @connection.index_exists?("ex", expr, name: "expression") end end @@ -379,7 +394,7 @@ module ActiveRecord def test_errors_when_an_insert_query_is_called_while_preventing_writes with_example_table do assert_raises(ActiveRecord::ReadOnlyError) do - @connection.while_preventing_writes do + @connection_handler.while_preventing_writes do @connection.execute("INSERT INTO ex (data) VALUES ('138853948594')") end end @@ -391,7 +406,7 @@ module ActiveRecord @connection.execute("INSERT INTO ex (data) VALUES ('138853948594')") assert_raises(ActiveRecord::ReadOnlyError) do - @connection.while_preventing_writes do + @connection_handler.while_preventing_writes do @connection.execute("UPDATE ex SET data = '9989' WHERE data = '138853948594'") end end @@ -403,7 +418,7 @@ module ActiveRecord @connection.execute("INSERT INTO ex (data) VALUES ('138853948594')") assert_raises(ActiveRecord::ReadOnlyError) do - @connection.while_preventing_writes do + @connection_handler.while_preventing_writes do @connection.execute("DELETE FROM ex where data = '138853948594'") end end @@ -414,20 +429,20 @@ module ActiveRecord with_example_table do @connection.execute("INSERT INTO ex (data) VALUES ('138853948594')") - @connection.while_preventing_writes do + @connection_handler.while_preventing_writes do assert_equal 1, @connection.execute("SELECT * FROM ex WHERE data = '138853948594'").entries.count end end end def test_doesnt_error_when_a_show_query_is_called_while_preventing_writes - @connection.while_preventing_writes do + @connection_handler.while_preventing_writes do assert_equal 1, @connection.execute("SHOW TIME ZONE").entries.count end end def test_doesnt_error_when_a_set_query_is_called_while_preventing_writes - @connection.while_preventing_writes do + @connection_handler.while_preventing_writes do assert_equal [], @connection.execute("SET standard_conforming_strings = on").entries end end @@ -436,14 +451,13 @@ module ActiveRecord with_example_table do @connection.execute("INSERT INTO ex (data) VALUES ('138853948594')") - @connection.while_preventing_writes do + @connection_handler.while_preventing_writes do assert_equal 1, @connection.execute("(\n( SELECT * FROM ex WHERE data = '138853948594' ) )").entries.count end end end private - def with_example_table(definition = "id serial primary key, number integer, data character varying(255)", &block) super(@connection, "ex", definition, &block) end diff --git a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb index 96cfabf58f..a4f722c063 100644 --- a/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb +++ b/activerecord/test/cases/adapters/postgresql/referential_integrity_test.rb @@ -106,7 +106,6 @@ class PostgreSQLReferentialIntegrityTest < ActiveRecord::PostgreSQLTestCase end private - def assert_transaction_is_not_broken assert_equal 1, @connection.select_value("SELECT 1") end diff --git a/activerecord/test/cases/adapters/postgresql/rename_table_test.rb b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb index 7eccaf4aa2..fae20de086 100644 --- a/activerecord/test/cases/adapters/postgresql/rename_table_test.rb +++ b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb @@ -25,7 +25,6 @@ class PostgresqlRenameTableTest < ActiveRecord::PostgreSQLTestCase end private - def num_indices_named(name) @connection.execute(<<~SQL).values.length SELECT 1 FROM "pg_index" diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb index 336cec30ca..fe6a3deff4 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb @@ -104,7 +104,11 @@ class SchemaTest < ActiveRecord::PostgreSQLTestCase end def test_schema_names - assert_equal ["public", "test_schema", "test_schema2"], @connection.schema_names + schema_names = @connection.schema_names + assert_includes schema_names, "public" + assert_includes schema_names, "test_schema" + assert_includes schema_names, "test_schema2" + assert_includes schema_names, "hint_plan" if @connection.supports_optimizer_hints? end def test_create_schema diff --git a/activerecord/test/cases/adapters/postgresql/transaction_test.rb b/activerecord/test/cases/adapters/postgresql/transaction_test.rb index 919ff3d158..311863a418 100644 --- a/activerecord/test/cases/adapters/postgresql/transaction_test.rb +++ b/activerecord/test/cases/adapters/postgresql/transaction_test.rb @@ -177,7 +177,6 @@ module ActiveRecord end private - def with_warning_suppression log_level = ActiveRecord::Base.connection.client_min_messages ActiveRecord::Base.connection.client_min_messages = "error" diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb index d2d8ea8042..a1c985fc71 100644 --- a/activerecord/test/cases/adapters/postgresql/uuid_test.rb +++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb @@ -293,14 +293,16 @@ class PostgresqlUUIDGenerationTest < ActiveRecord::PostgreSQLTestCase create_table("pg_uuids_4", id: :uuid) end end.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], ActiveRecord::Base.connection.schema_migration).migrate schema = dump_table_schema "pg_uuids_4" assert_match(/\bcreate_table "pg_uuids_4", id: :uuid, default: -> { "uuid_generate_v4\(\)" }/, schema) ensure drop_table "pg_uuids_4" ActiveRecord::Migration.verbose = @verbose_was + ActiveRecord::Base.connection.schema_migration.delete_all end + uses_transaction :test_schema_dumper_for_uuid_primary_key_default_in_legacy_migration end class PostgresqlUUIDTestNilDefault < ActiveRecord::PostgreSQLTestCase @@ -341,14 +343,16 @@ class PostgresqlUUIDTestNilDefault < ActiveRecord::PostgreSQLTestCase create_table("pg_uuids_4", id: :uuid, default: nil) end end.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], ActiveRecord::Base.connection.schema_migration).migrate schema = dump_table_schema "pg_uuids_4" assert_match(/\bcreate_table "pg_uuids_4", id: :uuid, default: nil/, schema) ensure drop_table "pg_uuids_4" ActiveRecord::Migration.verbose = @verbose_was + ActiveRecord::Base.connection.schema_migration.delete_all end + uses_transaction :test_schema_dumper_for_uuid_primary_key_with_default_nil_in_legacy_migration end class PostgresqlUUIDTestInverseOf < ActiveRecord::PostgreSQLTestCase diff --git a/activerecord/test/cases/adapters/sqlite3/annotate_test.rb b/activerecord/test/cases/adapters/sqlite3/annotate_test.rb deleted file mode 100644 index 6567a5eca3..0000000000 --- a/activerecord/test/cases/adapters/sqlite3/annotate_test.rb +++ /dev/null @@ -1,37 +0,0 @@ -# frozen_string_literal: true - -require "cases/helper" -require "models/post" - -class SQLite3AnnotateTest < ActiveRecord::SQLite3TestCase - fixtures :posts - - def test_annotate_wraps_content_in_an_inline_comment - assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* foo \*/}) do - posts = Post.select(:id).annotate("foo") - assert posts.first - end - end - - def test_annotate_is_sanitized - assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* foo \*/}) do - posts = Post.select(:id).annotate("*/foo/*") - assert posts.first - end - - assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* foo \*/}) do - posts = Post.select(:id).annotate("**//foo//**") - assert posts.first - end - - assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* foo \*/ /\* bar \*/}) do - posts = Post.select(:id).annotate("*/foo/*").annotate("*/bar") - assert posts.first - end - - assert_sql(%r{\ASELECT "posts"\."id" FROM "posts" /\* \+ MAX_EXECUTION_TIME\(1\) \*/}) do - posts = Post.select(:id).annotate("+ MAX_EXECUTION_TIME(1)") - assert posts.first - end - end -end diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index 806cfbfc00..b6d72c7bcd 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -19,6 +19,8 @@ module ActiveRecord @conn = Base.sqlite3_connection database: ":memory:", adapter: "sqlite3", timeout: 100 + + @connection_handler = ActiveRecord::Base.connection_handler end def test_bad_connection @@ -28,6 +30,17 @@ module ActiveRecord end end + def test_database_exists_returns_false_when_the_database_does_not_exist + assert_not SQLite3Adapter.database_exists?(adapter: "sqlite3", database: "non_extant_db"), + "expected non_extant_db to not exist" + end + + def test_database_exists_returns_true_when_databae_exists + config = ActiveRecord::Base.configurations["arunit"] + assert SQLite3Adapter.database_exists?(config), + "expected #{config[:database]} to exist" + end + unless in_memory_db? def test_connect_with_url original_connection = ActiveRecord::Base.remove_connection @@ -51,6 +64,11 @@ module ActiveRecord end end + def test_database_exists_returns_true_for_an_in_memory_db + assert SQLite3Adapter.database_exists?(database: ":memory:"), + "Expected in memory database to exist" + end + def test_column_types owner = Owner.create!(name: "hello".encode("ascii-8bit")) owner.reload @@ -572,7 +590,7 @@ module ActiveRecord def test_errors_when_an_insert_query_is_called_while_preventing_writes with_example_table "id int, data string" do assert_raises(ActiveRecord::ReadOnlyError) do - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do @conn.execute("INSERT INTO ex (data) VALUES ('138853948594')") end end @@ -584,7 +602,7 @@ module ActiveRecord @conn.execute("INSERT INTO ex (data) VALUES ('138853948594')") assert_raises(ActiveRecord::ReadOnlyError) do - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do @conn.execute("UPDATE ex SET data = '9989' WHERE data = '138853948594'") end end @@ -596,7 +614,7 @@ module ActiveRecord @conn.execute("INSERT INTO ex (data) VALUES ('138853948594')") assert_raises(ActiveRecord::ReadOnlyError) do - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do @conn.execute("DELETE FROM ex where data = '138853948594'") end end @@ -608,7 +626,7 @@ module ActiveRecord @conn.execute("INSERT INTO ex (data) VALUES ('138853948594')") assert_raises(ActiveRecord::ReadOnlyError) do - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do @conn.execute("REPLACE INTO ex (data) VALUES ('249823948')") end end @@ -619,7 +637,7 @@ module ActiveRecord with_example_table "id int, data string" do @conn.execute("INSERT INTO ex (data) VALUES ('138853948594')") - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do assert_equal 1, @conn.execute("SELECT data from ex WHERE data = '138853948594'").count end end @@ -629,14 +647,13 @@ module ActiveRecord with_example_table "id int, data string" do @conn.execute("INSERT INTO ex (data) VALUES ('138853948594')") - @conn.while_preventing_writes do + @connection_handler.while_preventing_writes do assert_equal 1, @conn.execute(" SELECT data from ex WHERE data = '138853948594'").count end end end private - def assert_logged(logs) subscriber = SQLSubscriber.new subscription = ActiveSupport::Notifications.subscribe("sql.active_record", subscriber) diff --git a/activerecord/test/cases/annotate_test.rb b/activerecord/test/cases/annotate_test.rb new file mode 100644 index 0000000000..4d71d28f83 --- /dev/null +++ b/activerecord/test/cases/annotate_test.rb @@ -0,0 +1,46 @@ +# frozen_string_literal: true + +require "cases/helper" +require "models/post" + +class AnnotateTest < ActiveRecord::TestCase + fixtures :posts + + def test_annotate_wraps_content_in_an_inline_comment + quoted_posts_id, quoted_posts = regexp_escape_table_name("posts.id"), regexp_escape_table_name("posts") + + assert_sql(%r{\ASELECT #{quoted_posts_id} FROM #{quoted_posts} /\* foo \*/}i) do + posts = Post.select(:id).annotate("foo") + assert posts.first + end + end + + def test_annotate_is_sanitized + quoted_posts_id, quoted_posts = regexp_escape_table_name("posts.id"), regexp_escape_table_name("posts") + + assert_sql(%r{\ASELECT #{quoted_posts_id} FROM #{quoted_posts} /\* foo \*/}i) do + posts = Post.select(:id).annotate("*/foo/*") + assert posts.first + end + + assert_sql(%r{\ASELECT #{quoted_posts_id} FROM #{quoted_posts} /\* foo \*/}i) do + posts = Post.select(:id).annotate("**//foo//**") + assert posts.first + end + + assert_sql(%r{\ASELECT #{quoted_posts_id} FROM #{quoted_posts} /\* foo \*/ /\* bar \*/}i) do + posts = Post.select(:id).annotate("*/foo/*").annotate("*/bar") + assert posts.first + end + + assert_sql(%r{\ASELECT #{quoted_posts_id} FROM #{quoted_posts} /\* \+ MAX_EXECUTION_TIME\(1\) \*/}i) do + posts = Post.select(:id).annotate("+ MAX_EXECUTION_TIME(1)") + assert posts.first + end + end + + private + def regexp_escape_table_name(name) + Regexp.escape(Post.connection.quote_table_name(name)) + end +end diff --git a/activerecord/test/cases/ar_schema_test.rb b/activerecord/test/cases/ar_schema_test.rb index 7aa6d089c5..2d5a06a4ac 100644 --- a/activerecord/test/cases/ar_schema_test.rb +++ b/activerecord/test/cases/ar_schema_test.rb @@ -9,7 +9,8 @@ class ActiveRecordSchemaTest < ActiveRecord::TestCase @original_verbose = ActiveRecord::Migration.verbose ActiveRecord::Migration.verbose = false @connection = ActiveRecord::Base.connection - ActiveRecord::SchemaMigration.drop_table + @schema_migration = @connection.schema_migration + @schema_migration.drop_table end teardown do @@ -18,21 +19,21 @@ class ActiveRecordSchemaTest < ActiveRecord::TestCase @connection.drop_table :nep_schema_migrations rescue nil @connection.drop_table :has_timestamps rescue nil @connection.drop_table :multiple_indexes rescue nil - ActiveRecord::SchemaMigration.delete_all rescue nil + @schema_migration.delete_all rescue nil ActiveRecord::Migration.verbose = @original_verbose end def test_has_primary_key old_primary_key_prefix_type = ActiveRecord::Base.primary_key_prefix_type ActiveRecord::Base.primary_key_prefix_type = :table_name_with_underscore - assert_equal "version", ActiveRecord::SchemaMigration.primary_key + assert_equal "version", @schema_migration.primary_key - ActiveRecord::SchemaMigration.create_table - assert_difference "ActiveRecord::SchemaMigration.count", 1 do - ActiveRecord::SchemaMigration.create version: 12 + @schema_migration.create_table + assert_difference "@schema_migration.count", 1 do + @schema_migration.create version: 12 end ensure - ActiveRecord::SchemaMigration.drop_table + @schema_migration.drop_table ActiveRecord::Base.primary_key_prefix_type = old_primary_key_prefix_type end @@ -54,7 +55,7 @@ class ActiveRecordSchemaTest < ActiveRecord::TestCase def test_schema_define_with_table_name_prefix old_table_name_prefix = ActiveRecord::Base.table_name_prefix ActiveRecord::Base.table_name_prefix = "nep_" - ActiveRecord::SchemaMigration.reset_table_name + @schema_migration.reset_table_name ActiveRecord::InternalMetadata.reset_table_name ActiveRecord::Schema.define(version: 7) do create_table :fruits do |t| @@ -67,7 +68,7 @@ class ActiveRecordSchemaTest < ActiveRecord::TestCase assert_equal 7, @connection.migration_context.current_version ensure ActiveRecord::Base.table_name_prefix = old_table_name_prefix - ActiveRecord::SchemaMigration.reset_table_name + @schema_migration.reset_table_name ActiveRecord::InternalMetadata.reset_table_name end @@ -89,10 +90,10 @@ class ActiveRecordSchemaTest < ActiveRecord::TestCase end def test_normalize_version - assert_equal "118", ActiveRecord::SchemaMigration.normalize_migration_number("0000118") - assert_equal "002", ActiveRecord::SchemaMigration.normalize_migration_number("2") - assert_equal "017", ActiveRecord::SchemaMigration.normalize_migration_number("0017") - assert_equal "20131219224947", ActiveRecord::SchemaMigration.normalize_migration_number("20131219224947") + assert_equal "118", @schema_migration.normalize_migration_number("0000118") + assert_equal "002", @schema_migration.normalize_migration_number("2") + assert_equal "017", @schema_migration.normalize_migration_number("0017") + assert_equal "20131219224947", @schema_migration.normalize_migration_number("20131219224947") end def test_schema_load_with_multiple_indexes_for_column_of_different_names diff --git a/activerecord/test/cases/arel/attributes/attribute_test.rb b/activerecord/test/cases/arel/attributes/attribute_test.rb index c7bd0a053b..7ebb90c6fd 100644 --- a/activerecord/test/cases/arel/attributes/attribute_test.rb +++ b/activerecord/test/cases/arel/attributes/attribute_test.rb @@ -638,6 +638,18 @@ module Arel ) end + if Gem::Version.new("2.7.0") <= Gem::Version.new(RUBY_VERSION) + it "can be constructed with a range implicitly starting at Infinity" do + attribute = Attribute.new nil, nil + node = attribute.between(eval("..0")) # eval for backwards compatibility + + node.must_equal Nodes::LessThanOrEqual.new( + attribute, + Nodes::Casted.new(0, attribute) + ) + end + end + if Gem::Version.new("2.6.0") <= Gem::Version.new(RUBY_VERSION) it "can be constructed with a range implicitly ending at Infinity" do attribute = Attribute.new nil, nil @@ -839,6 +851,18 @@ module Arel ) end + if Gem::Version.new("2.7.0") <= Gem::Version.new(RUBY_VERSION) + it "can be constructed with a range implicitly starting at Infinity" do + attribute = Attribute.new nil, nil + node = attribute.not_between(eval("..0")) # eval for backwards compatibility + + node.must_equal Nodes::GreaterThan.new( + attribute, + Nodes::Casted.new(0, attribute) + ) + end + end + if Gem::Version.new("2.6.0") <= Gem::Version.new(RUBY_VERSION) it "can be constructed with a range implicitly ending at Infinity" do attribute = Attribute.new nil, nil diff --git a/activerecord/test/cases/arel/attributes_test.rb b/activerecord/test/cases/arel/attributes_test.rb index b00af4bd29..1712633ae9 100644 --- a/activerecord/test/cases/arel/attributes_test.rb +++ b/activerecord/test/cases/arel/attributes_test.rb @@ -23,46 +23,5 @@ module Arel assert_equal 2, array.uniq.size end end - - describe "for" do - it "deals with unknown column types" do - column = Struct.new(:type).new :crazy - Attributes.for(column).must_equal Attributes::Undefined - end - - it "returns the correct constant for strings" do - [:string, :text, :binary].each do |type| - column = Struct.new(:type).new type - Attributes.for(column).must_equal Attributes::String - end - end - - it "returns the correct constant for ints" do - column = Struct.new(:type).new :integer - Attributes.for(column).must_equal Attributes::Integer - end - - it "returns the correct constant for floats" do - column = Struct.new(:type).new :float - Attributes.for(column).must_equal Attributes::Float - end - - it "returns the correct constant for decimals" do - column = Struct.new(:type).new :decimal - Attributes.for(column).must_equal Attributes::Decimal - end - - it "returns the correct constant for boolean" do - column = Struct.new(:type).new :boolean - Attributes.for(column).must_equal Attributes::Boolean - end - - it "returns the correct constant for time" do - [:date, :datetime, :timestamp, :time].each do |type| - column = Struct.new(:type).new type - Attributes.for(column).must_equal Attributes::Time - end - end - end end end diff --git a/activerecord/test/cases/arel/nodes/node_test.rb b/activerecord/test/cases/arel/nodes/node_test.rb index f4f07ef2c5..f1e0ce1ea9 100644 --- a/activerecord/test/cases/arel/nodes/node_test.rb +++ b/activerecord/test/cases/arel/nodes/node_test.rb @@ -18,24 +18,5 @@ module Arel assert klass.ancestors.include?(Nodes::Node), klass.name end end - - def test_each - list = [] - node = Nodes::Node.new - node.each { |n| list << n } - assert_equal [node], list - end - - def test_generator - list = [] - node = Nodes::Node.new - node.each.each { |n| list << n } - assert_equal [node], list - end - - def test_enumerable - node = Nodes::Node.new - assert_kind_of Enumerable, node - end end end diff --git a/activerecord/test/cases/arel/select_manager_test.rb b/activerecord/test/cases/arel/select_manager_test.rb index e6c49cd429..526fe6787a 100644 --- a/activerecord/test/cases/arel/select_manager_test.rb +++ b/activerecord/test/cases/arel/select_manager_test.rb @@ -369,16 +369,6 @@ module Arel mgr = table.from assert mgr.ast end - - it "should allow orders to work when the ast is grepped" do - table = Table.new :users - mgr = table.from - mgr.project Arel.sql "*" - mgr.from table - mgr.orders << Arel::Nodes::Ascending.new(Arel.sql("foo")) - mgr.ast.grep(Arel::Nodes::OuterJoin) - mgr.to_sql.must_be_like %{ SELECT * FROM "users" ORDER BY foo ASC } - end end describe "taken" do diff --git a/activerecord/test/cases/arel/visitors/depth_first_test.rb b/activerecord/test/cases/arel/visitors/depth_first_test.rb deleted file mode 100644 index 106be2311d..0000000000 --- a/activerecord/test/cases/arel/visitors/depth_first_test.rb +++ /dev/null @@ -1,276 +0,0 @@ -# frozen_string_literal: true - -require_relative "../helper" - -module Arel - module Visitors - class TestDepthFirst < Arel::Test - Collector = Struct.new(:calls) do - def call(object) - calls << object - end - end - - def setup - @collector = Collector.new [] - @visitor = Visitors::DepthFirst.new @collector - end - - def test_raises_with_object - assert_raises(TypeError) do - @visitor.accept(Object.new) - end - end - - - # unary ops - [ - Arel::Nodes::Not, - Arel::Nodes::Group, - Arel::Nodes::On, - Arel::Nodes::Grouping, - Arel::Nodes::Offset, - Arel::Nodes::Ordering, - Arel::Nodes::StringJoin, - Arel::Nodes::UnqualifiedColumn, - Arel::Nodes::ValuesList, - Arel::Nodes::Limit, - Arel::Nodes::Else, - ].each do |klass| - define_method("test_#{klass.name.gsub('::', '_')}") do - op = klass.new(:a) - @visitor.accept op - assert_equal [:a, op], @collector.calls - end - end - - # functions - [ - Arel::Nodes::Exists, - Arel::Nodes::Avg, - Arel::Nodes::Min, - Arel::Nodes::Max, - Arel::Nodes::Sum, - ].each do |klass| - define_method("test_#{klass.name.gsub('::', '_')}") do - func = klass.new(:a, "b") - @visitor.accept func - assert_equal [:a, "b", false, func], @collector.calls - end - end - - def test_named_function - func = Arel::Nodes::NamedFunction.new(:a, :b, "c") - @visitor.accept func - assert_equal [:a, :b, false, "c", func], @collector.calls - end - - def test_lock - lock = Nodes::Lock.new true - @visitor.accept lock - assert_equal [lock], @collector.calls - end - - def test_count - count = Nodes::Count.new :a, :b, "c" - @visitor.accept count - assert_equal [:a, "c", :b, count], @collector.calls - end - - def test_inner_join - join = Nodes::InnerJoin.new :a, :b - @visitor.accept join - assert_equal [:a, :b, join], @collector.calls - end - - def test_full_outer_join - join = Nodes::FullOuterJoin.new :a, :b - @visitor.accept join - assert_equal [:a, :b, join], @collector.calls - end - - def test_outer_join - join = Nodes::OuterJoin.new :a, :b - @visitor.accept join - assert_equal [:a, :b, join], @collector.calls - end - - def test_right_outer_join - join = Nodes::RightOuterJoin.new :a, :b - @visitor.accept join - assert_equal [:a, :b, join], @collector.calls - end - - def test_comment - comment = Nodes::Comment.new ["foo"] - @visitor.accept comment - assert_equal ["foo", ["foo"], comment], @collector.calls - end - - [ - Arel::Nodes::Assignment, - Arel::Nodes::Between, - Arel::Nodes::Concat, - Arel::Nodes::DoesNotMatch, - Arel::Nodes::Equality, - Arel::Nodes::GreaterThan, - Arel::Nodes::GreaterThanOrEqual, - Arel::Nodes::In, - Arel::Nodes::LessThan, - Arel::Nodes::LessThanOrEqual, - Arel::Nodes::Matches, - Arel::Nodes::NotEqual, - Arel::Nodes::NotIn, - Arel::Nodes::Or, - Arel::Nodes::TableAlias, - Arel::Nodes::As, - Arel::Nodes::DeleteStatement, - Arel::Nodes::JoinSource, - Arel::Nodes::When, - ].each do |klass| - define_method("test_#{klass.name.gsub('::', '_')}") do - binary = klass.new(:a, :b) - @visitor.accept binary - assert_equal [:a, :b, binary], @collector.calls - end - end - - def test_Arel_Nodes_InfixOperation - binary = Arel::Nodes::InfixOperation.new(:o, :a, :b) - @visitor.accept binary - assert_equal [:a, :b, binary], @collector.calls - end - - # N-ary - [ - Arel::Nodes::And, - ].each do |klass| - define_method("test_#{klass.name.gsub('::', '_')}") do - binary = klass.new([:a, :b, :c]) - @visitor.accept binary - assert_equal [:a, :b, :c, binary], @collector.calls - end - end - - [ - Arel::Attributes::Integer, - Arel::Attributes::Float, - Arel::Attributes::String, - Arel::Attributes::Time, - Arel::Attributes::Boolean, - Arel::Attributes::Attribute - ].each do |klass| - define_method("test_#{klass.name.gsub('::', '_')}") do - binary = klass.new(:a, :b) - @visitor.accept binary - assert_equal [:a, :b, binary], @collector.calls - end - end - - def test_table - relation = Arel::Table.new(:users) - @visitor.accept relation - assert_equal ["users", relation], @collector.calls - end - - def test_array - node = Nodes::Or.new(:a, :b) - list = [node] - @visitor.accept list - assert_equal [:a, :b, node, list], @collector.calls - end - - def test_set - node = Nodes::Or.new(:a, :b) - set = Set.new([node]) - @visitor.accept set - assert_equal [:a, :b, node, set], @collector.calls - end - - def test_hash - node = Nodes::Or.new(:a, :b) - hash = { node => node } - @visitor.accept hash - assert_equal [:a, :b, node, :a, :b, node, hash], @collector.calls - end - - def test_update_statement - stmt = Nodes::UpdateStatement.new - stmt.relation = :a - stmt.values << :b - stmt.wheres << :c - stmt.orders << :d - stmt.limit = :e - - @visitor.accept stmt - assert_equal [:a, :b, stmt.values, :c, stmt.wheres, :d, stmt.orders, - :e, stmt], @collector.calls - end - - def test_select_core - core = Nodes::SelectCore.new - core.projections << :a - core.froms = :b - core.wheres << :c - core.groups << :d - core.windows << :e - core.havings << :f - - @visitor.accept core - assert_equal [ - :a, core.projections, - :b, [], - core.source, - :c, core.wheres, - :d, core.groups, - :e, core.windows, - :f, core.havings, - core], @collector.calls - end - - def test_select_statement - ss = Nodes::SelectStatement.new - ss.cores.replace [:a] - ss.orders << :b - ss.limit = :c - ss.lock = :d - ss.offset = :e - - @visitor.accept ss - assert_equal [ - :a, ss.cores, - :b, ss.orders, - :c, - :d, - :e, - ss], @collector.calls - end - - def test_insert_statement - stmt = Nodes::InsertStatement.new - stmt.relation = :a - stmt.columns << :b - stmt.values = :c - - @visitor.accept stmt - assert_equal [:a, :b, stmt.columns, :c, stmt], @collector.calls - end - - def test_case - node = Arel::Nodes::Case.new - node.case = :a - node.conditions << :b - node.default = :c - - @visitor.accept node - assert_equal [:a, :b, node.conditions, :c, node], @collector.calls - end - - def test_node - node = Nodes::Node.new - @visitor.accept node - assert_equal [node], @collector.calls - end - end - end -end diff --git a/activerecord/test/cases/arel/visitors/dispatch_contamination_test.rb b/activerecord/test/cases/arel/visitors/dispatch_contamination_test.rb index a07a1a050a..36f9eb49a2 100644 --- a/activerecord/test/cases/arel/visitors/dispatch_contamination_test.rb +++ b/activerecord/test/cases/arel/visitors/dispatch_contamination_test.rb @@ -48,7 +48,13 @@ module Arel node = Nodes::Union.new(Nodes::True.new, Nodes::False.new) assert_equal "( TRUE UNION FALSE )", node.to_sql - node.first # from Nodes::Node's Enumerable mixin + visitor = Class.new(Visitor) { + def visit_Arel_Nodes_Union(o); end + alias :visit_Arel_Nodes_True :visit_Arel_Nodes_Union + alias :visit_Arel_Nodes_False :visit_Arel_Nodes_Union + }.new + + visitor.accept(node) assert_equal "( TRUE UNION FALSE )", node.to_sql end diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb index 849939de75..9be21b23db 100644 --- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb +++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb @@ -14,6 +14,7 @@ module Remembered included do after_create :remember + private def remember; self.class.remembered << self; end end diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index f7aad9d775..cb46f9e053 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -523,7 +523,7 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_association_loading_with_belongs_to_and_order_string_with_quoted_table_name quoted_posts_id = Comment.connection.quote_table_name("posts") + "." + Comment.connection.quote_column_name("id") assert_nothing_raised do - Comment.includes(:post).references(:posts).order(Arel.sql(quoted_posts_id)) + Comment.includes(:post).references(:posts).order(quoted_posts_id) end end @@ -789,7 +789,6 @@ class EagerAssociationTest < ActiveRecord::TestCase .where("comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment'") .references(:comments) .scoping do - posts = authors(:david).posts.limit(2).to_a assert_equal 2, posts.size end @@ -798,7 +797,6 @@ class EagerAssociationTest < ActiveRecord::TestCase .where("authors.name = 'David' AND (comments.body like 'Normal%' OR comments.#{QUOTED_TYPE}= 'SpecialComment')") .references(:authors, :comments) .scoping do - count = Post.limit(2).count assert_equal count, posts.size end @@ -970,14 +968,14 @@ class EagerAssociationTest < ActiveRecord::TestCase posts(:thinking, :sti_comments), Post.all.merge!( includes: [:author, :comments], where: { "authors.name" => "David" }, - order: Arel.sql("UPPER(posts.title)"), limit: 2, offset: 1 + order: "UPPER(posts.title)", limit: 2, offset: 1 ).to_a ) assert_equal( posts(:sti_post_and_comments, :sti_comments), Post.all.merge!( includes: [:author, :comments], where: { "authors.name" => "David" }, - order: Arel.sql("UPPER(posts.title) DESC"), limit: 2, offset: 1 + order: "UPPER(posts.title) DESC", limit: 2, offset: 1 ).to_a ) end @@ -987,14 +985,14 @@ class EagerAssociationTest < ActiveRecord::TestCase posts(:thinking, :sti_comments), Post.all.merge!( includes: [:author, :comments], where: { "authors.name" => "David" }, - order: [Arel.sql("UPPER(posts.title)"), "posts.id"], limit: 2, offset: 1 + order: ["UPPER(posts.title)", "posts.id"], limit: 2, offset: 1 ).to_a ) assert_equal( posts(:sti_post_and_comments, :sti_comments), Post.all.merge!( includes: [:author, :comments], where: { "authors.name" => "David" }, - order: [Arel.sql("UPPER(posts.title) DESC"), "posts.id"], limit: 2, offset: 1 + order: ["UPPER(posts.title) DESC", "posts.id"], limit: 2, offset: 1 ).to_a ) end diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb index 5e6e3e8ec4..604a52655c 100644 --- a/activerecord/test/cases/associations/extension_test.rb +++ b/activerecord/test/cases/associations/extension_test.rb @@ -87,7 +87,6 @@ class AssociationsExtensionsTest < ActiveRecord::TestCase end private - def extend!(model) ActiveRecord::Associations::Builder::HasMany.send(:define_extensions, model, :association_name) { } end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 545bc77fed..6c54c2f1cd 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -2932,8 +2932,12 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal [], reference.ideal_jobs end - private + def test_has_many_preloading_with_duplicate_records + posts = Post.joins(:comments).preload(:comments).to_a + assert_equal [1, 2], posts.first.comments.map(&:id) + end + private def force_signal37_to_load_all_clients_of_firm companies(:first_firm).clients_of_firm.load_target end diff --git a/activerecord/test/cases/associations/nested_through_associations_test.rb b/activerecord/test/cases/associations/nested_through_associations_test.rb index 35da74102d..8d74ae3961 100644 --- a/activerecord/test/cases/associations/nested_through_associations_test.rb +++ b/activerecord/test/cases/associations/nested_through_associations_test.rb @@ -626,7 +626,6 @@ class NestedThroughAssociationsTest < ActiveRecord::TestCase end private - def assert_includes_and_joins_equal(query, expected, association) actual = assert_queries(1) { query.joins(association).to_a.uniq } assert_equal expected, actual diff --git a/activerecord/test/cases/associations/required_test.rb b/activerecord/test/cases/associations/required_test.rb index c7a78e6bc4..db7f945a36 100644 --- a/activerecord/test/cases/associations/required_test.rb +++ b/activerecord/test/cases/associations/required_test.rb @@ -117,7 +117,6 @@ class RequiredAssociationsTest < ActiveRecord::TestCase end private - def subclass_of(klass, &block) subclass = Class.new(klass, &block) def subclass.name diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index 5cbe5d796d..71b5407dcc 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -1087,7 +1087,6 @@ class AttributeMethodsTest < ActiveRecord::TestCase end private - def new_topic_like_ar_class(&block) klass = Class.new(ActiveRecord::Base) do self.table_name = "topics" diff --git a/activerecord/test/cases/attributes_test.rb b/activerecord/test/cases/attributes_test.rb index a6fb9f0af7..d6ac5a1057 100644 --- a/activerecord/test/cases/attributes_test.rb +++ b/activerecord/test/cases/attributes_test.rb @@ -241,7 +241,7 @@ module ActiveRecord test "attributes not backed by database columns are always initialized" do OverloadedType.create! - model = OverloadedType.first + model = OverloadedType.last assert_nil model.non_existent_decimal model.non_existent_decimal = "123" @@ -253,7 +253,7 @@ module ActiveRecord attribute :non_existent_decimal, :decimal, default: 123 end child.create! - model = child.first + model = child.last assert_equal 123, model.non_existent_decimal end @@ -264,7 +264,7 @@ module ActiveRecord attribute :foo, :string, default: "lol" end child.create! - model = child.first + model = child.last assert_equal "lol", model.foo diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 2fb5ca4152..3528ac045f 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -2,6 +2,7 @@ require "cases/helper" require "models/author" +require "models/book" require "models/bird" require "models/post" require "models/comment" @@ -12,12 +13,14 @@ require "models/developer" require "models/computer" require "models/invoice" require "models/line_item" +require "models/mouse" require "models/order" require "models/parrot" require "models/pirate" require "models/project" require "models/ship" require "models/ship_part" +require "models/squeak" require "models/tag" require "models/tagging" require "models/treasure" @@ -39,7 +42,6 @@ class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase def self.name; "Person"; end private - def should_be_cool unless first_name == "cool" errors.add :first_name, "not cool" @@ -82,7 +84,6 @@ class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase end private - def assert_no_difference_when_adding_callbacks_twice_for(model, association_name) reflection = model.reflect_on_association(association_name) assert_no_difference "callbacks_for_model(#{model.name}).length" do @@ -387,6 +388,20 @@ class TestDefaultAutosaveAssociationOnABelongsToAssociation < ActiveRecord::Test assert_predicate auditlog, :valid? end + + def test_validation_does_not_validate_non_dirty_association_target + mouse = Mouse.create!(name: "Will") + Squeak.create!(mouse: mouse) + + mouse.name = nil + mouse.save! validate: false + + squeak = Squeak.last + + assert_equal true, squeak.valid? + assert_equal true, squeak.mouse.present? + assert_equal true, squeak.valid? + end end class TestDefaultAutosaveAssociationOnAHasManyAssociationWithAcceptsNestedAttributes < ActiveRecord::TestCase @@ -1673,6 +1688,10 @@ class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::Te super @pirate = Pirate.create(catchphrase: "Don' botharrr talkin' like one, savvy?") @pirate.birds.create(name: "cookoo") + + @author = Author.new(name: "DHH") + @author.published_books.build(name: "Rework", isbn: "1234") + @author.published_books.build(name: "Remote", isbn: "1234") end test "should automatically validate associations" do @@ -1681,6 +1700,42 @@ class TestAutosaveAssociationValidationsOnAHasManyAssociation < ActiveRecord::Te assert_not_predicate @pirate, :valid? end + + test "rollbacks whole transaction and raises ActiveRecord::RecordInvalid when associations fail to #save! due to uniqueness validation failure" do + author_count_before_save = Author.count + book_count_before_save = Book.count + + assert_no_difference "Author.count" do + assert_no_difference "Book.count" do + exception = assert_raises(ActiveRecord::RecordInvalid) do + @author.save! + end + + assert_equal("Validation failed: Published books is invalid", exception.message) + end + end + + assert_equal(author_count_before_save, Author.count) + assert_equal(book_count_before_save, Book.count) + end + + test "rollbacks whole transaction when associations fail to #save due to uniqueness validation failure" do + author_count_before_save = Author.count + book_count_before_save = Book.count + + assert_no_difference "Author.count" do + assert_no_difference "Book.count" do + assert_nothing_raised do + result = @author.save + + assert_not(result) + end + end + end + + assert_equal(author_count_before_save, Author.count) + assert_equal(book_count_before_save, Book.count) + end end class TestAutosaveAssociationValidationsOnAHasOneAssociation < ActiveRecord::TestCase diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index ddafa468ed..1324bdf9b8 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1141,11 +1141,14 @@ class BasicsTest < ActiveRecord::TestCase def test_clear_cache! # preheat cache c1 = Post.connection.schema_cache.columns("posts") + assert_not_equal 0, Post.connection.schema_cache.size + ActiveRecord::Base.clear_cache! + assert_equal 0, Post.connection.schema_cache.size + c2 = Post.connection.schema_cache.columns("posts") - c1.each_with_index do |v, i| - assert_not_same v, c2[i] - end + assert_not_equal 0, Post.connection.schema_cache.size + assert_equal c1, c2 end @@ -1412,6 +1415,14 @@ class BasicsTest < ActiveRecord::TestCase assert_not_includes SymbolIgnoredDeveloper.columns_hash.keys, "first_name" end + test ".columns_hash raises an error if the record has an empty table name" do + expected_message = "FirstAbstractClass has no table configured. Set one with FirstAbstractClass.table_name=" + exception = assert_raises(ActiveRecord::TableNotSpecified) do + FirstAbstractClass.columns_hash + end + assert_equal expected_message, exception.message + end + test "ignored columns have no attribute methods" do assert_not_respond_to Developer.new, :first_name assert_not_respond_to Developer.new, :first_name= @@ -1496,7 +1507,7 @@ class BasicsTest < ActiveRecord::TestCase test "creating a record raises if preventing writes" do error = assert_raises ActiveRecord::ReadOnlyError do - ActiveRecord::Base.connection.while_preventing_writes do + ActiveRecord::Base.connection_handler.while_preventing_writes do Bird.create! name: "Bluejay" end end @@ -1508,7 +1519,7 @@ class BasicsTest < ActiveRecord::TestCase bird = Bird.create! name: "Bluejay" error = assert_raises ActiveRecord::ReadOnlyError do - ActiveRecord::Base.connection.while_preventing_writes do + ActiveRecord::Base.connection_handler.while_preventing_writes do bird.update! name: "Robin" end end @@ -1520,7 +1531,7 @@ class BasicsTest < ActiveRecord::TestCase bird = Bird.create! name: "Bluejay" error = assert_raises ActiveRecord::ReadOnlyError do - ActiveRecord::Base.connection.while_preventing_writes do + ActiveRecord::Base.connection_handler.while_preventing_writes do bird.destroy! end end @@ -1531,7 +1542,7 @@ class BasicsTest < ActiveRecord::TestCase test "selecting a record does not raise if preventing writes" do bird = Bird.create! name: "Bluejay" - ActiveRecord::Base.connection.while_preventing_writes do + ActiveRecord::Base.connection_handler.while_preventing_writes do assert_equal bird, Bird.where(name: "Bluejay").first end end @@ -1539,13 +1550,13 @@ class BasicsTest < ActiveRecord::TestCase test "an explain query does not raise if preventing writes" do Bird.create!(name: "Bluejay") - ActiveRecord::Base.connection.while_preventing_writes do + ActiveRecord::Base.connection_handler.while_preventing_writes do assert_queries(2) { Bird.where(name: "Bluejay").explain } end end test "an empty transaction does not raise if preventing writes" do - ActiveRecord::Base.connection.while_preventing_writes do + ActiveRecord::Base.connection_handler.while_preventing_writes do assert_queries(2, ignore_none: true) do Bird.transaction do ActiveRecord::Base.connection.materialize_transactions @@ -1553,4 +1564,59 @@ class BasicsTest < ActiveRecord::TestCase end end end + + test "preventing writes applies to all connections on a handler" do + conn1_error = assert_raises ActiveRecord::ReadOnlyError do + ActiveRecord::Base.connection_handler.while_preventing_writes do + assert_equal ActiveRecord::Base.connection, Bird.connection + assert_not_equal ARUnit2Model.connection, Bird.connection + Bird.create!(name: "Bluejay") + end + end + + assert_match %r/\AWrite query attempted while in readonly mode: INSERT /, conn1_error.message + + conn2_error = assert_raises ActiveRecord::ReadOnlyError do + ActiveRecord::Base.connection_handler.while_preventing_writes do + assert_not_equal ActiveRecord::Base.connection, Professor.connection + assert_equal ARUnit2Model.connection, Professor.connection + Professor.create!(name: "Professor Bluejay") + end + end + + assert_match %r/\AWrite query attempted while in readonly mode: INSERT /, conn2_error.message + end + + unless in_memory_db? + test "preventing writes with multiple handlers" do + ActiveRecord::Base.connects_to(database: { writing: :arunit, reading: :arunit }) + + conn1_error = assert_raises ActiveRecord::ReadOnlyError do + ActiveRecord::Base.connected_to(role: :writing) do + assert_equal :writing, ActiveRecord::Base.current_role + + ActiveRecord::Base.connection_handler.while_preventing_writes do + Bird.create!(name: "Bluejay") + end + end + end + + assert_match %r/\AWrite query attempted while in readonly mode: INSERT /, conn1_error.message + + conn2_error = assert_raises ActiveRecord::ReadOnlyError do + ActiveRecord::Base.connected_to(role: :reading) do + assert_equal :reading, ActiveRecord::Base.current_role + + ActiveRecord::Base.connection_handler.while_preventing_writes do + Bird.create!(name: "Bluejay") + end + end + end + + assert_match %r/\AWrite query attempted while in readonly mode: INSERT /, conn2_error.message + ensure + ActiveRecord::Base.connection_handlers = { writing: ActiveRecord::Base.default_connection_handler } + ActiveRecord::Base.establish_connection(:arunit) + end + end end diff --git a/activerecord/test/cases/batches_test.rb b/activerecord/test/cases/batches_test.rb index cf6e280898..0d0bf39f79 100644 --- a/activerecord/test/cases/batches_test.rb +++ b/activerecord/test/cases/batches_test.rb @@ -146,7 +146,7 @@ class EachTest < ActiveRecord::TestCase def test_find_in_batches_should_quote_batch_order c = Post.connection - assert_sql(/ORDER BY #{c.quote_table_name('posts')}\.#{c.quote_column_name('id')}/) do + assert_sql(/ORDER BY #{Regexp.escape(c.quote_table_name("posts.id"))}/i) do Post.find_in_batches(batch_size: 1) do |batch| assert_kind_of Array, batch assert_kind_of Post, batch.first diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb index 85685d1d00..720446b39d 100644 --- a/activerecord/test/cases/bind_parameter_test.rb +++ b/activerecord/test/cases/bind_parameter_test.rb @@ -93,7 +93,7 @@ if ActiveRecord::Base.connection.prepared_statements def test_statement_cache_with_in_clause @connection.clear_cache! - topics = Topic.where(id: [1, 3]) + topics = Topic.where(id: [1, 3]).order(:id) assert_equal [1, 3], topics.map(&:id) assert_not_includes statement_cache, to_sql_key(topics.arel) end diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index e42af3686e..dbd1d03c4c 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -139,6 +139,13 @@ class CalculationsTest < ActiveRecord::TestCase end end + def test_should_not_use_alias_for_grouped_field + assert_sql(/GROUP BY #{Regexp.escape(Account.connection.quote_table_name("accounts.firm_id"))}/i) do + c = Account.group(:firm_id).order("accounts_firm_id").sum(:credit_limit) + assert_equal [1, 2, 6, 9], c.keys.compact + end + end + def test_should_order_by_grouped_field c = Account.group(:firm_id).order("firm_id").sum(:credit_limit) assert_equal [1, 2, 6, 9], c.keys.compact @@ -589,11 +596,7 @@ class CalculationsTest < ActiveRecord::TestCase end def test_should_sum_expression - if current_adapter?(:SQLite3Adapter, :Mysql2Adapter, :PostgreSQLAdapter, :OracleAdapter) - assert_equal 636, Account.sum("2 * credit_limit") - else - assert_equal 636, Account.sum("2 * credit_limit").to_i - end + assert_equal 636, Account.sum("2 * credit_limit") end def test_sum_expression_returns_zero_when_no_records_to_sum @@ -771,6 +774,12 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal [[2, 2], [4, 4]], Reply.includes(:topic).pluck(:id, :"topics.id") end + def test_group_by_with_order_by_virtual_count_attribute + expected = { "SpecialPost" => 1, "StiPost" => 2 } + actual = Post.group(:type).order(:count).limit(2).maximum(:comments_count) + assert_equal expected, actual + end if current_adapter?(:PostgreSQLAdapter) + def test_group_by_with_limit expected = { "Post" => 8, "SpecialPost" => 1 } actual = Post.includes(:comments).group(:type).order(:type).limit(2).count("comments.id") diff --git a/activerecord/test/cases/connection_adapters/connection_handler_test.rb b/activerecord/test/cases/connection_adapters/connection_handler_test.rb index 6282759a10..843242a897 100644 --- a/activerecord/test/cases/connection_adapters/connection_handler_test.rb +++ b/activerecord/test/cases/connection_adapters/connection_handler_test.rb @@ -29,7 +29,7 @@ module ActiveRecord def test_establish_connection_uses_spec_name old_config = ActiveRecord::Base.configurations - config = { "readonly" => { "adapter" => "sqlite3" } } + config = { "readonly" => { "adapter" => "sqlite3", "pool" => "5" } } ActiveRecord::Base.configurations = config resolver = ConnectionAdapters::ConnectionSpecification::Resolver.new(ActiveRecord::Base.configurations) spec = resolver.spec(:readonly) @@ -367,11 +367,24 @@ module ActiveRecord assert_same klass2.connection, ActiveRecord::Base.connection end + class ApplicationRecord < ActiveRecord::Base + self.abstract_class = true + end + + class MyClass < ApplicationRecord + end + def test_connection_specification_name_should_fallback_to_parent klassA = Class.new(Base) klassB = Class.new(klassA) + klassC = Class.new(MyClass) assert_equal klassB.connection_specification_name, klassA.connection_specification_name + assert_equal klassC.connection_specification_name, klassA.connection_specification_name + + assert_equal "primary", klassA.connection_specification_name + assert_equal "primary", klassC.connection_specification_name + klassA.connection_specification_name = "readonly" assert_equal "readonly", klassB.connection_specification_name end diff --git a/activerecord/test/cases/connection_adapters/merge_and_resolve_default_url_config_test.rb b/activerecord/test/cases/connection_adapters/merge_and_resolve_default_url_config_test.rb index 515bf5df06..15a045ed23 100644 --- a/activerecord/test/cases/connection_adapters/merge_and_resolve_default_url_config_test.rb +++ b/activerecord/test/cases/connection_adapters/merge_and_resolve_default_url_config_test.rb @@ -244,6 +244,25 @@ module ActiveRecord assert_equal expected, actual end + def test_no_url_sub_key_with_database_url_doesnt_trample_other_envs + ENV["DATABASE_URL"] = "postgres://localhost/baz" + + config = { "default_env" => { "database" => "foo" }, "other_env" => { "url" => "postgres://foohost/bardb" } } + actual = resolve_config(config) + expected = { "default_env" => + { "database" => "baz", + "adapter" => "postgresql", + "host" => "localhost" + }, + "other_env" => + { "adapter" => "postgresql", + "database" => "bardb", + "host" => "foohost" + } + } + assert_equal expected, actual + end + def test_merge_no_conflicts_with_database_url ENV["DATABASE_URL"] = "postgres://localhost/foo" @@ -273,6 +292,61 @@ module ActiveRecord } assert_equal expected, actual end + + def test_merge_no_conflicts_with_database_url_and_adapter + ENV["DATABASE_URL"] = "postgres://localhost/foo" + + config = { "default_env" => { "adapter" => "postgresql", "pool" => "5" } } + actual = resolve_config(config) + expected = { "default_env" => + { "adapter" => "postgresql", + "database" => "foo", + "host" => "localhost", + "pool" => "5" + } + } + assert_equal expected, actual + end + + def test_merge_no_conflicts_with_database_url_and_numeric_pool + ENV["DATABASE_URL"] = "postgres://localhost/foo" + + config = { "default_env" => { "pool" => 5 } } + actual = resolve_config(config) + expected = { "default_env" => + { "adapter" => "postgresql", + "database" => "foo", + "host" => "localhost", + "pool" => 5 + } + } + + assert_equal expected, actual + end + + def test_tiered_configs_with_database_url + ENV["DATABASE_URL"] = "postgres://localhost/foo" + + config = { + "default_env" => { + "primary" => { "pool" => 5 }, + "animals" => { "pool" => 5 } + } + } + + expected = { + "adapter" => "postgresql", + "database" => "foo", + "host" => "localhost", + "pool" => 5 + } + + ["primary", "animals"].each do |spec_name| + configs = ActiveRecord::DatabaseConfigurations.new(config) + actual = configs.configs_for(env_name: "default_env", spec_name: spec_name).config + assert_equal expected, actual + end + end end end end diff --git a/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb b/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb index 38331aa641..774380d7e0 100644 --- a/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb +++ b/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb @@ -40,7 +40,7 @@ if current_adapter?(:Mysql2Adapter) end def test_enum_type_with_value_matching_other_type - assert_lookup_type :string, "ENUM('unicode', '8bit', 'none')" + assert_lookup_type :string, "ENUM('unicode', '8bit', 'none', 'time')" end def test_binary_types @@ -58,7 +58,6 @@ if current_adapter?(:Mysql2Adapter) end private - def assert_lookup_type(type, lookup) cast_type = @connection.send(:type_map).lookup(lookup) assert_equal type, cast_type.type diff --git a/activerecord/test/cases/connection_adapters/type_lookup_test.rb b/activerecord/test/cases/connection_adapters/type_lookup_test.rb index 1c79d776f0..e92bb40632 100644 --- a/activerecord/test/cases/connection_adapters/type_lookup_test.rb +++ b/activerecord/test/cases/connection_adapters/type_lookup_test.rb @@ -109,7 +109,6 @@ unless current_adapter?(:PostgreSQLAdapter) # PostgreSQL does not use type strin end private - def assert_lookup_type(type, lookup) cast_type = @connection.send(:type_map).lookup(lookup) assert_equal type, cast_type.type diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb index a15ad9a45b..ccbb6e16cd 100644 --- a/activerecord/test/cases/connection_pool_test.rb +++ b/activerecord/test/cases/connection_pool_test.rb @@ -507,7 +507,6 @@ module ActiveRecord pool.schema_cache = schema_cache pool.with_connection do |conn| - assert_not_same pool.schema_cache, conn.schema_cache assert_equal pool.schema_cache.size, conn.schema_cache.size assert_same pool.schema_cache.columns(:posts), conn.schema_cache.columns(:posts) end @@ -695,6 +694,28 @@ module ActiveRecord end end + def test_public_connections_access_threadsafe + _conn1 = @pool.checkout + conn2 = @pool.checkout + + connections = @pool.connections + found_conn = nil + + # Without assuming too much about implementation + # details make sure that a concurrent change to + # the pool is thread-safe. + connections.each_index do |idx| + if connections[idx] == conn2 + Thread.new do + @pool.remove(conn2) + end.join + end + found_conn = connections[idx] + end + + assert_not_nil found_conn + end + private def with_single_connection_pool one_conn_spec = ActiveRecord::Base.connection_pool.spec.dup diff --git a/activerecord/test/cases/database_statements_test.rb b/activerecord/test/cases/database_statements_test.rb index 1c934602ec..119d48b85e 100644 --- a/activerecord/test/cases/database_statements_test.rb +++ b/activerecord/test/cases/database_statements_test.rb @@ -23,7 +23,6 @@ class DatabaseStatementsTest < ActiveRecord::TestCase end private - def return_the_inserted_id(method:) # Oracle adapter uses prefetched primary key values from sequence and passes them to connection adapter insert method if current_adapter?(:OracleAdapter) diff --git a/activerecord/test/cases/explain_test.rb b/activerecord/test/cases/explain_test.rb index a0e75f4e89..edd2c768d3 100644 --- a/activerecord/test/cases/explain_test.rb +++ b/activerecord/test/cases/explain_test.rb @@ -72,7 +72,6 @@ if ActiveRecord::Base.connection.supports_explain? end private - def stub_explain_for_query_plans(query_plans = ["query plan foo", "query plan bar"]) explain_called = 0 diff --git a/activerecord/test/cases/finder_respond_to_test.rb b/activerecord/test/cases/finder_respond_to_test.rb index 66413a98e4..d9e88b3feb 100644 --- a/activerecord/test/cases/finder_respond_to_test.rb +++ b/activerecord/test/cases/finder_respond_to_test.rb @@ -54,7 +54,6 @@ class FinderRespondToTest < ActiveRecord::TestCase end private - def ensure_topic_method_is_not_cached(method_id) Topic.singleton_class.remove_method method_id if Topic.public_methods.include? method_id end diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index ca114d468e..1f2058cc0a 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -245,7 +245,8 @@ class FinderTest < ActiveRecord::TestCase end def test_exists_does_not_select_columns_without_alias - assert_sql(/SELECT\W+1 AS one FROM ["`]topics["`]/i) do + c = Topic.connection + assert_sql(/SELECT 1 AS one FROM #{Regexp.escape(c.quote_table_name("topics"))}/i) do Topic.exists? end end @@ -282,6 +283,11 @@ class FinderTest < ActiveRecord::TestCase assert_not Post.select(:body).distinct.offset(4).exists? end + def test_exists_with_distinct_and_offset_and_eagerload_and_order + assert Post.eager_load(:comments).distinct.offset(10).merge(Comment.order(post_id: :asc)).exists? + assert_not Post.eager_load(:comments).distinct.offset(11).merge(Comment.order(post_id: :asc)).exists? + end + # Ensure +exists?+ runs without an error by excluding distinct value. # See https://github.com/rails/rails/pull/26981. def test_exists_with_order_and_distinct @@ -517,6 +523,7 @@ class FinderTest < ActiveRecord::TestCase expected.touch # PostgreSQL changes the default order if no order clause is used assert_equal expected, Topic.first assert_equal expected, Topic.limit(5).first + assert_equal expected, Topic.order(nil).first end def test_model_class_responds_to_first_bang @@ -540,6 +547,7 @@ class FinderTest < ActiveRecord::TestCase expected.touch # PostgreSQL changes the default order if no order clause is used assert_equal expected, Topic.second assert_equal expected, Topic.limit(5).second + assert_equal expected, Topic.order(nil).second end def test_model_class_responds_to_second_bang @@ -563,6 +571,7 @@ class FinderTest < ActiveRecord::TestCase expected.touch # PostgreSQL changes the default order if no order clause is used assert_equal expected, Topic.third assert_equal expected, Topic.limit(5).third + assert_equal expected, Topic.order(nil).third end def test_model_class_responds_to_third_bang @@ -586,6 +595,7 @@ class FinderTest < ActiveRecord::TestCase expected.touch # PostgreSQL changes the default order if no order clause is used assert_equal expected, Topic.fourth assert_equal expected, Topic.limit(5).fourth + assert_equal expected, Topic.order(nil).fourth end def test_model_class_responds_to_fourth_bang @@ -609,6 +619,7 @@ class FinderTest < ActiveRecord::TestCase expected.touch # PostgreSQL changes the default order if no order clause is used assert_equal expected, Topic.fifth assert_equal expected, Topic.limit(5).fifth + assert_equal expected, Topic.order(nil).fifth end def test_model_class_responds_to_fifth_bang @@ -777,6 +788,7 @@ class FinderTest < ActiveRecord::TestCase assert_equal expected, clients.first(2) assert_equal expected, clients.limit(5).first(2) + assert_equal expected, clients.order(nil).first(2) end def test_implicit_order_column_is_configurable diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 0cb868da6e..a7f01e898e 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -948,7 +948,6 @@ class TransactionalFixturesOnConnectionNotification < ActiveRecord::TestCase end private - def fire_connection_notification(connection) assert_called_with(ActiveRecord::Base.connection_handler, :retrieve_connection, ["book"], returns: connection) do message_bus = ActiveSupport::Notifications.instrumenter @@ -1367,7 +1366,6 @@ class MultipleDatabaseFixturesTest < ActiveRecord::TestCase end private - def with_temporary_connection_pool old_pool = ActiveRecord::Base.connection_handler.retrieve_connection_pool(ActiveRecord::Base.connection_specification_name) new_pool = ActiveRecord::ConnectionAdapters::ConnectionPool.new ActiveRecord::Base.connection_pool.spec diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index 543a0aeb39..56c780c4a6 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -189,7 +189,6 @@ end module InTimeZone private - def in_time_zone(zone) old_zone = Time.zone old_tz = ActiveRecord::Base.time_zone_aware_attributes diff --git a/activerecord/test/cases/hot_compatibility_test.rb b/activerecord/test/cases/hot_compatibility_test.rb index 7b388ebc5e..f41aea6125 100644 --- a/activerecord/test/cases/hot_compatibility_test.rb +++ b/activerecord/test/cases/hot_compatibility_test.rb @@ -115,7 +115,6 @@ class HotCompatibilityTest < ActiveRecord::TestCase end private - def get_prepared_statement_cache(connection) connection.instance_variable_get(:@statements) .instance_variable_get(:@cache)[Process.pid] diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb index 629167e9ed..01e4878c3f 100644 --- a/activerecord/test/cases/inheritance_test.rb +++ b/activerecord/test/cases/inheritance_test.rb @@ -471,9 +471,9 @@ class InheritanceTest < ActiveRecord::TestCase end def test_eager_load_belongs_to_primary_key_quoting - con = Account.connection + c = Account.connection bind_param = Arel::Nodes::BindParam.new(nil) - assert_sql(/#{con.quote_table_name('companies')}\.#{con.quote_column_name('id')} = (?:#{Regexp.quote(bind_param.to_sql)}|1)/) do + assert_sql(/#{Regexp.escape(c.quote_table_name("companies.id"))} = (?:#{Regexp.escape(bind_param.to_sql)}|1)/i) do Account.all.merge!(includes: :firm).find(1) end end diff --git a/activerecord/test/cases/insert_all_test.rb b/activerecord/test/cases/insert_all_test.rb index f24c63031c..d086d77081 100644 --- a/activerecord/test/cases/insert_all_test.rb +++ b/activerecord/test/cases/insert_all_test.rb @@ -262,7 +262,6 @@ class InsertAllTest < ActiveRecord::TestCase end private - def capture_log_output output = StringIO.new old_logger, ActiveRecord::Base.logger = ActiveRecord::Base.logger, ActiveSupport::Logger.new(output) diff --git a/activerecord/test/cases/json_serialization_test.rb b/activerecord/test/cases/json_serialization_test.rb index 82cf281cff..d68e208617 100644 --- a/activerecord/test/cases/json_serialization_test.rb +++ b/activerecord/test/cases/json_serialization_test.rb @@ -10,7 +10,6 @@ require "models/comment" module JsonSerializationHelpers private - def set_include_root_in_json(value) original_root_in_json = ActiveRecord::Base.include_root_in_json ActiveRecord::Base.include_root_in_json = value @@ -24,7 +23,7 @@ class JsonSerializationTest < ActiveRecord::TestCase include JsonSerializationHelpers class NamespacedContact < Contact - column :name, :string + column :name, "string" end def setup diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb index 04f9b26960..b468da7c76 100644 --- a/activerecord/test/cases/locking_test.rb +++ b/activerecord/test/cases/locking_test.rb @@ -593,7 +593,6 @@ class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase end private - def add_counter_column_to(model, col = "test_count") model.connection.add_column model.table_name, col, :integer, null: false, default: 0 model.reset_column_information diff --git a/activerecord/test/cases/migration/compatibility_test.rb b/activerecord/test/cases/migration/compatibility_test.rb index 726ccf925e..ff2a694e66 100644 --- a/activerecord/test/cases/migration/compatibility_test.rb +++ b/activerecord/test/cases/migration/compatibility_test.rb @@ -12,6 +12,7 @@ module ActiveRecord def setup super @connection = ActiveRecord::Base.connection + @schema_migration = @connection.schema_migration @verbose_was = ActiveRecord::Migration.verbose ActiveRecord::Migration.verbose = false @@ -38,7 +39,7 @@ module ActiveRecord }.new assert connection.index_exists?(:testings, :foo, name: "custom_index_name") - assert_raise(StandardError) { ActiveRecord::Migrator.new(:up, [migration]).migrate } + assert_raise(StandardError) { ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate } assert connection.index_exists?(:testings, :foo, name: "custom_index_name") end @@ -53,7 +54,7 @@ module ActiveRecord }.new assert connection.index_exists?(:testings, :bar) - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate assert_not connection.index_exists?(:testings, :bar) end @@ -67,7 +68,7 @@ module ActiveRecord end }.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate assert_not connection.index_exists?(:more_testings, :foo_id) assert_not connection.index_exists?(:more_testings, :bar_id) @@ -84,7 +85,7 @@ module ActiveRecord end }.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate assert connection.column_exists?(:more_testings, :created_at, null: true) assert connection.column_exists?(:more_testings, :updated_at, null: true) @@ -101,7 +102,7 @@ module ActiveRecord end }.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate assert connection.column_exists?(:testings, :created_at, null: true) assert connection.column_exists?(:testings, :updated_at, null: true) @@ -117,7 +118,7 @@ module ActiveRecord end }.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate assert connection.column_exists?(:testings, :created_at, null: true) assert connection.column_exists?(:testings, :updated_at, null: true) @@ -131,7 +132,7 @@ module ActiveRecord end }.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate assert connection.column_exists?(:testings, :created_at, null: true) assert connection.column_exists?(:testings, :updated_at, null: true) @@ -146,7 +147,7 @@ module ActiveRecord end }.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate assert connection.column_exists?(:more_testings, :created_at, null: false, **precision_implicit_default) assert connection.column_exists?(:more_testings, :updated_at, null: false, **precision_implicit_default) @@ -163,7 +164,7 @@ module ActiveRecord end }.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate assert connection.column_exists?(:testings, :created_at, null: false, **precision_implicit_default) assert connection.column_exists?(:testings, :updated_at, null: false, **precision_implicit_default) @@ -179,7 +180,7 @@ module ActiveRecord end }.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate assert connection.column_exists?(:testings, :created_at, null: false, **precision_implicit_default) assert connection.column_exists?(:testings, :updated_at, null: false, **precision_implicit_default) @@ -193,7 +194,7 @@ module ActiveRecord end }.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate assert connection.column_exists?(:testings, :created_at, null: false, **precision_implicit_default) assert connection.column_exists?(:testings, :updated_at, null: false, **precision_implicit_default) @@ -230,7 +231,7 @@ module ActiveRecord end }.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate assert connection.column_exists?(:testings, :foo, comment: "comment") end @@ -243,7 +244,7 @@ module ActiveRecord end }.new - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate assert_equal "comment", connection.table_comment("testings") end @@ -261,7 +262,7 @@ module ActiveRecord }.new Testing.create! - ActiveRecord::Migrator.new(:up, [migration]).migrate + ActiveRecord::Migrator.new(:up, [migration], @schema_migration).migrate assert_equal ["foobar"], Testing.all.map(&:foo) ensure ActiveRecord::Base.clear_cache! diff --git a/activerecord/test/cases/migration/create_join_table_test.rb b/activerecord/test/cases/migration/create_join_table_test.rb index e0cbb29dcf..0257545330 100644 --- a/activerecord/test/cases/migration/create_join_table_test.rb +++ b/activerecord/test/cases/migration/create_join_table_test.rb @@ -151,7 +151,6 @@ module ActiveRecord end private - def with_table_cleanup tables_before = connection.data_sources diff --git a/activerecord/test/cases/migration/helper.rb b/activerecord/test/cases/migration/helper.rb index c056199140..da8bdc472a 100644 --- a/activerecord/test/cases/migration/helper.rb +++ b/activerecord/test/cases/migration/helper.rb @@ -34,7 +34,6 @@ module ActiveRecord end private - delegate(*CONNECTION_METHODS, to: :connection) end end diff --git a/activerecord/test/cases/migration/logger_test.rb b/activerecord/test/cases/migration/logger_test.rb index 28f4cc124b..431047f957 100644 --- a/activerecord/test/cases/migration/logger_test.rb +++ b/activerecord/test/cases/migration/logger_test.rb @@ -17,19 +17,20 @@ module ActiveRecord def setup super - ActiveRecord::SchemaMigration.create_table - ActiveRecord::SchemaMigration.delete_all + @schema_migration = ActiveRecord::Base.connection.schema_migration + @schema_migration.create_table + @schema_migration.delete_all end teardown do - ActiveRecord::SchemaMigration.drop_table + @schema_migration.drop_table end def test_migration_should_be_run_without_logger previous_logger = ActiveRecord::Base.logger ActiveRecord::Base.logger = nil migrations = [Migration.new("a", 1), Migration.new("b", 2), Migration.new("c", 3)] - ActiveRecord::Migrator.new(:up, migrations).migrate + ActiveRecord::Migrator.new(:up, migrations, @schema_migration).migrate ensure ActiveRecord::Base.logger = previous_logger end diff --git a/activerecord/test/cases/migration/references_statements_test.rb b/activerecord/test/cases/migration/references_statements_test.rb index 769241ba12..451894fc54 100644 --- a/activerecord/test/cases/migration/references_statements_test.rb +++ b/activerecord/test/cases/migration/references_statements_test.rb @@ -126,7 +126,6 @@ module ActiveRecord end private - def with_polymorphic_column add_column table_name, :supplier_type, :string add_index table_name, [:supplier_id, :supplier_type] diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 255885b599..20f577b2c5 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -38,6 +38,7 @@ class MigrationTest < ActiveRecord::TestCase end Reminder.reset_column_information @verbose_was, ActiveRecord::Migration.verbose = ActiveRecord::Migration.verbose, false + @schema_migration = ActiveRecord::Base.connection.schema_migration ActiveRecord::Base.connection.schema_cache.clear! end @@ -84,7 +85,7 @@ class MigrationTest < ActiveRecord::TestCase def test_migrator_versions migrations_path = MIGRATIONS_ROOT + "/valid" - migrator = ActiveRecord::MigrationContext.new(migrations_path) + migrator = ActiveRecord::MigrationContext.new(migrations_path, @schema_migration) migrator.up assert_equal 3, migrator.current_version @@ -102,23 +103,23 @@ class MigrationTest < ActiveRecord::TestCase ActiveRecord::Base.connection.drop_table "schema_migrations", if_exists: true migrations_path = MIGRATIONS_ROOT + "/valid" - migrator = ActiveRecord::MigrationContext.new(migrations_path) + migrator = ActiveRecord::MigrationContext.new(migrations_path, @schema_migration) assert_equal true, migrator.needs_migration? end def test_any_migrations - migrator = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/valid") + migrator = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/valid", @schema_migration) assert_predicate migrator, :any_migrations? - migrator_empty = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/empty") + migrator_empty = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/empty", @schema_migration) assert_not_predicate migrator_empty, :any_migrations? end def test_migration_version - migrator = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/version_check") + migrator = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/version_check", @schema_migration) assert_equal 0, migrator.current_version migrator.up(20131219224947) assert_equal 20131219224947, migrator.current_version @@ -190,6 +191,7 @@ class MigrationTest < ActiveRecord::TestCase assert_not_predicate BigNumber, :table_exists? GiveMeBigNumbers.up + assert_predicate BigNumber, :table_exists? BigNumber.reset_column_information assert BigNumber.create( @@ -248,7 +250,7 @@ class MigrationTest < ActiveRecord::TestCase assert_not_predicate Reminder, :table_exists? name_filter = lambda { |migration| migration.name == "ValidPeopleHaveLastNames" } - migrator = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/valid") + migrator = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/valid", @schema_migration) migrator.up(&name_filter) assert_column Person, :last_name @@ -310,7 +312,7 @@ class MigrationTest < ActiveRecord::TestCase end }.new - migrator = ActiveRecord::Migrator.new(:up, [migration], 100) + migrator = ActiveRecord::Migrator.new(:up, [migration], @schema_migration, 100) e = assert_raise(StandardError) { migrator.migrate } @@ -331,7 +333,7 @@ class MigrationTest < ActiveRecord::TestCase end }.new - migrator = ActiveRecord::Migrator.new(:up, [migration], 100) + migrator = ActiveRecord::Migrator.new(:up, [migration], @schema_migration, 100) e = assert_raise(StandardError) { migrator.run } @@ -354,7 +356,7 @@ class MigrationTest < ActiveRecord::TestCase end }.new - migrator = ActiveRecord::Migrator.new(:up, [migration], 101) + migrator = ActiveRecord::Migrator.new(:up, [migration], @schema_migration, 101) e = assert_raise(StandardError) { migrator.migrate } assert_equal "An error has occurred, all later migrations canceled:\n\nSomething broke", e.message @@ -413,7 +415,7 @@ class MigrationTest < ActiveRecord::TestCase def test_internal_metadata_stores_environment current_env = ActiveRecord::ConnectionHandling::DEFAULT_ENV.call migrations_path = MIGRATIONS_ROOT + "/valid" - migrator = ActiveRecord::MigrationContext.new(migrations_path) + migrator = ActiveRecord::MigrationContext.new(migrations_path, @schema_migration) migrator.up assert_equal current_env, ActiveRecord::InternalMetadata[:environment] @@ -441,7 +443,7 @@ class MigrationTest < ActiveRecord::TestCase current_env = ActiveRecord::ConnectionHandling::DEFAULT_ENV.call migrations_path = MIGRATIONS_ROOT + "/valid" - migrator = ActiveRecord::MigrationContext.new(migrations_path) + migrator = ActiveRecord::MigrationContext.new(migrations_path, @schema_migration) migrator.up assert_equal current_env, ActiveRecord::InternalMetadata[:environment] assert_equal "bar", ActiveRecord::InternalMetadata[:foo] @@ -482,6 +484,7 @@ class MigrationTest < ActiveRecord::TestCase Thing.reset_table_name Thing.reset_sequence_name WeNeedThings.up + assert_predicate Thing, :table_exists? Thing.reset_column_information assert Thing.create("content" => "hello world") @@ -502,8 +505,9 @@ class MigrationTest < ActiveRecord::TestCase ActiveRecord::Base.table_name_suffix = "_suffix" Reminder.reset_table_name Reminder.reset_sequence_name - Reminder.reset_column_information WeNeedReminders.up + assert_predicate Reminder, :table_exists? + Reminder.reset_column_information assert Reminder.create("content" => "hello world", "remind_at" => Time.now) assert_equal "hello world", Reminder.first.content @@ -636,7 +640,7 @@ class MigrationTest < ActiveRecord::TestCase if ActiveRecord::Base.connection.supports_advisory_locks? def test_migrator_generates_valid_lock_id migration = Class.new(ActiveRecord::Migration::Current).new - migrator = ActiveRecord::Migrator.new(:up, [migration], 100) + migrator = ActiveRecord::Migrator.new(:up, [migration], @schema_migration, 100) lock_id = migrator.send(:generate_migrator_advisory_lock_id) @@ -650,7 +654,7 @@ class MigrationTest < ActiveRecord::TestCase # It is important we are consistent with how we generate this so that # exclusive locking works across migrator versions migration = Class.new(ActiveRecord::Migration::Current).new - migrator = ActiveRecord::Migrator.new(:up, [migration], 100) + migrator = ActiveRecord::Migrator.new(:up, [migration], @schema_migration, 100) lock_id = migrator.send(:generate_migrator_advisory_lock_id) @@ -672,7 +676,7 @@ class MigrationTest < ActiveRecord::TestCase end }.new - migrator = ActiveRecord::Migrator.new(:up, [migration], 100) + migrator = ActiveRecord::Migrator.new(:up, [migration], @schema_migration, 100) lock_id = migrator.send(:generate_migrator_advisory_lock_id) with_another_process_holding_lock(lock_id) do @@ -693,7 +697,7 @@ class MigrationTest < ActiveRecord::TestCase end }.new - migrator = ActiveRecord::Migrator.new(:up, [migration], 100) + migrator = ActiveRecord::Migrator.new(:up, [migration], @schema_migration, 100) lock_id = migrator.send(:generate_migrator_advisory_lock_id) with_another_process_holding_lock(lock_id) do @@ -706,7 +710,7 @@ class MigrationTest < ActiveRecord::TestCase def test_with_advisory_lock_raises_the_right_error_when_it_fails_to_release_lock migration = Class.new(ActiveRecord::Migration::Current).new - migrator = ActiveRecord::Migrator.new(:up, [migration], 100) + migrator = ActiveRecord::Migrator.new(:up, [migration], @schema_migration, 100) lock_id = migrator.send(:generate_migrator_advisory_lock_id) e = assert_raises(ActiveRecord::ConcurrentMigrationError) do @@ -935,7 +939,6 @@ if ActiveRecord::Base.connection.supports_bulk_alter? end private - def with_bulk_change_table # Reset columns/indexes cache as we're changing the table @columns = @indexes = nil diff --git a/activerecord/test/cases/migrator_test.rb b/activerecord/test/cases/migrator_test.rb index 30e199f1c5..aeba8e1d14 100644 --- a/activerecord/test/cases/migrator_test.rb +++ b/activerecord/test/cases/migrator_test.rb @@ -23,8 +23,9 @@ class MigratorTest < ActiveRecord::TestCase def setup super - ActiveRecord::SchemaMigration.create_table - ActiveRecord::SchemaMigration.delete_all rescue nil + @schema_migration = ActiveRecord::Base.connection.schema_migration + @schema_migration.create_table + @schema_migration.delete_all rescue nil @verbose_was = ActiveRecord::Migration.verbose ActiveRecord::Migration.message_count = 0 ActiveRecord::Migration.class_eval do @@ -36,7 +37,7 @@ class MigratorTest < ActiveRecord::TestCase end teardown do - ActiveRecord::SchemaMigration.delete_all rescue nil + @schema_migration.delete_all rescue nil ActiveRecord::Migration.verbose = @verbose_was ActiveRecord::Migration.class_eval do undef :puts @@ -49,7 +50,7 @@ class MigratorTest < ActiveRecord::TestCase def test_migrator_with_duplicate_names e = assert_raises(ActiveRecord::DuplicateMigrationNameError) do list = [ActiveRecord::Migration.new("Chunky"), ActiveRecord::Migration.new("Chunky")] - ActiveRecord::Migrator.new(:up, list) + ActiveRecord::Migrator.new(:up, list, @schema_migration) end assert_match(/Multiple migrations have the name Chunky/, e.message) end @@ -57,39 +58,40 @@ class MigratorTest < ActiveRecord::TestCase def test_migrator_with_duplicate_versions assert_raises(ActiveRecord::DuplicateMigrationVersionError) do list = [ActiveRecord::Migration.new("Foo", 1), ActiveRecord::Migration.new("Bar", 1)] - ActiveRecord::Migrator.new(:up, list) + ActiveRecord::Migrator.new(:up, list, @schema_migration) end end def test_migrator_with_missing_version_numbers assert_raises(ActiveRecord::UnknownMigrationVersionError) do list = [ActiveRecord::Migration.new("Foo", 1), ActiveRecord::Migration.new("Bar", 2)] - ActiveRecord::Migrator.new(:up, list, 3).run + ActiveRecord::Migrator.new(:up, list, @schema_migration, 3).run end assert_raises(ActiveRecord::UnknownMigrationVersionError) do list = [ActiveRecord::Migration.new("Foo", 1), ActiveRecord::Migration.new("Bar", 2)] - ActiveRecord::Migrator.new(:up, list, -1).run + ActiveRecord::Migrator.new(:up, list, @schema_migration, -1).run end assert_raises(ActiveRecord::UnknownMigrationVersionError) do list = [ActiveRecord::Migration.new("Foo", 1), ActiveRecord::Migration.new("Bar", 2)] - ActiveRecord::Migrator.new(:up, list, 0).run + ActiveRecord::Migrator.new(:up, list, @schema_migration, 0).run end assert_raises(ActiveRecord::UnknownMigrationVersionError) do list = [ActiveRecord::Migration.new("Foo", 1), ActiveRecord::Migration.new("Bar", 2)] - ActiveRecord::Migrator.new(:up, list, 3).migrate + ActiveRecord::Migrator.new(:up, list, @schema_migration, 3).migrate end assert_raises(ActiveRecord::UnknownMigrationVersionError) do list = [ActiveRecord::Migration.new("Foo", 1), ActiveRecord::Migration.new("Bar", 2)] - ActiveRecord::Migrator.new(:up, list, -1).migrate + ActiveRecord::Migrator.new(:up, list, @schema_migration, -1).migrate end end def test_finds_migrations - migrations = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/valid").migrations + schema_migration = ActiveRecord::Base.connection.schema_migration + migrations = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/valid", schema_migration).migrations [[1, "ValidPeopleHaveLastNames"], [2, "WeNeedReminders"], [3, "InnocentJointable"]].each_with_index do |pair, i| assert_equal migrations[i].version, pair.first @@ -98,7 +100,8 @@ class MigratorTest < ActiveRecord::TestCase end def test_finds_migrations_in_subdirectories - migrations = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/valid_with_subdirectories").migrations + schema_migration = ActiveRecord::Base.connection.schema_migration + migrations = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/valid_with_subdirectories", schema_migration).migrations [[1, "ValidPeopleHaveLastNames"], [2, "WeNeedReminders"], [3, "InnocentJointable"]].each_with_index do |pair, i| assert_equal migrations[i].version, pair.first @@ -107,8 +110,9 @@ class MigratorTest < ActiveRecord::TestCase end def test_finds_migrations_from_two_directories + schema_migration = ActiveRecord::Base.connection.schema_migration directories = [MIGRATIONS_ROOT + "/valid_with_timestamps", MIGRATIONS_ROOT + "/to_copy_with_timestamps"] - migrations = ActiveRecord::MigrationContext.new(directories).migrations + migrations = ActiveRecord::MigrationContext.new(directories, schema_migration).migrations [[20090101010101, "PeopleHaveHobbies"], [20090101010202, "PeopleHaveDescriptions"], @@ -121,14 +125,16 @@ class MigratorTest < ActiveRecord::TestCase end def test_finds_migrations_in_numbered_directory - migrations = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/10_urban").migrations + schema_migration = ActiveRecord::Base.connection.schema_migration + migrations = ActiveRecord::MigrationContext.new(MIGRATIONS_ROOT + "/10_urban", schema_migration).migrations assert_equal 9, migrations[0].version assert_equal "AddExpressions", migrations[0].name end def test_relative_migrations + schema_migration = ActiveRecord::Base.connection.schema_migration list = Dir.chdir(MIGRATIONS_ROOT) do - ActiveRecord::MigrationContext.new("valid").migrations + ActiveRecord::MigrationContext.new("valid", schema_migration).migrations end migration_proxy = list.find { |item| @@ -138,9 +144,9 @@ class MigratorTest < ActiveRecord::TestCase end def test_finds_pending_migrations - ActiveRecord::SchemaMigration.create!(version: "1") + @schema_migration.create!(version: "1") migration_list = [ActiveRecord::Migration.new("foo", 1), ActiveRecord::Migration.new("bar", 3)] - migrations = ActiveRecord::Migrator.new(:up, migration_list).pending_migrations + migrations = ActiveRecord::Migrator.new(:up, migration_list, @schema_migration).pending_migrations assert_equal 1, migrations.size assert_equal migration_list.last, migrations.first @@ -148,35 +154,38 @@ class MigratorTest < ActiveRecord::TestCase def test_migrations_status path = MIGRATIONS_ROOT + "/valid" + schema_migration = ActiveRecord::Base.connection.schema_migration - ActiveRecord::SchemaMigration.create(version: 2) - ActiveRecord::SchemaMigration.create(version: 10) + @schema_migration.create(version: 2) + @schema_migration.create(version: 10) assert_equal [ ["down", "001", "Valid people have last names"], ["up", "002", "We need reminders"], ["down", "003", "Innocent jointable"], ["up", "010", "********** NO FILE **********"], - ], ActiveRecord::MigrationContext.new(path).migrations_status + ], ActiveRecord::MigrationContext.new(path, schema_migration).migrations_status end def test_migrations_status_in_subdirectories path = MIGRATIONS_ROOT + "/valid_with_subdirectories" + schema_migration = ActiveRecord::Base.connection.schema_migration - ActiveRecord::SchemaMigration.create(version: 2) - ActiveRecord::SchemaMigration.create(version: 10) + @schema_migration.create(version: 2) + @schema_migration.create(version: 10) assert_equal [ ["down", "001", "Valid people have last names"], ["up", "002", "We need reminders"], ["down", "003", "Innocent jointable"], ["up", "010", "********** NO FILE **********"], - ], ActiveRecord::MigrationContext.new(path).migrations_status + ], ActiveRecord::MigrationContext.new(path, schema_migration).migrations_status end def test_migrations_status_with_schema_define_in_subdirectories path = MIGRATIONS_ROOT + "/valid_with_subdirectories" prev_paths = ActiveRecord::Migrator.migrations_paths + schema_migration = ActiveRecord::Base.connection.schema_migration ActiveRecord::Migrator.migrations_paths = path ActiveRecord::Schema.define(version: 3) do @@ -186,16 +195,17 @@ class MigratorTest < ActiveRecord::TestCase ["up", "001", "Valid people have last names"], ["up", "002", "We need reminders"], ["up", "003", "Innocent jointable"], - ], ActiveRecord::MigrationContext.new(path).migrations_status + ], ActiveRecord::MigrationContext.new(path, schema_migration).migrations_status ensure ActiveRecord::Migrator.migrations_paths = prev_paths end def test_migrations_status_from_two_directories paths = [MIGRATIONS_ROOT + "/valid_with_timestamps", MIGRATIONS_ROOT + "/to_copy_with_timestamps"] + schema_migration = ActiveRecord::Base.connection.schema_migration - ActiveRecord::SchemaMigration.create(version: "20100101010101") - ActiveRecord::SchemaMigration.create(version: "20160528010101") + @schema_migration.create(version: "20100101010101") + @schema_migration.create(version: "20160528010101") assert_equal [ ["down", "20090101010101", "People have hobbies"], @@ -204,18 +214,18 @@ class MigratorTest < ActiveRecord::TestCase ["down", "20100201010101", "Valid with timestamps we need reminders"], ["down", "20100301010101", "Valid with timestamps innocent jointable"], ["up", "20160528010101", "********** NO FILE **********"], - ], ActiveRecord::MigrationContext.new(paths).migrations_status + ], ActiveRecord::MigrationContext.new(paths, schema_migration).migrations_status end def test_migrator_interleaved_migrations pass_one = [Sensor.new("One", 1)] - ActiveRecord::Migrator.new(:up, pass_one).migrate + ActiveRecord::Migrator.new(:up, pass_one, @schema_migration).migrate assert pass_one.first.went_up assert_not pass_one.first.went_down pass_two = [Sensor.new("One", 1), Sensor.new("Three", 3)] - ActiveRecord::Migrator.new(:up, pass_two).migrate + ActiveRecord::Migrator.new(:up, pass_two, @schema_migration).migrate assert_not pass_two[0].went_up assert pass_two[1].went_up assert pass_two.all? { |x| !x.went_down } @@ -224,7 +234,7 @@ class MigratorTest < ActiveRecord::TestCase Sensor.new("Two", 2), Sensor.new("Three", 3)] - ActiveRecord::Migrator.new(:down, pass_three).migrate + ActiveRecord::Migrator.new(:down, pass_three, @schema_migration).migrate assert pass_three[0].went_down assert_not pass_three[1].went_down assert pass_three[2].went_down @@ -232,7 +242,7 @@ class MigratorTest < ActiveRecord::TestCase def test_up_calls_up migrations = [Sensor.new(nil, 0), Sensor.new(nil, 1), Sensor.new(nil, 2)] - migrator = ActiveRecord::Migrator.new(:up, migrations) + migrator = ActiveRecord::Migrator.new(:up, migrations, @schema_migration) migrator.migrate assert migrations.all?(&:went_up) assert migrations.all? { |m| !m.went_down } @@ -243,7 +253,7 @@ class MigratorTest < ActiveRecord::TestCase test_up_calls_up migrations = [Sensor.new(nil, 0), Sensor.new(nil, 1), Sensor.new(nil, 2)] - migrator = ActiveRecord::Migrator.new(:down, migrations) + migrator = ActiveRecord::Migrator.new(:down, migrations, @schema_migration) migrator.migrate assert migrations.all? { |m| !m.went_up } assert migrations.all?(&:went_down) @@ -251,30 +261,31 @@ class MigratorTest < ActiveRecord::TestCase end def test_current_version - ActiveRecord::SchemaMigration.create!(version: "1000") - migrator = ActiveRecord::MigrationContext.new("db/migrate") + @schema_migration.create!(version: "1000") + schema_migration = ActiveRecord::Base.connection.schema_migration + migrator = ActiveRecord::MigrationContext.new("db/migrate", schema_migration) assert_equal 1000, migrator.current_version end def test_migrator_one_up calls, migrations = sensors(3) - ActiveRecord::Migrator.new(:up, migrations, 1).migrate + ActiveRecord::Migrator.new(:up, migrations, @schema_migration, 1).migrate assert_equal [[:up, 1]], calls calls.clear - ActiveRecord::Migrator.new(:up, migrations, 2).migrate + ActiveRecord::Migrator.new(:up, migrations, @schema_migration, 2).migrate assert_equal [[:up, 2]], calls end def test_migrator_one_down calls, migrations = sensors(3) - ActiveRecord::Migrator.new(:up, migrations).migrate + ActiveRecord::Migrator.new(:up, migrations, @schema_migration).migrate assert_equal [[:up, 1], [:up, 2], [:up, 3]], calls calls.clear - ActiveRecord::Migrator.new(:down, migrations, 1).migrate + ActiveRecord::Migrator.new(:down, migrations, @schema_migration, 1).migrate assert_equal [[:down, 3], [:down, 2]], calls end @@ -282,17 +293,17 @@ class MigratorTest < ActiveRecord::TestCase def test_migrator_one_up_one_down calls, migrations = sensors(3) - ActiveRecord::Migrator.new(:up, migrations, 1).migrate + ActiveRecord::Migrator.new(:up, migrations, @schema_migration, 1).migrate assert_equal [[:up, 1]], calls calls.clear - ActiveRecord::Migrator.new(:down, migrations, 0).migrate + ActiveRecord::Migrator.new(:down, migrations, @schema_migration, 0).migrate assert_equal [[:down, 1]], calls end def test_migrator_double_up calls, migrations = sensors(3) - migrator = ActiveRecord::Migrator.new(:up, migrations, 1) + migrator = ActiveRecord::Migrator.new(:up, migrations, @schema_migration, 1) assert_equal(0, migrator.current_version) migrator.migrate @@ -305,7 +316,7 @@ class MigratorTest < ActiveRecord::TestCase def test_migrator_double_down calls, migrations = sensors(3) - migrator = ActiveRecord::Migrator.new(:up, migrations, 1) + migrator = ActiveRecord::Migrator.new(:up, migrations, @schema_migration, 1) assert_equal 0, migrator.current_version @@ -313,7 +324,7 @@ class MigratorTest < ActiveRecord::TestCase assert_equal [[:up, 1]], calls calls.clear - migrator = ActiveRecord::Migrator.new(:down, migrations, 1) + migrator = ActiveRecord::Migrator.new(:down, migrations, @schema_migration, 1) migrator.run assert_equal [[:down, 1]], calls calls.clear @@ -328,12 +339,12 @@ class MigratorTest < ActiveRecord::TestCase _, migrations = sensors(3) ActiveRecord::Migration.verbose = true - ActiveRecord::Migrator.new(:up, migrations, 1).migrate + ActiveRecord::Migrator.new(:up, migrations, @schema_migration, 1).migrate assert_not_equal 0, ActiveRecord::Migration.message_count ActiveRecord::Migration.message_count = 0 - ActiveRecord::Migrator.new(:down, migrations, 0).migrate + ActiveRecord::Migrator.new(:down, migrations, @schema_migration, 0).migrate assert_not_equal 0, ActiveRecord::Migration.message_count end @@ -341,9 +352,9 @@ class MigratorTest < ActiveRecord::TestCase _, migrations = sensors(3) ActiveRecord::Migration.verbose = false - ActiveRecord::Migrator.new(:up, migrations, 1).migrate + ActiveRecord::Migrator.new(:up, migrations, @schema_migration, 1).migrate assert_equal 0, ActiveRecord::Migration.message_count - ActiveRecord::Migrator.new(:down, migrations, 0).migrate + ActiveRecord::Migrator.new(:down, migrations, @schema_migration, 0).migrate assert_equal 0, ActiveRecord::Migration.message_count end @@ -351,23 +362,24 @@ class MigratorTest < ActiveRecord::TestCase calls, migrations = sensors(3) # migrate up to 1 - ActiveRecord::Migrator.new(:up, migrations, 1).migrate + ActiveRecord::Migrator.new(:up, migrations, @schema_migration, 1).migrate assert_equal [[:up, 1]], calls calls.clear # migrate down to 0 - ActiveRecord::Migrator.new(:down, migrations, 0).migrate + ActiveRecord::Migrator.new(:down, migrations, @schema_migration, 0).migrate assert_equal [[:down, 1]], calls calls.clear # migrate down to 0 again - ActiveRecord::Migrator.new(:down, migrations, 0).migrate + ActiveRecord::Migrator.new(:down, migrations, @schema_migration, 0).migrate assert_equal [], calls end def test_migrator_going_down_due_to_version_target + schema_migration = ActiveRecord::Base.connection.schema_migration calls, migrator = migrator_class(3) - migrator = migrator.new("valid") + migrator = migrator.new("valid", schema_migration) migrator.up(1) assert_equal [[:up, 1]], calls @@ -382,8 +394,9 @@ class MigratorTest < ActiveRecord::TestCase end def test_migrator_output_when_running_multiple_migrations + schema_migration = ActiveRecord::Base.connection.schema_migration _, migrator = migrator_class(3) - migrator = migrator.new("valid") + migrator = migrator.new("valid", schema_migration) result = migrator.migrate assert_equal(3, result.count) @@ -397,8 +410,9 @@ class MigratorTest < ActiveRecord::TestCase end def test_migrator_output_when_running_single_migration + schema_migration = ActiveRecord::Base.connection.schema_migration _, migrator = migrator_class(1) - migrator = migrator.new("valid") + migrator = migrator.new("valid", schema_migration) result = migrator.run(:up, 1) @@ -406,8 +420,9 @@ class MigratorTest < ActiveRecord::TestCase end def test_migrator_rollback + schema_migration = ActiveRecord::Base.connection.schema_migration _, migrator = migrator_class(3) - migrator = migrator.new("valid") + migrator = migrator.new("valid", schema_migration) migrator.migrate assert_equal(3, migrator.current_version) @@ -426,18 +441,20 @@ class MigratorTest < ActiveRecord::TestCase end def test_migrator_db_has_no_schema_migrations_table + schema_migration = ActiveRecord::Base.connection.schema_migration _, migrator = migrator_class(3) - migrator = migrator.new("valid") + migrator = migrator.new("valid", schema_migration) - ActiveRecord::Base.connection.drop_table "schema_migrations", if_exists: true - assert_not ActiveRecord::Base.connection.table_exists?("schema_migrations") + ActiveRecord::SchemaMigration.drop_table + assert_not_predicate ActiveRecord::SchemaMigration, :table_exists? migrator.migrate(1) - assert ActiveRecord::Base.connection.table_exists?("schema_migrations") + assert_predicate ActiveRecord::SchemaMigration, :table_exists? end def test_migrator_forward + schema_migration = ActiveRecord::Base.connection.schema_migration _, migrator = migrator_class(3) - migrator = migrator.new("/valid") + migrator = migrator.new("/valid", schema_migration) migrator.migrate(1) assert_equal(1, migrator.current_version) @@ -450,18 +467,20 @@ class MigratorTest < ActiveRecord::TestCase def test_only_loads_pending_migrations # migrate up to 1 - ActiveRecord::SchemaMigration.create!(version: "1") + @schema_migration.create!(version: "1") + schema_migration = ActiveRecord::Base.connection.schema_migration calls, migrator = migrator_class(3) - migrator = migrator.new("valid") + migrator = migrator.new("valid", schema_migration) migrator.migrate assert_equal [[:up, 2], [:up, 3]], calls end def test_get_all_versions + schema_migration = ActiveRecord::Base.connection.schema_migration _, migrator = migrator_class(3) - migrator = migrator.new("valid") + migrator = migrator.new("valid", schema_migration) migrator.migrate assert_equal([1, 2, 3], migrator.get_all_versions) diff --git a/activerecord/test/cases/multi_db_migrator_test.rb b/activerecord/test/cases/multi_db_migrator_test.rb new file mode 100644 index 0000000000..650b3af6f0 --- /dev/null +++ b/activerecord/test/cases/multi_db_migrator_test.rb @@ -0,0 +1,218 @@ +# frozen_string_literal: true + +require "cases/helper" +require "cases/migration/helper" + +class MultiDbMigratorTest < ActiveRecord::TestCase + self.use_transactional_tests = false + + # Use this class to sense if migrations have gone + # up or down. + class Sensor < ActiveRecord::Migration::Current + attr_reader :went_up, :went_down + + def initialize(name = self.class.name, version = nil) + super + @went_up = false + @went_down = false + end + + def up; @went_up = true; end + def down; @went_down = true; end + end + + def setup + super + @connection_a = ActiveRecord::Base.connection + @connection_b = ARUnit2Model.connection + + @connection_a.schema_migration.create_table + @connection_b.schema_migration.create_table + + @connection_a.schema_migration.delete_all rescue nil + @connection_b.schema_migration.delete_all rescue nil + + @path_a = MIGRATIONS_ROOT + "/valid" + @path_b = MIGRATIONS_ROOT + "/to_copy" + + @schema_migration_a = @connection_a.schema_migration + @migrations_a = ActiveRecord::MigrationContext.new(@path_a, @schema_migration_a).migrations + @schema_migration_b = @connection_b.schema_migration + @migrations_b = ActiveRecord::MigrationContext.new(@path_b, @schema_migration_b).migrations + + @migrations_a_list = [[1, "ValidPeopleHaveLastNames"], [2, "WeNeedReminders"], [3, "InnocentJointable"]] + @migrations_b_list = [[1, "PeopleHaveHobbies"], [2, "PeopleHaveDescriptions"]] + + @verbose_was = ActiveRecord::Migration.verbose + + ActiveRecord::Migration.message_count = 0 + ActiveRecord::Migration.class_eval do + undef :puts + def puts(*) + ActiveRecord::Migration.message_count += 1 + end + end + end + + teardown do + @connection_a.schema_migration.delete_all rescue nil + @connection_b.schema_migration.delete_all rescue nil + + ActiveRecord::Migration.verbose = @verbose_was + ActiveRecord::Migration.class_eval do + undef :puts + def puts(*) + super + end + end + end + + def test_finds_migrations + @migrations_a_list.each_with_index do |pair, i| + assert_equal @migrations_a[i].version, pair.first + assert_equal @migrations_a[i].name, pair.last + end + + @migrations_b_list.each_with_index do |pair, i| + assert_equal @migrations_b[i].version, pair.first + assert_equal @migrations_b[i].name, pair.last + end + end + + def test_migrations_status + @schema_migration_a.create(version: 2) + @schema_migration_a.create(version: 10) + + assert_equal [ + ["down", "001", "Valid people have last names"], + ["up", "002", "We need reminders"], + ["down", "003", "Innocent jointable"], + ["up", "010", "********** NO FILE **********"], + ], ActiveRecord::MigrationContext.new(@path_a, @schema_migration_a).migrations_status + + @schema_migration_b.create(version: 4) + + assert_equal [ + ["down", "001", "People have hobbies"], + ["down", "002", "People have descriptions"], + ["up", "004", "********** NO FILE **********"] + ], ActiveRecord::MigrationContext.new(@path_b, @schema_migration_b).migrations_status + end + + def test_get_all_versions + _, migrator_a = migrator_class(3) + migrator_a = migrator_a.new(@path_a, @schema_migration_a) + + migrator_a.migrate + assert_equal([1, 2, 3], migrator_a.get_all_versions) + + migrator_a.rollback + assert_equal([1, 2], migrator_a.get_all_versions) + + migrator_a.rollback + assert_equal([1], migrator_a.get_all_versions) + + migrator_a.rollback + assert_equal([], migrator_a.get_all_versions) + + _, migrator_b = migrator_class(2) + migrator_b = migrator_b.new(@path_b, @schema_migration_b) + + migrator_b.migrate + assert_equal([1, 2], migrator_b.get_all_versions) + + migrator_b.rollback + assert_equal([1], migrator_b.get_all_versions) + + migrator_b.rollback + assert_equal([], migrator_b.get_all_versions) + end + + def test_finds_pending_migrations + @schema_migration_a.create!(version: "1") + migration_list_a = [ActiveRecord::Migration.new("foo", 1), ActiveRecord::Migration.new("bar", 3)] + migrations_a = ActiveRecord::Migrator.new(:up, migration_list_a, @schema_migration_a).pending_migrations + + assert_equal 1, migrations_a.size + assert_equal migration_list_a.last, migrations_a.first + + @schema_migration_b.create!(version: "1") + migration_list_b = [ActiveRecord::Migration.new("foo", 1), ActiveRecord::Migration.new("bar", 3)] + migrations_b = ActiveRecord::Migrator.new(:up, migration_list_b, @schema_migration_b).pending_migrations + + assert_equal 1, migrations_b.size + assert_equal migration_list_b.last, migrations_b.first + end + + def test_migrator_db_has_no_schema_migrations_table + _, migrator = migrator_class(3) + migrator = migrator.new(@path_a, @schema_migration_a) + + @schema_migration_a.drop_table + assert_not @connection_a.table_exists?("schema_migrations") + migrator.migrate(1) + assert @connection_a.table_exists?("schema_migrations") + + _, migrator = migrator_class(3) + migrator = migrator.new(@path_b, @schema_migration_b) + + @schema_migration_b.drop_table + assert_not @connection_b.table_exists?("schema_migrations") + migrator.migrate(1) + assert @connection_b.table_exists?("schema_migrations") + end + + def test_migrator_forward + _, migrator = migrator_class(3) + migrator = migrator.new(@path_a, @schema_migration_a) + migrator.migrate(1) + assert_equal(1, migrator.current_version) + + migrator.forward(2) + assert_equal(3, migrator.current_version) + + migrator.forward + assert_equal(3, migrator.current_version) + + _, migrator_b = migrator_class(3) + migrator_b = migrator_b.new(@path_b, @schema_migration_b) + migrator_b.migrate(1) + assert_equal(1, migrator_b.current_version) + + migrator_b.forward(2) + assert_equal(3, migrator_b.current_version) + + migrator_b.forward + assert_equal(3, migrator_b.current_version) + end + + private + def m(name, version) + x = Sensor.new name, version + x.extend(Module.new { + define_method(:up) { yield(:up, x); super() } + define_method(:down) { yield(:down, x); super() } + }) if block_given? + end + + def sensors(count) + calls = [] + migrations = count.times.map { |i| + m(nil, i + 1) { |c, migration| + calls << [c, migration.version] + } + } + [calls, migrations] + end + + def migrator_class(count) + calls, migrations = sensors(count) + + migrator = Class.new(ActiveRecord::MigrationContext) { + define_method(:migrations) { |*| + migrations + } + } + [calls, migrator] + end +end diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index bb1c1ea17d..b49e62bee6 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -851,7 +851,6 @@ module NestedAttributesOnACollectionAssociationTests end private - def association_setter @association_setter ||= "#{@association_name}_attributes=".to_sym end diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index 080aeb0989..d783b2945d 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -72,7 +72,6 @@ class PooledConnectionsTest < ActiveRecord::TestCase end private - def add_record(name) ActiveRecord::Base.connection_pool.with_connection { Project.create! name: name } end diff --git a/activerecord/test/cases/query_cache_test.rb b/activerecord/test/cases/query_cache_test.rb index eb32b690aa..79bd6906d1 100644 --- a/activerecord/test/cases/query_cache_test.rb +++ b/activerecord/test/cases/query_cache_test.rb @@ -335,11 +335,7 @@ class QueryCacheTest < ActiveRecord::TestCase def test_cache_does_not_wrap_results_in_arrays Task.cache do - if current_adapter?(:SQLite3Adapter, :Mysql2Adapter, :PostgreSQLAdapter, :OracleAdapter) - assert_equal 2, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks") - else - assert_instance_of String, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks") - end + assert_equal 2, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks") end end @@ -540,8 +536,24 @@ class QueryCacheTest < ActiveRecord::TestCase ActiveRecord::Base.connection_handlers = { writing: ActiveRecord::Base.default_connection_handler } end - private + test "query cache is enabled in threads with shared connection" do + ActiveRecord::Base.connection_pool.lock_thread = true + + assert_cache :off + thread_a = Thread.new do + middleware { |env| + assert_cache :clean + [200, {}, nil] + }.call({}) + end + + thread_a.join + + ActiveRecord::Base.connection_pool.lock_thread = false + end + + private def with_temporary_connection_pool old_pool = ActiveRecord::Base.connection_handler.retrieve_connection_pool(ActiveRecord::Base.connection_specification_name) new_pool = ActiveRecord::ConnectionAdapters::ConnectionPool.new ActiveRecord::Base.connection_pool.spec diff --git a/activerecord/test/cases/relation/where_clause_test.rb b/activerecord/test/cases/relation/where_clause_test.rb index b26a1a1d80..35db3d1175 100644 --- a/activerecord/test/cases/relation/where_clause_test.rb +++ b/activerecord/test/cases/relation/where_clause_test.rb @@ -233,7 +233,6 @@ class ActiveRecord::Relation end private - def table Arel::Table.new("table") end diff --git a/activerecord/test/cases/relation_test.rb b/activerecord/test/cases/relation_test.rb index 3f370e5ede..e74fb1a098 100644 --- a/activerecord/test/cases/relation_test.rb +++ b/activerecord/test/cases/relation_test.rb @@ -363,6 +363,13 @@ module ActiveRecord assert_match %r{/\*\+ BADHINT \*/}, post_with_hint.to_sql end + def test_does_not_duplicate_optimizer_hints_on_merge + escaped_table = Post.connection.quote_table_name("posts") + expected = "SELECT /*+ OMGHINT */ #{escaped_table}.* FROM #{escaped_table}" + query = Post.optimizer_hints("OMGHINT").merge(Post.optimizer_hints("OMGHINT")).to_sql + assert_equal expected, query + end + class EnsureRoundTripTypeCasting < ActiveRecord::Type::Value def type :string @@ -405,7 +412,6 @@ module ActiveRecord end private - def skip_if_sqlite3_version_includes_quoting_bug if sqlite3_version_includes_quoting_bug? skip <<-ERROR.squish diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 4ec695c4c6..1a20fe5dc2 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -298,7 +298,7 @@ class RelationTest < ActiveRecord::TestCase end def test_reverse_order_with_function - topics = Topic.order(Arel.sql("length(title)")).reverse_order + topics = Topic.order("length(title)").reverse_order assert_equal topics(:second).title, topics.first.title end @@ -308,9 +308,9 @@ class RelationTest < ActiveRecord::TestCase end def test_reverse_order_with_function_other_predicates - topics = Topic.order(Arel.sql("author_name, length(title), id")).reverse_order + topics = Topic.order("author_name, length(title), id").reverse_order assert_equal topics(:second).title, topics.first.title - topics = Topic.order(Arel.sql("length(author_name), id, length(title)")).reverse_order + topics = Topic.order("length(author_name), id, length(title)").reverse_order assert_equal topics(:fifth).title, topics.first.title end @@ -337,21 +337,21 @@ class RelationTest < ActiveRecord::TestCase def test_reverse_order_with_nulls_first_or_last assert_raises(ActiveRecord::IrreversibleOrderError) do - Topic.order(Arel.sql("title NULLS FIRST")).reverse_order + Topic.order("title NULLS FIRST").reverse_order end assert_raises(ActiveRecord::IrreversibleOrderError) do - Topic.order(Arel.sql("title NULLS FIRST")).reverse_order + Topic.order("title NULLS FIRST").reverse_order end assert_raises(ActiveRecord::IrreversibleOrderError) do - Topic.order(Arel.sql("title nulls last")).reverse_order + Topic.order("title nulls last").reverse_order end assert_raises(ActiveRecord::IrreversibleOrderError) do - Topic.order(Arel.sql("title NULLS FIRST, author_name")).reverse_order + Topic.order("title NULLS FIRST, author_name").reverse_order end assert_raises(ActiveRecord::IrreversibleOrderError) do - Topic.order(Arel.sql("author_name, title nulls last")).reverse_order + Topic.order("author_name, title nulls last").reverse_order end - end + end if current_adapter?(:PostgreSQLAdapter, :OracleAdapter) def test_default_reverse_order_on_table_without_primary_key assert_raises(ActiveRecord::IrreversibleOrderError) do @@ -1679,7 +1679,7 @@ class RelationTest < ActiveRecord::TestCase scope = Post.order("comments.body") assert_equal ["comments"], scope.references_values - scope = Post.order(Arel.sql("#{Comment.quoted_table_name}.#{Comment.quoted_primary_key}")) + scope = Post.order("#{Comment.quoted_table_name}.#{Comment.quoted_primary_key}") if current_adapter?(:OracleAdapter) assert_equal ["COMMENTS"], scope.references_values else @@ -1696,7 +1696,7 @@ class RelationTest < ActiveRecord::TestCase scope = Post.order("comments.body asc") assert_equal ["comments"], scope.references_values - scope = Post.order(Arel.sql("foo(comments.body)")) + scope = Post.order("foo(comments.body)") assert_equal [], scope.references_values end @@ -1704,7 +1704,7 @@ class RelationTest < ActiveRecord::TestCase scope = Post.reorder("comments.body") assert_equal %w(comments), scope.references_values - scope = Post.reorder(Arel.sql("#{Comment.quoted_table_name}.#{Comment.quoted_primary_key}")) + scope = Post.reorder("#{Comment.quoted_table_name}.#{Comment.quoted_primary_key}") if current_adapter?(:OracleAdapter) assert_equal ["COMMENTS"], scope.references_values else @@ -1721,7 +1721,7 @@ class RelationTest < ActiveRecord::TestCase scope = Post.reorder("comments.body asc") assert_equal %w(comments), scope.references_values - scope = Post.reorder(Arel.sql("foo(comments.body)")) + scope = Post.reorder("foo(comments.body)") assert_equal [], scope.references_values end @@ -1955,8 +1955,8 @@ class RelationTest < ActiveRecord::TestCase test "joins with order by custom attribute" do companies = Company.create!([{ name: "test1" }, { name: "test2" }]) companies.each { |company| company.contracts.create! } - assert_equal companies, Company.joins(:contracts).order(:metadata) - assert_equal companies.reverse, Company.joins(:contracts).order(metadata: :desc) + assert_equal companies, Company.joins(:contracts).order(:metadata, :count) + assert_equal companies.reverse, Company.joins(:contracts).order(metadata: :desc, count: :desc) end test "delegations do not leak to other classes" do diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index 49e9be9565..bb7184c5fc 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -33,6 +33,7 @@ class SchemaDumperTest < ActiveRecord::TestCase schema_info = ActiveRecord::Base.connection.dump_schema_information assert_match(/20100201010101.*20100301010101/m, schema_info) + assert_includes schema_info, "20100101010101" ensure ActiveRecord::SchemaMigration.delete_all end diff --git a/activerecord/test/cases/schema_loading_test.rb b/activerecord/test/cases/schema_loading_test.rb index f539156466..5da2d9e08f 100644 --- a/activerecord/test/cases/schema_loading_test.rb +++ b/activerecord/test/cases/schema_loading_test.rb @@ -43,7 +43,6 @@ class SchemaLoadingTest < ActiveRecord::TestCase end private - def define_model Class.new(ActiveRecord::Base) do include SchemaLoadCounter diff --git a/activerecord/test/cases/tasks/database_tasks_test.rb b/activerecord/test/cases/tasks/database_tasks_test.rb index ffe94eee0f..6b6861465b 100644 --- a/activerecord/test/cases/tasks/database_tasks_test.rb +++ b/activerecord/test/cases/tasks/database_tasks_test.rb @@ -835,7 +835,6 @@ module ActiveRecord end private - def capture_migration_status capture(:stdout) do ActiveRecord::Tasks::DatabaseTasks.migrate_status diff --git a/activerecord/test/cases/tasks/mysql_rake_test.rb b/activerecord/test/cases/tasks/mysql_rake_test.rb index 552e623fd4..258132835f 100644 --- a/activerecord/test/cases/tasks/mysql_rake_test.rb +++ b/activerecord/test/cases/tasks/mysql_rake_test.rb @@ -100,7 +100,6 @@ if current_adapter?(:Mysql2Adapter) end private - def with_stubbed_connection_establish_connection ActiveRecord::Base.stub(:establish_connection, nil) do ActiveRecord::Base.stub(:connection, @connection) do @@ -180,7 +179,6 @@ if current_adapter?(:Mysql2Adapter) end private - def with_stubbed_connection_establish_connection ActiveRecord::Base.stub(:establish_connection, nil) do ActiveRecord::Base.stub(:connection, @connection) do @@ -233,7 +231,6 @@ if current_adapter?(:Mysql2Adapter) end private - def with_stubbed_connection_establish_connection ActiveRecord::Base.stub(:establish_connection, nil) do ActiveRecord::Base.stub(:connection, @connection) do diff --git a/activerecord/test/cases/tasks/postgresql_rake_test.rb b/activerecord/test/cases/tasks/postgresql_rake_test.rb index 065ba7734c..f9df650687 100644 --- a/activerecord/test/cases/tasks/postgresql_rake_test.rb +++ b/activerecord/test/cases/tasks/postgresql_rake_test.rb @@ -139,7 +139,6 @@ if current_adapter?(:PostgreSQLAdapter) end private - def with_stubbed_connection_establish_connection ActiveRecord::Base.stub(:connection, @connection) do ActiveRecord::Base.stub(:establish_connection, nil) do @@ -201,7 +200,6 @@ if current_adapter?(:PostgreSQLAdapter) end private - def with_stubbed_connection_establish_connection ActiveRecord::Base.stub(:connection, @connection) do ActiveRecord::Base.stub(:establish_connection, nil) do @@ -301,7 +299,6 @@ if current_adapter?(:PostgreSQLAdapter) end private - def with_stubbed_connection ActiveRecord::Base.stub(:connection, @connection) do yield diff --git a/activerecord/test/cases/transaction_callbacks_test.rb b/activerecord/test/cases/transaction_callbacks_test.rb index 100bd6a925..19b89ab08c 100644 --- a/activerecord/test/cases/transaction_callbacks_test.rb +++ b/activerecord/test/cases/transaction_callbacks_test.rb @@ -460,7 +460,6 @@ class TransactionCallbacksTest < ActiveRecord::TestCase end private - def add_transaction_execution_blocks(record) record.after_commit_block(:create) { |r| r.history << :commit_on_create } record.after_commit_block(:update) { |r| r.history << :commit_on_update } diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index 6795996cca..b5c1cac3d9 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -1077,7 +1077,6 @@ class TransactionTest < ActiveRecord::TestCase end private - %w(validation save destroy).each do |filter| define_method("add_cancelling_before_#{filter}_with_db_side_effect_to_topic") do |topic| meta = class << topic; self; end diff --git a/activerecord/test/cases/unsafe_raw_sql_test.rb b/activerecord/test/cases/unsafe_raw_sql_test.rb index d5d8f2a09a..87edb163f2 100644 --- a/activerecord/test/cases/unsafe_raw_sql_test.rb +++ b/activerecord/test/cases/unsafe_raw_sql_test.rb @@ -77,7 +77,7 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase assert_equal ids_expected, ids_disabled end - test "order: allows table and column name" do + test "order: allows table and column names" do ids_expected = Post.order(Arel.sql("title")).pluck(:id) ids_depr = with_unsafe_raw_sql_deprecated { Post.order("posts.title").pluck(:id) } @@ -87,6 +87,17 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase assert_equal ids_expected, ids_disabled end + test "order: allows quoted table and column names" do + ids_expected = Post.order(Arel.sql("title")).pluck(:id) + + quoted_title = Post.connection.quote_table_name("posts.title") + ids_depr = with_unsafe_raw_sql_deprecated { Post.order(quoted_title).pluck(:id) } + ids_disabled = with_unsafe_raw_sql_disabled { Post.order(quoted_title).pluck(:id) } + + assert_equal ids_expected, ids_depr + assert_equal ids_expected, ids_disabled + end + test "order: allows column name and direction in string" do ids_expected = Post.order(Arel.sql("title desc")).pluck(:id) @@ -116,10 +127,10 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase ["asc", "desc", ""].each do |direction| %w(first last).each do |position| - ids_expected = Post.order(Arel.sql("type #{direction} nulls #{position}")).pluck(:id) + ids_expected = Post.order(Arel.sql("type::text #{direction} nulls #{position}")).pluck(:id) - ids_depr = with_unsafe_raw_sql_deprecated { Post.order("type #{direction} nulls #{position}").pluck(:id) } - ids_disabled = with_unsafe_raw_sql_disabled { Post.order("type #{direction} nulls #{position}").pluck(:id) } + ids_depr = with_unsafe_raw_sql_deprecated { Post.order("type::text #{direction} nulls #{position}").pluck(:id) } + ids_disabled = with_unsafe_raw_sql_disabled { Post.order("type::text #{direction} nulls #{position}").pluck(:id) } assert_equal ids_expected, ids_depr assert_equal ids_expected, ids_disabled @@ -130,7 +141,7 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase test "order: disallows invalid column name" do with_unsafe_raw_sql_disabled do assert_raises(ActiveRecord::UnknownAttributeReference) do - Post.order("len(title) asc").pluck(:id) + Post.order("REPLACE(title, 'misc', 'zzzz') asc").pluck(:id) end end end @@ -146,7 +157,7 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase test "order: disallows invalid column with direction" do with_unsafe_raw_sql_disabled do assert_raises(ActiveRecord::UnknownAttributeReference) do - Post.order("len(title)" => :asc).pluck(:id) + Post.order("REPLACE(title, 'misc', 'zzzz')" => :asc).pluck(:id) end end end @@ -179,7 +190,7 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase test "order: disallows invalid Array arguments" do with_unsafe_raw_sql_disabled do assert_raises(ActiveRecord::UnknownAttributeReference) do - Post.order(["author_id", "length(title)"]).pluck(:id) + Post.order(["author_id", "REPLACE(title, 'misc', 'zzzz')"]).pluck(:id) end end end @@ -187,8 +198,8 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase test "order: allows valid Array arguments" do ids_expected = Post.order(Arel.sql("author_id, length(title)")).pluck(:id) - ids_depr = with_unsafe_raw_sql_deprecated { Post.order(["author_id", Arel.sql("length(title)")]).pluck(:id) } - ids_disabled = with_unsafe_raw_sql_disabled { Post.order(["author_id", Arel.sql("length(title)")]).pluck(:id) } + ids_depr = with_unsafe_raw_sql_deprecated { Post.order(["author_id", "length(title)"]).pluck(:id) } + ids_disabled = with_unsafe_raw_sql_disabled { Post.order(["author_id", "length(title)"]).pluck(:id) } assert_equal ids_expected, ids_depr assert_equal ids_expected, ids_disabled @@ -197,7 +208,7 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase test "order: logs deprecation warning for unrecognized column" do with_unsafe_raw_sql_deprecated do assert_deprecated(/Dangerous query method/) do - Post.order("length(title)") + Post.order("REPLACE(title, 'misc', 'zzzz')") end end end @@ -212,6 +223,16 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase assert_equal titles_expected, titles_disabled end + test "pluck: allows string column name with function and alias" do + titles_expected = Post.pluck(Arel.sql("UPPER(title)")) + + titles_depr = with_unsafe_raw_sql_deprecated { Post.pluck("UPPER(title) AS title") } + titles_disabled = with_unsafe_raw_sql_disabled { Post.pluck("UPPER(title) AS title") } + + assert_equal titles_expected, titles_depr + assert_equal titles_expected, titles_disabled + end + test "pluck: allows symbol column name" do titles_expected = Post.pluck(Arel.sql("title")) @@ -262,10 +283,21 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase assert_equal titles_expected, titles_disabled end + test "pluck: allows quoted table and column names" do + titles_expected = Post.pluck(Arel.sql("title")) + + quoted_title = Post.connection.quote_table_name("posts.title") + titles_depr = with_unsafe_raw_sql_deprecated { Post.pluck(quoted_title) } + titles_disabled = with_unsafe_raw_sql_disabled { Post.pluck(quoted_title) } + + assert_equal titles_expected, titles_depr + assert_equal titles_expected, titles_disabled + end + test "pluck: disallows invalid column name" do with_unsafe_raw_sql_disabled do assert_raises(ActiveRecord::UnknownAttributeReference) do - Post.pluck("length(title)") + Post.pluck("REPLACE(title, 'misc', 'zzzz')") end end end @@ -273,7 +305,7 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase test "pluck: disallows invalid column name amongst valid names" do with_unsafe_raw_sql_disabled do assert_raises(ActiveRecord::UnknownAttributeReference) do - Post.pluck(:title, "length(title)") + Post.pluck(:title, "REPLACE(title, 'misc', 'zzzz')") end end end @@ -281,7 +313,7 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase test "pluck: disallows invalid column names with includes" do with_unsafe_raw_sql_disabled do assert_raises(ActiveRecord::UnknownAttributeReference) do - Post.includes(:comments).pluck(:title, "length(title)") + Post.includes(:comments).pluck(:title, "REPLACE(title, 'misc', 'zzzz')") end end end @@ -296,24 +328,25 @@ class UnsafeRawSqlTest < ActiveRecord::TestCase test "pluck: logs deprecation warning" do with_unsafe_raw_sql_deprecated do assert_deprecated(/Dangerous query method/) do - Post.includes(:comments).pluck(:title, "length(title)") + Post.includes(:comments).pluck(:title, "REPLACE(title, 'misc', 'zzzz')") end end end - def with_unsafe_raw_sql_disabled(&blk) - with_config(:disabled, &blk) - end + private + def with_unsafe_raw_sql_disabled(&block) + with_config(:disabled, &block) + end - def with_unsafe_raw_sql_deprecated(&blk) - with_config(:deprecated, &blk) - end + def with_unsafe_raw_sql_deprecated(&block) + with_config(:deprecated, &block) + end - def with_config(new_value, &blk) - old_value = ActiveRecord::Base.allow_unsafe_raw_sql - ActiveRecord::Base.allow_unsafe_raw_sql = new_value - blk.call - ensure - ActiveRecord::Base.allow_unsafe_raw_sql = old_value - end + def with_config(new_value, &block) + old_value = ActiveRecord::Base.allow_unsafe_raw_sql + ActiveRecord::Base.allow_unsafe_raw_sql = new_value + yield + ensure + ActiveRecord::Base.allow_unsafe_raw_sql = old_value + end end diff --git a/activerecord/test/cases/validations/i18n_validation_test.rb b/activerecord/test/cases/validations/i18n_validation_test.rb index 2645776ab7..4dd8a4a82b 100644 --- a/activerecord/test/cases/validations/i18n_validation_test.rb +++ b/activerecord/test/cases/validations/i18n_validation_test.rb @@ -51,7 +51,7 @@ class I18nValidationTest < ActiveRecord::TestCase test "validates_uniqueness_of on generated message #{name}" do Topic.validates_uniqueness_of :title, validation_options @topic.title = unique_topic.title - assert_called_with(@topic.errors, :generate_message, [:title, :taken, generate_message_options.merge(value: "unique!")]) do + assert_called_with(ActiveModel::Error, :generate_message, [:title, :taken, @topic, generate_message_options.merge(value: "unique!")]) do @topic.valid? @topic.errors.messages end @@ -61,7 +61,7 @@ class I18nValidationTest < ActiveRecord::TestCase COMMON_CASES.each do |name, validation_options, generate_message_options| test "validates_associated on generated message #{name}" do Topic.validates_associated :replies, validation_options - assert_called_with(replied_topic.errors, :generate_message, [:replies, :invalid, generate_message_options.merge(value: replied_topic.replies)]) do + assert_called_with(ActiveModel::Error, :generate_message, [:replies, :invalid, replied_topic, generate_message_options.merge(value: replied_topic.replies)]) do replied_topic.save replied_topic.errors.messages end diff --git a/activerecord/test/cases/yaml_serialization_test.rb b/activerecord/test/cases/yaml_serialization_test.rb index 60ebdce178..7003afa33a 100644 --- a/activerecord/test/cases/yaml_serialization_test.rb +++ b/activerecord/test/cases/yaml_serialization_test.rb @@ -130,7 +130,6 @@ class YamlSerializationTest < ActiveRecord::TestCase end private - def yaml_fixture(file_name) path = File.expand_path( "../support/yaml_compatibility_fixtures/#{file_name}.yml", diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb index b52b643ad7..da7e4139b1 100644 --- a/activerecord/test/models/author.rb +++ b/activerecord/test/models/author.rb @@ -116,6 +116,7 @@ class Author < ActiveRecord::Base has_many :tags_with_primary_key, through: :posts has_many :books + has_many :published_books, class_name: "PublishedBook" has_many :unpublished_books, -> { where(status: [:proposed, :written]) }, class_name: "Book" has_many :subscriptions, through: :books has_many :subscribers, -> { order("subscribers.nick") }, through: :subscriptions diff --git a/activerecord/test/models/book.rb b/activerecord/test/models/book.rb index afdda1a81e..43b82e6047 100644 --- a/activerecord/test/models/book.rb +++ b/activerecord/test/models/book.rb @@ -24,3 +24,9 @@ class Book < ActiveRecord::Base "do publish work..." end end + +class PublishedBook < ActiveRecord::Base + self.table_name = "books" + + validates_uniqueness_of :isbn +end diff --git a/activerecord/test/models/club.rb b/activerecord/test/models/club.rb index bb49fb300c..890e427616 100644 --- a/activerecord/test/models/club.rb +++ b/activerecord/test/models/club.rb @@ -15,7 +15,6 @@ class Club < ActiveRecord::Base accepts_nested_attributes_for :membership private - def private_method "I'm sorry sir, this is a *private* club, not a *pirate* club" end diff --git a/activerecord/test/models/company.rb b/activerecord/test/models/company.rb index a0f48d23f1..339b5c8ca8 100644 --- a/activerecord/test/models/company.rb +++ b/activerecord/test/models/company.rb @@ -25,7 +25,6 @@ class Company < AbstractCompany end private - def private_method "I am Jack's innermost fears and aspirations" end diff --git a/activerecord/test/models/company_in_module.rb b/activerecord/test/models/company_in_module.rb index 52b7e06a63..320b26b950 100644 --- a/activerecord/test/models/company_in_module.rb +++ b/activerecord/test/models/company_in_module.rb @@ -91,7 +91,6 @@ module MyApplication validate :check_empty_credit_limit private - def check_empty_credit_limit errors.add("credit_card", :blank) if credit_card.blank? end diff --git a/activerecord/test/models/contact.rb b/activerecord/test/models/contact.rb index 6e02ff199b..d5f6f00691 100644 --- a/activerecord/test/models/contact.rb +++ b/activerecord/test/models/contact.rb @@ -10,14 +10,14 @@ module ContactFakeColumns table_name => "id" } - column :id, :integer - column :name, :string - column :age, :integer - column :avatar, :binary - column :created_at, :datetime - column :awesome, :boolean - column :preferences, :string - column :alternative_id, :integer + column :id, "integer" + column :name, "string" + column :age, "integer" + column :avatar, "binary" + column :created_at, "datetime" + column :awesome, "boolean" + column :preferences, "string" + column :alternative_id, "integer" serialize :preferences @@ -37,7 +37,7 @@ end class ContactSti < ActiveRecord::Base extend ContactFakeColumns - column :type, :string + column :type, "string" def type; "ContactSti" end end diff --git a/activerecord/test/models/mouse.rb b/activerecord/test/models/mouse.rb new file mode 100644 index 0000000000..75a55c125d --- /dev/null +++ b/activerecord/test/models/mouse.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +class Mouse < ActiveRecord::Base + has_many :squeaks, autosave: true + validates :name, presence: true +end diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb index c3d15a571a..0dfd29e45e 100644 --- a/activerecord/test/models/person.rb +++ b/activerecord/test/models/person.rb @@ -101,7 +101,6 @@ class RichPerson < ActiveRecord::Base before_validation :run_before_validation private - def run_before_create self.first_name = first_name.to_s + "run_before_create" end diff --git a/activerecord/test/models/ship.rb b/activerecord/test/models/ship.rb index 7973219a79..6bab7a1eb9 100644 --- a/activerecord/test/models/ship.rb +++ b/activerecord/test/models/ship.rb @@ -27,7 +27,8 @@ class ShipWithoutNestedAttributes < ActiveRecord::Base has_many :prisoners, inverse_of: :ship, foreign_key: :ship_id has_many :parts, class_name: "ShipPart", foreign_key: :ship_id - validates :name, presence: true + validates :name, presence: true, if: -> { true } + validates :name, presence: true, if: -> { true } end class Prisoner < ActiveRecord::Base diff --git a/activerecord/test/models/squeak.rb b/activerecord/test/models/squeak.rb new file mode 100644 index 0000000000..e0a643c238 --- /dev/null +++ b/activerecord/test/models/squeak.rb @@ -0,0 +1,6 @@ +# frozen_string_literal: true + +class Squeak < ActiveRecord::Base + belongs_to :mouse + accepts_nested_attributes_for :mouse +end diff --git a/activerecord/test/models/topic.rb b/activerecord/test/models/topic.rb index 77101090f2..7a864c728c 100644 --- a/activerecord/test/models/topic.rb +++ b/activerecord/test/models/topic.rb @@ -93,7 +93,6 @@ class Topic < ActiveRecord::Base end private - def default_written_on self.written_on = Time.now unless attribute_present?("written_on") end diff --git a/activerecord/test/schema/mysql2_specific_schema.rb b/activerecord/test/schema/mysql2_specific_schema.rb index b143035213..911ac808c6 100644 --- a/activerecord/test/schema/mysql2_specific_schema.rb +++ b/activerecord/test/schema/mysql2_specific_schema.rb @@ -62,10 +62,6 @@ ActiveRecord::Schema.define do t.binary :binary_column, limit: 1 end - create_table :enum_tests, id: false, force: true do |t| - t.column :enum_column, "ENUM('text','blob','tiny','medium','long','unsigned','bigint')" - end - execute "DROP PROCEDURE IF EXISTS ten" execute <<~SQL diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 41920b3719..dd0ff759b6 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -115,7 +115,7 @@ ActiveRecord::Schema.define do t.column :font_size, :integer, **default_zero t.column :difficulty, :integer, **default_zero t.column :cover, :string, default: "hard" - t.string :isbn + t.string :isbn, **case_sensitive_options t.datetime :published_on t.index [:author_id, :name], unique: true t.index :isbn, where: "published_on IS NOT NULL", unique: true @@ -261,6 +261,7 @@ ActiveRecord::Schema.define do t.references :developer, index: false t.references :company, index: false t.string :metadata + t.integer :count end create_table :customers, force: true do |t| @@ -562,6 +563,10 @@ ActiveRecord::Schema.define do t.string :type end + create_table :mice, force: true do |t| + t.string :name + end + create_table :movies, force: true, id: false do |t| t.primary_key :movieid t.string :name @@ -842,6 +847,10 @@ ActiveRecord::Schema.define do end end + create_table :squeaks, force: true do |t| + t.integer :mouse_id + end + create_table :prisoners, force: true do |t| t.belongs_to :ship end diff --git a/activerecord/test/support/config.rb b/activerecord/test/support/config.rb index de0d90a18f..66ae57b382 100644 --- a/activerecord/test/support/config.rb +++ b/activerecord/test/support/config.rb @@ -12,7 +12,6 @@ module ARTest end private - def config_file Pathname.new(ENV["ARCONFIG"] || TEST_ROOT + "/config.yml") end diff --git a/activestorage/CHANGELOG.md b/activestorage/CHANGELOG.md index fdb0f143f4..1475a7a786 100644 --- a/activestorage/CHANGELOG.md +++ b/activestorage/CHANGELOG.md @@ -1,3 +1,7 @@ +* Add `config.active_storage.draw_routes` to disable Active Storage routes. + + *Gannon McGibbon* + * Image analysis is skipped if ImageMagick returns an error. `ActiveStorage::Analyzer::ImageAnalyzer#metadata` would previously raise a diff --git a/activestorage/config/routes.rb b/activestorage/config/routes.rb index 3af7361cff..bde53e72f3 100644 --- a/activestorage/config/routes.rb +++ b/activestorage/config/routes.rb @@ -29,4 +29,4 @@ Rails.application.routes.draw do resolve("ActiveStorage::Blob") { |blob, options| route_for(:rails_blob, blob, options) } resolve("ActiveStorage::Attachment") { |attachment, options| route_for(:rails_blob, attachment.blob, options) } -end +end if ActiveStorage.draw_routes diff --git a/activestorage/lib/active_storage.rb b/activestorage/lib/active_storage.rb index 5c5da551ae..c35a9920d6 100644 --- a/activestorage/lib/active_storage.rb +++ b/activestorage/lib/active_storage.rb @@ -43,17 +43,26 @@ module ActiveStorage mattr_accessor :logger mattr_accessor :verifier + mattr_accessor :variant_processor, default: :mini_magick + mattr_accessor :queues, default: {} + mattr_accessor :previewers, default: [] - mattr_accessor :analyzers, default: [] - mattr_accessor :variant_processor, default: :mini_magick + mattr_accessor :analyzers, default: [] + mattr_accessor :paths, default: {} - mattr_accessor :variable_content_types, default: [] + + mattr_accessor :variable_content_types, default: [] + mattr_accessor :binary_content_type, default: "application/octet-stream" mattr_accessor :content_types_to_serve_as_binary, default: [] - mattr_accessor :content_types_allowed_inline, default: [] - mattr_accessor :binary_content_type, default: "application/octet-stream" + mattr_accessor :content_types_allowed_inline, default: [] + mattr_accessor :service_urls_expire_in, default: 5.minutes + mattr_accessor :routes_prefix, default: "/rails/active_storage" + mattr_accessor :draw_routes, default: true + + mattr_accessor :replace_on_assign_to_many, default: false module Transformers extend ActiveSupport::Autoload diff --git a/activestorage/lib/active_storage/attached/model.rb b/activestorage/lib/active_storage/attached/model.rb index ae7f0685f2..06864a846f 100644 --- a/activestorage/lib/active_storage/attached/model.rb +++ b/activestorage/lib/active_storage/attached/model.rb @@ -93,12 +93,19 @@ module ActiveStorage end def #{name}=(attachables) - attachment_changes["#{name}"] = - if attachables.nil? || Array(attachables).none? - ActiveStorage::Attached::Changes::DeleteMany.new("#{name}", self) - else - ActiveStorage::Attached::Changes::CreateMany.new("#{name}", self, attachables) + if ActiveStorage.replace_on_assign_to_many + attachment_changes["#{name}"] = + if attachables.nil? || Array(attachables).none? + ActiveStorage::Attached::Changes::DeleteMany.new("#{name}", self) + else + ActiveStorage::Attached::Changes::CreateMany.new("#{name}", self, attachables) + end + else + if !attachables.nil? || Array(attachables).any? + attachment_changes["#{name}"] = + ActiveStorage::Attached::Changes::CreateMany.new("#{name}", self, #{name}.blobs + attachables) end + end end CODE diff --git a/activestorage/lib/active_storage/engine.rb b/activestorage/lib/active_storage/engine.rb index f70d0a512a..9d9cd02d12 100644 --- a/activestorage/lib/active_storage/engine.rb +++ b/activestorage/lib/active_storage/engine.rb @@ -73,12 +73,15 @@ module ActiveStorage ActiveStorage.analyzers = app.config.active_storage.analyzers || [] ActiveStorage.paths = app.config.active_storage.paths || {} ActiveStorage.routes_prefix = app.config.active_storage.routes_prefix || "/rails/active_storage" + ActiveStorage.draw_routes = app.config.active_storage.draw_routes != false ActiveStorage.variable_content_types = app.config.active_storage.variable_content_types || [] ActiveStorage.content_types_to_serve_as_binary = app.config.active_storage.content_types_to_serve_as_binary || [] ActiveStorage.service_urls_expire_in = app.config.active_storage.service_urls_expire_in || 5.minutes ActiveStorage.content_types_allowed_inline = app.config.active_storage.content_types_allowed_inline || [] ActiveStorage.binary_content_type = app.config.active_storage.binary_content_type || "application/octet-stream" + + ActiveStorage.replace_on_assign_to_many = app.config.active_storage.replace_on_assign_to_many || false end end diff --git a/activestorage/lib/active_storage/service/azure_storage_service.rb b/activestorage/lib/active_storage/service/azure_storage_service.rb index 993cc0e5f7..8d77e9b20f 100644 --- a/activestorage/lib/active_storage/service/azure_storage_service.rb +++ b/activestorage/lib/active_storage/service/azure_storage_service.rb @@ -17,10 +17,10 @@ module ActiveStorage @container = container end - def upload(key, io, checksum: nil, **) + def upload(key, io, checksum: nil, content_type: nil, **) instrument :upload, key: key, checksum: checksum do handle_errors do - blobs.create_block_blob(container, key, IO.try_convert(io) || io, content_md5: checksum) + blobs.create_block_blob(container, key, IO.try_convert(io) || io, content_md5: checksum, content_type: content_type) end end end diff --git a/activestorage/lib/active_storage/service/disk_service.rb b/activestorage/lib/active_storage/service/disk_service.rb index 67892d43b2..764a447c69 100644 --- a/activestorage/lib/active_storage/service/disk_service.rb +++ b/activestorage/lib/active_storage/service/disk_service.rb @@ -84,8 +84,12 @@ module ActiveStorage purpose: :blob_key } ) + current_uri = URI.parse(current_host) + generated_url = url_helpers.rails_disk_service_url(verified_key_with_expiration, - host: current_host, + protocol: current_uri.scheme, + host: current_uri.host, + port: current_uri.port, disposition: content_disposition, content_type: content_type, filename: filename diff --git a/activestorage/test/analyzer/video_analyzer_test.rb b/activestorage/test/analyzer/video_analyzer_test.rb index d30f49315a..172a2f0aae 100644 --- a/activestorage/test/analyzer/video_analyzer_test.rb +++ b/activestorage/test/analyzer/video_analyzer_test.rb @@ -24,7 +24,6 @@ class ActiveStorage::Analyzer::VideoAnalyzerTest < ActiveSupport::TestCase assert_equal 480, metadata[:width] assert_equal 640, metadata[:height] assert_equal [4, 3], metadata[:display_aspect_ratio] - assert_equal 5.227975, metadata[:duration] assert_equal 90, metadata[:angle] end diff --git a/activestorage/test/models/attached/many_test.rb b/activestorage/test/models/attached/many_test.rb index 878e284049..39ddecb041 100644 --- a/activestorage/test/models/attached/many_test.rb +++ b/activestorage/test/models/attached/many_test.rb @@ -269,6 +269,24 @@ class ActiveStorage::ManyAttachedTest < ActiveSupport::TestCase end end + test "updating an existing record with attachments when appending on assign" do + append_on_assign do + @user.highlights.attach create_blob(filename: "funky.jpg"), create_blob(filename: "town.jpg") + + assert_difference -> { @user.reload.highlights.count }, +2 do + @user.update! highlights: [ create_blob(filename: "whenever.jpg"), create_blob(filename: "wherever.jpg") ] + end + + assert_no_difference -> { @user.reload.highlights.count } do + @user.update! highlights: [ ] + end + + assert_no_difference -> { @user.reload.highlights.count } do + @user.update! highlights: nil + end + end + end + test "attaching existing blobs to a new record" do User.new(name: "Jason").tap do |user| user.highlights.attach create_blob(filename: "funky.jpg"), create_blob(filename: "town.jpg") @@ -538,4 +556,12 @@ class ActiveStorage::ManyAttachedTest < ActiveSupport::TestCase User.remove_method :highlights end end + + private + def append_on_assign + ActiveStorage.replace_on_assign_to_many, previous = false, ActiveStorage.replace_on_assign_to_many + yield + ensure + ActiveStorage.replace_on_assign_to_many = previous + end end diff --git a/activestorage/test/service/azure_storage_service_test.rb b/activestorage/test/service/azure_storage_service_test.rb index 2b07902d07..fc7b86ccb0 100644 --- a/activestorage/test/service/azure_storage_service_test.rb +++ b/activestorage/test/service/azure_storage_service_test.rb @@ -9,6 +9,20 @@ if SERVICE_CONFIGURATIONS[:azure] include ActiveStorage::Service::SharedServiceTests + test "upload with content_type" do + key = SecureRandom.base58(24) + data = "Foobar" + + @service.upload(key, StringIO.new(data), checksum: Digest::MD5.base64digest(data), filename: ActiveStorage::Filename.new("test.txt"), content_type: "text/plain") + + url = @service.url(key, expires_in: 2.minutes, disposition: :attachment, content_type: nil, filename: ActiveStorage::Filename.new("test.html")) + response = Net::HTTP.get_response(URI(url)) + assert_equal "text/plain", response.content_type + assert_match(/attachment;.*test\.html/, response["Content-Disposition"]) + ensure + @service.delete key + end + test "signed URL generation" do url = @service.url(@key, expires_in: 5.minutes, disposition: :inline, filename: ActiveStorage::Filename.new("avatar.png"), content_type: "image/png") diff --git a/activestorage/test/service/disk_service_test.rb b/activestorage/test/service/disk_service_test.rb index f3c4dd26bd..b766cc3f56 100644 --- a/activestorage/test/service/disk_service_test.rb +++ b/activestorage/test/service/disk_service_test.rb @@ -8,8 +8,14 @@ class ActiveStorage::Service::DiskServiceTest < ActiveSupport::TestCase include ActiveStorage::Service::SharedServiceTests test "URL generation" do - assert_match(/^https:\/\/example.com\/rails\/active_storage\/disk\/.*\/avatar\.png\?content_type=image%2Fpng&disposition=inline/, - @service.url(@key, expires_in: 5.minutes, disposition: :inline, filename: ActiveStorage::Filename.new("avatar.png"), content_type: "image/png")) + original_url_options = Rails.application.routes.default_url_options.dup + Rails.application.routes.default_url_options.merge!(protocol: "http", host: "test.example.com", port: 3001) + begin + assert_match(/^https:\/\/example.com\/rails\/active_storage\/disk\/.*\/avatar\.png\?content_type=image%2Fpng&disposition=inline/, + @service.url(@key, expires_in: 5.minutes, disposition: :inline, filename: ActiveStorage::Filename.new("avatar.png"), content_type: "image/png")) + ensure + Rails.application.routes.default_url_options = original_url_options + end end test "headers_for_direct_upload generation" do diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index 6256fb8c86..f20c7c92e6 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -3,6 +3,55 @@ *Dana Sherson* +* Make ActiveSupport::Logger Fiber-safe. Fixes #36752. + + Use `Fiber.current.__id__` in `ActiveSupport::Logger#local_level=` in order + to make log level local to Ruby Fibers in addition to Threads. + + Example: + + logger = ActiveSupport::Logger.new(STDOUT) + logger.level = 1 + p "Main is debug? #{logger.debug?}" + + Fiber.new { + logger.local_level = 0 + p "Thread is debug? #{logger.debug?}" + }.resume + + p "Main is debug? #{logger.debug?}" + + Before: + + Main is debug? false + Thread is debug? true + Main is debug? true + + After: + + Main is debug? false + Thread is debug? true + Main is debug? false + + *Alexander Varnin* + +* Allow the `on_rotation` proc used when decrypting/verifying a message to be + passed at the constructor level. + + Before: + + crypt = ActiveSupport::MessageEncryptor.new('long_secret') + crypt.decrypt_and_verify(encrypted_message, on_rotation: proc { ... }) + crypt.decrypt_and_verify(another_encrypted_message, on_rotation: proc { ... }) + + After: + + crypt = ActiveSupport::MessageEncryptor.new('long_secret', on_rotation: proc { ... }) + crypt.decrypt_and_verify(encrypted_message) + crypt.decrypt_and_verify(another_encrypted_message) + + *Edouard Chin* + * `delegate_missing_to` would raise a `DelegationError` if the object delegated to was `nil`. Now the `allow_nil` option has been added to enable the user to specify they want `nil` returned in this case. diff --git a/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec index 7ecbafc911..da295a0d35 100644 --- a/activesupport/activesupport.gemspec +++ b/activesupport/activesupport.gemspec @@ -34,5 +34,5 @@ Gem::Specification.new do |s| s.add_dependency "tzinfo", "~> 1.1" s.add_dependency "minitest", "~> 5.1" s.add_dependency "concurrent-ruby", "~> 1.0", ">= 1.0.2" - s.add_dependency "zeitwerk", "~> 2.1", ">= 2.1.4" + s.add_dependency "zeitwerk", "~> 2.1", ">= 2.1.8" end diff --git a/activesupport/lib/active_support/backtrace_cleaner.rb b/activesupport/lib/active_support/backtrace_cleaner.rb index 02cbfbaee6..f55e821e10 100644 --- a/activesupport/lib/active_support/backtrace_cleaner.rb +++ b/activesupport/lib/active_support/backtrace_cleaner.rb @@ -85,7 +85,6 @@ module ActiveSupport end private - FORMATTED_GEMS_PATTERN = /\A[^\/]+ \([\w.]+\) / def add_gem_filter diff --git a/activesupport/lib/active_support/cache.rb b/activesupport/lib/active_support/cache.rb index e055135bb4..a5063d0784 100644 --- a/activesupport/lib/active_support/cache.rb +++ b/activesupport/lib/active_support/cache.rb @@ -678,18 +678,15 @@ module ActiveSupport end def instrument(operation, key, options = nil) - log { "Cache #{operation}: #{normalize_key(key, options)}#{options.blank? ? "" : " (#{options.inspect})"}" } + if logger && logger.debug? && !silence? + logger.debug "Cache #{operation}: #{normalize_key(key, options)}#{options.blank? ? "" : " (#{options.inspect})"}" + end payload = { key: key } payload.merge!(options) if options.is_a?(Hash) ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload) { yield(payload) } end - def log - return unless logger && logger.debug? && !silence? - logger.debug(yield) - end - def handle_expired_entry(entry, key, options) if entry && entry.expired? race_ttl = options[:race_condition_ttl].to_i diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb index f43894a1ea..925440a23f 100644 --- a/activesupport/lib/active_support/cache/file_store.rb +++ b/activesupport/lib/active_support/cache/file_store.rb @@ -72,7 +72,6 @@ module ActiveSupport end private - def read_entry(key, options) if File.exist?(key) File.open(key) { |f| Marshal.load(f) } diff --git a/activesupport/lib/active_support/cache/memory_store.rb b/activesupport/lib/active_support/cache/memory_store.rb index 629eb2dd70..fa24da91b4 100644 --- a/activesupport/lib/active_support/cache/memory_store.rb +++ b/activesupport/lib/active_support/cache/memory_store.rb @@ -114,7 +114,6 @@ module ActiveSupport end private - PER_ENTRY_OVERHEAD = 240 def cached_size(key, entry) diff --git a/activesupport/lib/active_support/cache/strategy/local_cache.rb b/activesupport/lib/active_support/cache/strategy/local_cache.rb index 39b32fc7f6..8e80946fbb 100644 --- a/activesupport/lib/active_support/cache/strategy/local_cache.rb +++ b/activesupport/lib/active_support/cache/strategy/local_cache.rb @@ -1,6 +1,5 @@ # frozen_string_literal: true -require "active_support/core_ext/object/duplicable" require "active_support/core_ext/string/inflections" require "active_support/per_thread_registry" @@ -75,7 +74,10 @@ module ActiveSupport end def fetch_entry(key, options = nil) # :nodoc: - @data.fetch(key) { @data[key] = yield } + entry = @data.fetch(key) { @data[key] = yield } + dup_entry = entry.dup + dup_entry&.dup_value! + dup_entry end end diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index d0644a0f7e..daf98c9528 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -7,7 +7,6 @@ require "active_support/core_ext/class/attribute" require "active_support/core_ext/kernel/reporting" require "active_support/core_ext/kernel/singleton_class" require "active_support/core_ext/string/filters" -require "active_support/deprecation" require "thread" module ActiveSupport @@ -142,7 +141,6 @@ module ActiveSupport end private - # A hook invoked every time a before callback is halted. # This can be overridden in ActiveSupport::Callbacks implementors in order # to provide better debugging/logging. @@ -582,7 +580,6 @@ module ActiveSupport attr_reader :chain private - def append_one(callback) @callbacks = nil remove_duplicates(callback) @@ -843,7 +840,6 @@ module ActiveSupport end protected - def get_callbacks(name) # :nodoc: __callbacks[name.to_sym] end diff --git a/activesupport/lib/active_support/concurrency/share_lock.rb b/activesupport/lib/active_support/concurrency/share_lock.rb index f18ccf1c88..eae7d4469f 100644 --- a/activesupport/lib/active_support/concurrency/share_lock.rb +++ b/activesupport/lib/active_support/concurrency/share_lock.rb @@ -200,7 +200,6 @@ module ActiveSupport end private - # Must be called within synchronize def busy_for_exclusive?(purpose) busy_for_sharing?(purpose) || diff --git a/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb b/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb index e2e11545e2..c7a2378e41 100644 --- a/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb +++ b/activesupport/lib/active_support/core_ext/date_and_time/calculations.rb @@ -20,21 +20,11 @@ module DateAndTime advance(days: -1) end - # Returns a new date/time the specified number of days ago. - def prev_day(days = 1) - advance(days: -days) - end - # Returns a new date/time representing tomorrow. def tomorrow advance(days: 1) end - # Returns a new date/time the specified number of days in the future. - def next_day(days = 1) - advance(days: days) - end - # Returns true if the date/time is today. def today? to_date == ::Date.current @@ -198,21 +188,11 @@ module DateAndTime end end - # Returns a new date/time the specified number of months in the future. - def next_month(months = 1) - advance(months: months) - end - # Short-hand for months_since(3) def next_quarter months_since(3) end - # Returns a new date/time the specified number of years in the future. - def next_year(years = 1) - advance(years: years) - end - # Returns a new date/time representing the given day in the previous week. # Week is assumed to start on +start_day+, default is # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. @@ -233,11 +213,6 @@ module DateAndTime end alias_method :last_weekday, :prev_weekday - # Returns a new date/time the specified number of months ago. - def prev_month(months = 1) - advance(months: -months) - end - # Short-hand for months_ago(1). def last_month months_ago(1) @@ -249,11 +224,6 @@ module DateAndTime end alias_method :last_quarter, :prev_quarter - # Returns a new date/time the specified number of years ago. - def prev_year(years = 1) - advance(years: -years) - end - # Short-hand for years_ago(1). def last_year years_ago(1) diff --git a/activesupport/lib/active_support/core_ext/date_and_time/zones.rb b/activesupport/lib/active_support/core_ext/date_and_time/zones.rb index 894fd9b76d..fb6a27cb27 100644 --- a/activesupport/lib/active_support/core_ext/date_and_time/zones.rb +++ b/activesupport/lib/active_support/core_ext/date_and_time/zones.rb @@ -29,7 +29,6 @@ module DateAndTime end private - def time_with_zone(time, zone) if time ActiveSupport::TimeWithZone.new(time.utc? ? time : time.getutc, zone) diff --git a/activesupport/lib/active_support/core_ext/date_time/conversions.rb b/activesupport/lib/active_support/core_ext/date_time/conversions.rb index 29725c89f7..231bf870a2 100644 --- a/activesupport/lib/active_support/core_ext/date_time/conversions.rb +++ b/activesupport/lib/active_support/core_ext/date_time/conversions.rb @@ -96,7 +96,6 @@ class DateTime end private - def offset_in_seconds (offset * 86400).to_i end diff --git a/activesupport/lib/active_support/core_ext/digest.rb b/activesupport/lib/active_support/core_ext/digest.rb new file mode 100644 index 0000000000..ce1427e13a --- /dev/null +++ b/activesupport/lib/active_support/core_ext/digest.rb @@ -0,0 +1,3 @@ +# frozen_string_literal: true + +require "active_support/core_ext/digest/uuid" diff --git a/activesupport/lib/active_support/core_ext/module/delegation.rb b/activesupport/lib/active_support/core_ext/module/delegation.rb index b8996ecb10..14d7f0c484 100644 --- a/activesupport/lib/active_support/core_ext/module/delegation.rb +++ b/activesupport/lib/active_support/core_ext/module/delegation.rb @@ -205,18 +205,18 @@ class Module if allow_nil method_def = [ "def #{method_prefix}#{method}(#{definition})", - "_ = #{to}", - "if !_.nil? || nil.respond_to?(:#{method})", - " _.#{method}(#{definition})", - "end", - "end" + " _ = #{to}", + " if !_.nil? || nil.respond_to?(:#{method})", + " _.#{method}(#{definition})", + " end", + "end" ].join ";" else exception = %(raise DelegationError, "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}") method_def = [ "def #{method_prefix}#{method}(#{definition})", - " _ = #{to}", + " _ = #{to}", " _.#{method}(#{definition})", "rescue NoMethodError => e", " if _.nil? && e.name == :#{method}", @@ -276,6 +276,11 @@ class Module # The delegated method must be public on the target, otherwise it will # raise +DelegationError+. If you wish to instead return +nil+, # use the <tt>:allow_nil</tt> option. + # + # The <tt>marshal_dump</tt> and <tt>_dump</tt> methods are exempt from + # delegation due to possible interference when calling + # <tt>Marshal.dump(object)</tt>, should the delegation target method + # of <tt>object</tt> add or remove instance variables. def delegate_missing_to(target, allow_nil: nil) target = target.to_s target = "self.#{target}" if DELEGATION_RESERVED_METHOD_NAMES.include?(target) @@ -285,6 +290,7 @@ class Module # It may look like an oversight, but we deliberately do not pass # +include_private+, because they do not get delegated. + return false if name == :marshal_dump || name == :_dump #{target}.respond_to?(name) || super end diff --git a/activesupport/lib/active_support/core_ext/object/duplicable.rb b/activesupport/lib/active_support/core_ext/object/duplicable.rb index c78ee6bbfc..3ebcdca02b 100644 --- a/activesupport/lib/active_support/core_ext/object/duplicable.rb +++ b/activesupport/lib/active_support/core_ext/object/duplicable.rb @@ -28,96 +28,6 @@ class Object end end -class NilClass - begin - nil.dup - rescue TypeError - - # +nil+ is not duplicable: - # - # nil.duplicable? # => false - # nil.dup # => TypeError: can't dup NilClass - def duplicable? - false - end - end -end - -class FalseClass - begin - false.dup - rescue TypeError - - # +false+ is not duplicable: - # - # false.duplicable? # => false - # false.dup # => TypeError: can't dup FalseClass - def duplicable? - false - end - end -end - -class TrueClass - begin - true.dup - rescue TypeError - - # +true+ is not duplicable: - # - # true.duplicable? # => false - # true.dup # => TypeError: can't dup TrueClass - def duplicable? - false - end - end -end - -class Symbol - begin - :symbol.dup - - # Some symbols couldn't be duped in Ruby 2.4.0 only, due to a bug. - # This feature check catches any regression. - "symbol_from_string".to_sym.dup - rescue TypeError - - # Symbols are not duplicable: - # - # :my_symbol.duplicable? # => false - # :my_symbol.dup # => TypeError: can't dup Symbol - def duplicable? - false - end - end -end - -class Numeric - begin - 1.dup - rescue TypeError - - # Numbers are not duplicable: - # - # 3.duplicable? # => false - # 3.dup # => TypeError: can't dup Integer - def duplicable? - false - end - end -end - -require "bigdecimal" -class BigDecimal - # BigDecimals are duplicable: - # - # BigDecimal("1.2").duplicable? # => true - # BigDecimal("1.2").dup # => #<BigDecimal:...,'0.12E1',18(18)> - def duplicable? - true - end -end - class Method # Methods are not duplicable: # @@ -128,32 +38,12 @@ class Method end end -class Complex - 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 - 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 +class UnboundMethod + # Unbound methods are not duplicable: + # + # method(:puts).unbind.duplicable? # => false + # method(:puts).unbind.dup # => TypeError: allocator undefined for UnboundMethod + def duplicable? + false end end diff --git a/activesupport/lib/active_support/core_ext/range/each.rb b/activesupport/lib/active_support/core_ext/range/each.rb index 2f22cd0e92..2d86997edf 100644 --- a/activesupport/lib/active_support/core_ext/range/each.rb +++ b/activesupport/lib/active_support/core_ext/range/each.rb @@ -15,7 +15,6 @@ module ActiveSupport end private - def ensure_iteration_allowed raise TypeError, "can't iterate from #{first.class}" if first.is_a?(TimeWithZone) end diff --git a/activesupport/lib/active_support/core_ext/string/output_safety.rb b/activesupport/lib/active_support/core_ext/string/output_safety.rb index 645b1fea17..f48ea56326 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -291,7 +291,6 @@ module ActiveSupport #:nodoc: end private - def html_escape_interpolated_argument(arg) (!html_safe? || arg.html_safe?) ? arg : CGI.escapeHTML(arg.to_s) end diff --git a/activesupport/lib/active_support/core_ext/time/calculations.rb b/activesupport/lib/active_support/core_ext/time/calculations.rb index f09a6271ad..eed34965e3 100644 --- a/activesupport/lib/active_support/core_ext/time/calculations.rb +++ b/activesupport/lib/active_support/core_ext/time/calculations.rb @@ -311,4 +311,34 @@ class Time end alias_method :eql_without_coercion, :eql? alias_method :eql?, :eql_with_coercion + + # Returns a new time the specified number of days ago. + def prev_day(days = 1) + advance(days: -days) + end + + # Returns a new time the specified number of days in the future. + def next_day(days = 1) + advance(days: days) + end + + # Returns a new time the specified number of months ago. + def prev_month(months = 1) + advance(months: -months) + end + + # Returns a new time the specified number of months in the future. + def next_month(months = 1) + advance(months: months) + end + + # Returns a new time the specified number of years ago. + def prev_year(years = 1) + advance(years: -years) + end + + # Returns a new time the specified number of years in the future. + def next_year(years = 1) + advance(years: years) + end end diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 82f07c085e..32cb3a53f4 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -201,6 +201,11 @@ module ActiveSupport #:nodoc: end end + def self.include_into(base) + base.include(self) + append_features(base) + end + def const_missing(const_name) from_mod = anonymous? ? guess_for_anonymous(const_name) : self Dependencies.load_missing_constant(from_mod, const_name) @@ -230,6 +235,21 @@ module ActiveSupport #:nodoc: base.class_eval do define_method(:load, Kernel.instance_method(:load)) private :load + + define_method(:require, Kernel.instance_method(:require)) + private :require + end + end + + def self.include_into(base) + base.include(self) + + if base.instance_method(:load).owner == base + base.remove_method(:load) + end + + if base.instance_method(:require).owner == base + base.remove_method(:require) end end @@ -290,7 +310,6 @@ module ActiveSupport #:nodoc: end private - def load(file, wrap = false) result = false load_dependency(file) { result = super } @@ -326,9 +345,9 @@ module ActiveSupport #:nodoc: end def hook! - Object.class_eval { include Loadable } - Module.class_eval { include ModuleConstMissing } - Exception.class_eval { include Blamable } + Loadable.include_into(Object) + ModuleConstMissing.include_into(Module) + Exception.include(Blamable) end def unhook! diff --git a/activesupport/lib/active_support/dependencies/zeitwerk_integration.rb b/activesupport/lib/active_support/dependencies/zeitwerk_integration.rb index fd39ad6e55..821e3f971e 100644 --- a/activesupport/lib/active_support/dependencies/zeitwerk_integration.rb +++ b/activesupport/lib/active_support/dependencies/zeitwerk_integration.rb @@ -56,7 +56,6 @@ module ActiveSupport end private - def setup_autoloaders(enable_reloading) Dependencies.autoload_paths.each do |autoload_path| # Zeitwerk only accepts existing directories in `push_dir` to diff --git a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb index 56f1e23136..d7d3c30b97 100644 --- a/activesupport/lib/active_support/deprecation/proxy_wrappers.rb +++ b/activesupport/lib/active_support/deprecation/proxy_wrappers.rb @@ -120,9 +120,16 @@ module ActiveSupport # # => DEPRECATION WARNING: PLANETS is deprecated! Use PLANETS_POST_2006 instead. # (Backtrace information…) # ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"] - class DeprecatedConstantProxy < DeprecationProxy + class DeprecatedConstantProxy < Module + def self.new(*args, &block) + object = args.first + + return object unless object + super + end + def initialize(old_const, new_const, deprecator = ActiveSupport::Deprecation.instance, message: "#{old_const} is deprecated! Use #{new_const} instead.") - require "active_support/inflector/methods" + Kernel.require "active_support/inflector/methods" @old_const = old_const @new_const = new_const @@ -130,6 +137,14 @@ module ActiveSupport @message = message end + instance_methods.each { |m| undef_method m unless /^__|^object_id$/.match?(m) } + + # Don't give a deprecation warning on inspect since test/unit and error + # logs rely on it for diagnostics. + def inspect + target.inspect + end + # Returns the class of the new constant. # # PLANETS_POST_2006 = %w(mercury venus earth mars jupiter saturn uranus neptune) @@ -144,8 +159,14 @@ module ActiveSupport ActiveSupport::Inflector.constantize(@new_const.to_s) end - def warn(callstack, called, args) - @deprecator.warn(@message, callstack) + def const_missing(name) + @deprecator.warn(@message, caller_locations) + target.const_get(name) + end + + def method_missing(called, *args, &block) + @deprecator.warn(@message, caller_locations) + target.__send__(called, *args, &block) end end end diff --git a/activesupport/lib/active_support/descendants_tracker.rb b/activesupport/lib/active_support/descendants_tracker.rb index 21565138a7..b14842bf67 100644 --- a/activesupport/lib/active_support/descendants_tracker.rb +++ b/activesupport/lib/active_support/descendants_tracker.rb @@ -41,7 +41,6 @@ module ActiveSupport end private - def accumulate_descendants(klass, acc) if direct_descendants = @@direct_descendants[klass] direct_descendants.each do |direct_descendant| @@ -78,15 +77,17 @@ module ActiveSupport end def <<(klass) - cleanup! @refs << WeakRef.new(klass) end def each - @refs.each do |ref| + @refs.reject! do |ref| yield ref.__getobj__ + false rescue WeakRef::RefError + true end + self end def refs_size diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb index a30bd11a87..2b4f1288f1 100644 --- a/activesupport/lib/active_support/duration.rb +++ b/activesupport/lib/active_support/duration.rb @@ -198,7 +198,6 @@ module ActiveSupport end private - def calculate_total_seconds(parts) parts.inject(0) do |total, (part, value)| total + value * PARTS_IN_SECONDS[part] @@ -399,7 +398,6 @@ module ActiveSupport end private - def sum(sign, time = ::Time.current) parts.inject(time) do |t, (type, number)| if t.acts_like?(:time) || t.acts_like?(:date) diff --git a/activesupport/lib/active_support/duration/iso8601_parser.rb b/activesupport/lib/active_support/duration/iso8601_parser.rb index d3233e6111..83f3b28602 100644 --- a/activesupport/lib/active_support/duration/iso8601_parser.rb +++ b/activesupport/lib/active_support/duration/iso8601_parser.rb @@ -80,7 +80,6 @@ module ActiveSupport end private - def finished? scanner.eos? end diff --git a/activesupport/lib/active_support/duration/iso8601_serializer.rb b/activesupport/lib/active_support/duration/iso8601_serializer.rb index 1125454919..8314df12b0 100644 --- a/activesupport/lib/active_support/duration/iso8601_serializer.rb +++ b/activesupport/lib/active_support/duration/iso8601_serializer.rb @@ -32,7 +32,6 @@ module ActiveSupport end private - # Return pair of duration's parts and whole duration sign. # Parts are summarized (as they can become repetitive due to addition, etc). # Zero parts are removed as not significant. diff --git a/activesupport/lib/active_support/evented_file_update_checker.rb b/activesupport/lib/active_support/evented_file_update_checker.rb index 5a79822c49..6075e0a3d3 100644 --- a/activesupport/lib/active_support/evented_file_update_checker.rb +++ b/activesupport/lib/active_support/evented_file_update_checker.rb @@ -217,7 +217,6 @@ module ActiveSupport end private - def ascendant_of?(base, other) base != other && other.ascend do |ascendant| break true if base == ascendant diff --git a/activesupport/lib/active_support/file_update_checker.rb b/activesupport/lib/active_support/file_update_checker.rb index 1a0bb10815..9b665e7f19 100644 --- a/activesupport/lib/active_support/file_update_checker.rb +++ b/activesupport/lib/active_support/file_update_checker.rb @@ -98,7 +98,6 @@ module ActiveSupport end private - def watched @watched || begin all = @files.select { |f| File.exist?(f) } diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb index 5981763f0e..bbb7c36382 100644 --- a/activesupport/lib/active_support/hash_with_indifferent_access.rb +++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb @@ -367,7 +367,9 @@ module ActiveSupport key.kind_of?(Symbol) ? key.to_s : key end - def convert_value(value, options = {}) # :doc: + EMPTY_HASH = {}.freeze + + def convert_value(value, options = EMPTY_HASH) # :doc: if value.is_a? Hash if options[:for] == :to_hash value.to_hash diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb index 88cdd99dbd..efee74a1df 100644 --- a/activesupport/lib/active_support/inflector/inflections.rb +++ b/activesupport/lib/active_support/inflector/inflections.rb @@ -2,7 +2,6 @@ require "concurrent/map" require "active_support/i18n" -require "active_support/deprecation" module ActiveSupport module Inflector @@ -230,7 +229,6 @@ module ActiveSupport end private - def define_acronym_regex_patterns @acronym_regex = @acronyms.empty? ? /(?=a)b/ : /#{@acronyms.values.join("|")}/ @acronyms_camelize_regex = /^(?:#{@acronym_regex}(?=\b|[A-Z_])|\w)/ diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb index ee193add6f..18f3f53879 100644 --- a/activesupport/lib/active_support/inflector/methods.rb +++ b/activesupport/lib/active_support/inflector/methods.rb @@ -359,7 +359,6 @@ module ActiveSupport end private - # Mounts a regular expression, returned as a string to ease interpolation, # that will match part by part the given constant. # diff --git a/activesupport/lib/active_support/json/decoding.rb b/activesupport/lib/active_support/json/decoding.rb index 402a3fbe60..b4bf882bc3 100644 --- a/activesupport/lib/active_support/json/decoding.rb +++ b/activesupport/lib/active_support/json/decoding.rb @@ -44,7 +44,6 @@ module ActiveSupport end private - def convert_dates_from(data) case data when nil diff --git a/activesupport/lib/active_support/lazy_load_hooks.rb b/activesupport/lib/active_support/lazy_load_hooks.rb index a6b096a973..c6f7ccf0a2 100644 --- a/activesupport/lib/active_support/lazy_load_hooks.rb +++ b/activesupport/lib/active_support/lazy_load_hooks.rb @@ -54,7 +54,6 @@ module ActiveSupport end private - def with_execution_control(name, block, once) unless @run_once[name].include?(block) @run_once[name] << block if once diff --git a/activesupport/lib/active_support/log_subscriber.rb b/activesupport/lib/active_support/log_subscriber.rb index 938cfdb914..8b9dd1fffe 100644 --- a/activesupport/lib/active_support/log_subscriber.rb +++ b/activesupport/lib/active_support/log_subscriber.rb @@ -29,6 +29,9 @@ module ActiveSupport # subscriber, the line above should be called after your # <tt>ActiveRecord::LogSubscriber</tt> definition. # + # A logger also needs to be set with <tt>ActiveRecord::LogSubscriber.logger=</tt>. + # This is assigned automatically in a Rails environment. + # # After configured, whenever a <tt>"sql.active_record"</tt> notification is published, # it will properly dispatch the event # (<tt>ActiveSupport::Notifications::Event</tt>) to the sql method. @@ -112,7 +115,6 @@ module ActiveSupport end private - %w(info debug warn error fatal unknown).each do |level| class_eval <<-METHOD, __FILE__, __LINE__ + 1 def #{level}(progname = nil, &block) diff --git a/activesupport/lib/active_support/logger_thread_safe_level.rb b/activesupport/lib/active_support/logger_thread_safe_level.rb index f16c90cfc6..1775a41492 100644 --- a/activesupport/lib/active_support/logger_thread_safe_level.rb +++ b/activesupport/lib/active_support/logger_thread_safe_level.rb @@ -3,6 +3,7 @@ require "active_support/concern" require "active_support/core_ext/module/attribute_accessors" require "concurrent" +require "fiber" module ActiveSupport module LoggerThreadSafeLevel # :nodoc: @@ -28,7 +29,7 @@ module ActiveSupport end def local_log_id - Thread.current.__id__ + Fiber.current.__id__ end def local_level diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb index c4a4afe95f..a5dc1181d8 100644 --- a/activesupport/lib/active_support/message_verifier.rb +++ b/activesupport/lib/active_support/message_verifier.rb @@ -178,8 +178,8 @@ module ActiveSupport # Generates a signed message for the provided value. # - # The message is signed with the +MessageVerifier+'s secret. Without knowing - # the secret, the original value cannot be extracted from the message. + # The message is signed with the +MessageVerifier+'s secret. + # Returns Base64-encoded message joined with the generated signature. # # verifier = ActiveSupport::MessageVerifier.new 's3Krit' # verifier.generate 'a private message' # => "BAhJIhRwcml2YXRlLW1lc3NhZ2UGOgZFVA==--e2d724331ebdee96a10fb99b089508d1c72bd772" diff --git a/activesupport/lib/active_support/messages/rotator.rb b/activesupport/lib/active_support/messages/rotator.rb index 823a399d67..50ea7dcd8d 100644 --- a/activesupport/lib/active_support/messages/rotator.rb +++ b/activesupport/lib/active_support/messages/rotator.rb @@ -3,11 +3,12 @@ module ActiveSupport module Messages module Rotator # :nodoc: - def initialize(*, **options) + def initialize(*, on_rotation: nil, **options) super @options = options @rotations = [] + @on_rotation = on_rotation end def rotate(*secrets, **options) @@ -17,7 +18,7 @@ module ActiveSupport module Encryptor include Rotator - def decrypt_and_verify(*args, on_rotation: nil, **options) + def decrypt_and_verify(*args, on_rotation: @on_rotation, **options) super rescue MessageEncryptor::InvalidMessage, MessageVerifier::InvalidSignature run_rotations(on_rotation) { |encryptor| encryptor.decrypt_and_verify(*args, options) } || raise @@ -32,7 +33,7 @@ module ActiveSupport module Verifier include Rotator - def verified(*args, on_rotation: nil, **options) + def verified(*args, on_rotation: @on_rotation, **options) super || run_rotations(on_rotation) { |verifier| verifier.verified(*args, options) } end @@ -46,7 +47,7 @@ module ActiveSupport def run_rotations(on_rotation) @rotations.find do |rotation| if message = yield(rotation) rescue next - on_rotation.call if on_rotation + on_rotation&.call return message end end diff --git a/activesupport/lib/active_support/multibyte/chars.rb b/activesupport/lib/active_support/multibyte/chars.rb index a1e23aeaca..2ba3936cae 100644 --- a/activesupport/lib/active_support/multibyte/chars.rb +++ b/activesupport/lib/active_support/multibyte/chars.rb @@ -207,7 +207,6 @@ module ActiveSupport #:nodoc: end private - def chars(string) self.class.new(string) end diff --git a/activesupport/lib/active_support/multibyte/unicode.rb b/activesupport/lib/active_support/multibyte/unicode.rb index ce8ecece69..3956137049 100644 --- a/activesupport/lib/active_support/multibyte/unicode.rb +++ b/activesupport/lib/active_support/multibyte/unicode.rb @@ -148,7 +148,6 @@ module ActiveSupport end private - def recode_windows1252_chars(string) string.encode(Encoding::UTF_8, Encoding::Windows_1252, invalid: :replace, undef: :replace) end diff --git a/activesupport/lib/active_support/notifications/instrumenter.rb b/activesupport/lib/active_support/notifications/instrumenter.rb index 12546511a8..7ab39c9bfb 100644 --- a/activesupport/lib/active_support/notifications/instrumenter.rb +++ b/activesupport/lib/active_support/notifications/instrumenter.rb @@ -46,7 +46,6 @@ module ActiveSupport end private - def unique_id SecureRandom.hex(10) end diff --git a/activesupport/lib/active_support/number_helper.rb b/activesupport/lib/active_support/number_helper.rb index 8f3d04aa5c..0c87114c0d 100644 --- a/activesupport/lib/active_support/number_helper.rb +++ b/activesupport/lib/active_support/number_helper.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require "active_support/dependencies/autoload" - module ActiveSupport module NumberHelper extend ActiveSupport::Autoload diff --git a/activesupport/lib/active_support/number_helper/number_converter.rb b/activesupport/lib/active_support/number_helper/number_converter.rb index 06ba797a13..76dd12f27d 100644 --- a/activesupport/lib/active_support/number_helper/number_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_converter.rb @@ -136,7 +136,6 @@ module ActiveSupport end private - def options @options ||= format_options.merge(opts) end diff --git a/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb b/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb index 0e8ae82dd5..4ad89dc62e 100644 --- a/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_to_currency_converter.rb @@ -21,7 +21,6 @@ module ActiveSupport end private - def absolute_value(number) number.respond_to?(:abs) ? number.abs : number.sub(/\A-/, "") end diff --git a/activesupport/lib/active_support/number_helper/number_to_delimited_converter.rb b/activesupport/lib/active_support/number_helper/number_to_delimited_converter.rb index 467a580a2e..351444289c 100644 --- a/activesupport/lib/active_support/number_helper/number_to_delimited_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_to_delimited_converter.rb @@ -14,7 +14,6 @@ module ActiveSupport end private - def parts left, right = number.to_s.split(".") left.gsub!(delimiter_pattern) do |digit_to_delimit| diff --git a/activesupport/lib/active_support/number_helper/number_to_human_converter.rb b/activesupport/lib/active_support/number_helper/number_to_human_converter.rb index 494408fc01..f089d7ae65 100644 --- a/activesupport/lib/active_support/number_helper/number_to_human_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_to_human_converter.rb @@ -31,7 +31,6 @@ module ActiveSupport end private - def format options[:format] || translate_in_locale("human.decimal_units.format") end diff --git a/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb b/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb index 91262fa656..ed8acbda6e 100644 --- a/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_to_human_size_converter.rb @@ -28,7 +28,6 @@ module ActiveSupport end private - def conversion_format translate_number_value_with_default("human.storage_units.format", locale: options[:locale], raise: true) end diff --git a/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb b/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb index d5e72981b4..21eadfdcc7 100644 --- a/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_to_phone_converter.rb @@ -12,7 +12,6 @@ module ActiveSupport end private - def convert_to_phone_number(number) if opts[:area_code] convert_with_area_code(number) diff --git a/activesupport/lib/active_support/number_helper/number_to_rounded_converter.rb b/activesupport/lib/active_support/number_helper/number_to_rounded_converter.rb index 6ceb9a572e..767cfe22ad 100644 --- a/activesupport/lib/active_support/number_helper/number_to_rounded_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_to_rounded_converter.rb @@ -38,7 +38,6 @@ module ActiveSupport end private - def strip_insignificant_zeros options[:strip_insignificant_zeros] end diff --git a/activesupport/lib/active_support/parameter_filter.rb b/activesupport/lib/active_support/parameter_filter.rb index 1389d82523..e1cd7c46c1 100644 --- a/activesupport/lib/active_support/parameter_filter.rb +++ b/activesupport/lib/active_support/parameter_filter.rb @@ -51,7 +51,6 @@ module ActiveSupport end private - def compiled_filter @compiled_filter ||= CompiledFilter.compile(@filters, mask: @mask) end @@ -110,7 +109,12 @@ module ActiveSupport elsif value.is_a?(Hash) value = call(value, parents, original_params) elsif value.is_a?(Array) - value = value.map { |v| v.is_a?(Hash) ? call(v, parents, original_params) : v } + # If we don't pop the current parent it will be duplicated as we + # process each array value. + parents.pop if deep_regexps + value = value.map { |v| value_for_key(key, v, parents, original_params) } + # Restore the parent stack after processing the array. + parents.push(key) if deep_regexps elsif blocks.any? key = key.dup if key.duplicable? value = value.dup if value.duplicable? diff --git a/activesupport/lib/active_support/rails.rb b/activesupport/lib/active_support/rails.rb index 8b727a69ec..30857f04d8 100644 --- a/activesupport/lib/active_support/rails.rb +++ b/activesupport/lib/active_support/rails.rb @@ -13,9 +13,6 @@ # Defines Object#blank? and Object#present?. require "active_support/core_ext/object/blank" -# Rails own autoload, eager_load, etc. -require "active_support/dependencies/autoload" - # Support for ClassMethods and the included macro. require "active_support/concern" diff --git a/activesupport/lib/active_support/secure_compare_rotator.rb b/activesupport/lib/active_support/secure_compare_rotator.rb new file mode 100644 index 0000000000..14a0aee947 --- /dev/null +++ b/activesupport/lib/active_support/secure_compare_rotator.rb @@ -0,0 +1,52 @@ +# frozen_string_literal: true + +require "active_support/security_utils" +require "active_support/messages/rotator" + +module ActiveSupport + # The ActiveSupport::SecureCompareRotator is a wrapper around +ActiveSupport::SecurityUtils.secure_compare+ + # and allows you to rotate a previously defined value to a new one. + # + # It can be used as follow: + # + # rotator = ActiveSupport::SecureCompareRotator.new('new_production_value') + # rotator.rotate('previous_production_value') + # rotator.secure_compare!('previous_production_value') + # + # One real use case example would be to rotate a basic auth credentials: + # + # class MyController < ApplicationController + # def authenticate_request + # rotator = ActiveSupport::SecureComparerotator.new('new_password') + # rotator.rotate('old_password') + # + # authenticate_or_request_with_http_basic do |username, password| + # rotator.secure_compare!(password) + # rescue ActiveSupport::SecureCompareRotator::InvalidMatch + # false + # end + # end + # end + class SecureCompareRotator + include SecurityUtils + prepend Messages::Rotator + + InvalidMatch = Class.new(StandardError) + + def initialize(value, **_options) + @value = value + end + + def secure_compare!(other_value, on_rotation: @rotation) + secure_compare(@value, other_value) || + run_rotations(on_rotation) { |wrapper| wrapper.secure_compare!(other_value) } || + raise(InvalidMatch) + end + + private + + def build_rotation(previous_value, _options) + self.class.new(previous_value) + end + end +end diff --git a/activesupport/lib/active_support/string_inquirer.rb b/activesupport/lib/active_support/string_inquirer.rb index a3af36720e..e5091e127a 100644 --- a/activesupport/lib/active_support/string_inquirer.rb +++ b/activesupport/lib/active_support/string_inquirer.rb @@ -18,7 +18,6 @@ module ActiveSupport # vehicle.bike? # => false class StringInquirer < String private - def respond_to_missing?(method_name, include_private = false) (method_name[-1] == "?") || super end diff --git a/activesupport/lib/active_support/testing/parallelization.rb b/activesupport/lib/active_support/testing/parallelization.rb index f50a5e0554..96518a4a58 100644 --- a/activesupport/lib/active_support/testing/parallelization.rb +++ b/activesupport/lib/active_support/testing/parallelization.rb @@ -72,7 +72,11 @@ module ActiveSupport def start @pool = @queue_size.times.map do |worker| + title = "Rails test worker #{worker}" + fork do + Process.setproctitle("#{title} - (starting)") + DRb.stop_service begin @@ -85,6 +89,9 @@ module ActiveSupport klass = job[0] method = job[1] reporter = job[2] + + Process.setproctitle("#{title} - #{klass}##{method}") + result = klass.with_info_handler reporter do Minitest.run_one_method(klass, method) end @@ -99,8 +106,12 @@ module ActiveSupport end queue.record(reporter, result) end + + Process.setproctitle("#{title} - (idle)") end ensure + Process.setproctitle("#{title} - (stopping)") + run_cleanup(worker) end end diff --git a/activesupport/lib/active_support/testing/stream.rb b/activesupport/lib/active_support/testing/stream.rb index 127cfe1e12..f895a74644 100644 --- a/activesupport/lib/active_support/testing/stream.rb +++ b/activesupport/lib/active_support/testing/stream.rb @@ -4,7 +4,6 @@ module ActiveSupport module Testing module Stream #:nodoc: private - def silence_stream(stream) old_stream = stream.dup stream.reopen(IO::NULL) diff --git a/activesupport/lib/active_support/testing/time_helpers.rb b/activesupport/lib/active_support/testing/time_helpers.rb index 5a3fa9346c..84bd920d86 100644 --- a/activesupport/lib/active_support/testing/time_helpers.rb +++ b/activesupport/lib/active_support/testing/time_helpers.rb @@ -40,7 +40,6 @@ module ActiveSupport end private - def unstub_object(stub) singleton_class = stub.object.singleton_class singleton_class.silence_redefinition_of_method stub.method_name @@ -191,7 +190,6 @@ module ActiveSupport end private - def simple_stubs @simple_stubs ||= SimpleStubs.new end diff --git a/activesupport/lib/active_support/xml_mini.rb b/activesupport/lib/active_support/xml_mini.rb index 075cd4ed8b..f6ae08bb5d 100644 --- a/activesupport/lib/active_support/xml_mini.rb +++ b/activesupport/lib/active_support/xml_mini.rb @@ -155,7 +155,6 @@ module ActiveSupport end private - def _dasherize(key) # $2 must be a non-greedy regex for this to work left, middle, right = /\A(_*)(.*?)(_*)\Z/.match(key.strip)[1, 3] diff --git a/activesupport/lib/active_support/xml_mini/jdom.rb b/activesupport/lib/active_support/xml_mini/jdom.rb index 32fe6ade28..12ca19a76f 100644 --- a/activesupport/lib/active_support/xml_mini/jdom.rb +++ b/activesupport/lib/active_support/xml_mini/jdom.rb @@ -53,7 +53,6 @@ module ActiveSupport end private - # Convert an XML element and merge into the hash # # hash:: diff --git a/activesupport/test/cache/behaviors/cache_store_behavior.rb b/activesupport/test/cache/behaviors/cache_store_behavior.rb index a696760bb2..e6f014e08d 100644 --- a/activesupport/test/cache/behaviors/cache_store_behavior.rb +++ b/activesupport/test/cache/behaviors/cache_store_behavior.rb @@ -507,7 +507,6 @@ module CacheStoreBehavior end private - def assert_compressed(value, **options) assert_compression(true, value, **options) end diff --git a/activesupport/test/cache/behaviors/local_cache_behavior.rb b/activesupport/test/cache/behaviors/local_cache_behavior.rb index baa38ba6ac..6f5d53c190 100644 --- a/activesupport/test/cache/behaviors/local_cache_behavior.rb +++ b/activesupport/test/cache/behaviors/local_cache_behavior.rb @@ -46,6 +46,15 @@ module LocalCacheBehavior end end + def test_local_cache_of_read_returns_a_copy_of_the_entry + @cache.with_local_cache do + @cache.write(:foo, type: "bar") + value = @cache.read(:foo) + assert_equal("bar", value.delete(:type)) + assert_equal({ type: "bar" }, @cache.read(:foo)) + end + end + def test_local_cache_of_read @cache.write("foo", "bar") @cache.with_local_cache do diff --git a/activesupport/test/cache/cache_key_test.rb b/activesupport/test/cache/cache_key_test.rb index c2240d03c2..f0cd991553 100644 --- a/activesupport/test/cache/cache_key_test.rb +++ b/activesupport/test/cache/cache_key_test.rb @@ -79,7 +79,6 @@ class CacheKeyTest < ActiveSupport::TestCase end private - def with_env(kv) old_values = {} kv.each { |key, value| old_values[key], ENV[key] = ENV[key], value } diff --git a/activesupport/test/cache/stores/mem_cache_store_test.rb b/activesupport/test/cache/stores/mem_cache_store_test.rb index 0e472f5a1a..3917d14d1c 100644 --- a/activesupport/test/cache/stores/mem_cache_store_test.rb +++ b/activesupport/test/cache/stores/mem_cache_store_test.rb @@ -113,7 +113,6 @@ class MemCacheStoreTest < ActiveSupport::TestCase end private - def store [:mem_cache_store, ENV["MEMCACHE_SERVERS"] || "localhost:11211"] end diff --git a/activesupport/test/cache/stores/redis_cache_store_test.rb b/activesupport/test/cache/stores/redis_cache_store_test.rb index 790534cd3c..a2177e0476 100644 --- a/activesupport/test/cache/stores/redis_cache_store_test.rb +++ b/activesupport/test/cache/stores/redis_cache_store_test.rb @@ -191,7 +191,6 @@ module ActiveSupport::Cache::RedisCacheStoreTests include ConnectionPoolBehavior private - def store [:redis_cache_store] end @@ -238,7 +237,6 @@ module ActiveSupport::Cache::RedisCacheStoreTests include FailureSafetyBehavior private - def emulating_unavailability old_client = Redis.send(:remove_const, :Client) Redis.const_set(:Client, UnavailableRedisClient) diff --git a/activesupport/test/callbacks_test.rb b/activesupport/test/callbacks_test.rb index 79098b2a7d..cc37c4fa99 100644 --- a/activesupport/test/callbacks_test.rb +++ b/activesupport/test/callbacks_test.rb @@ -397,7 +397,6 @@ module CallbacksTest end private - def record1 @recorder << 1 end @@ -989,6 +988,7 @@ module CallbacksTest define_callbacks :foo, scope: [:name] set_callback :foo, :before, :foo, if: callback def run; run_callbacks :foo; end + private def foo; end } diff --git a/activesupport/test/core_ext/date_and_time_behavior.rb b/activesupport/test/core_ext/date_and_time_behavior.rb index b77ea22701..6d31734f27 100644 --- a/activesupport/test/core_ext/date_and_time_behavior.rb +++ b/activesupport/test/core_ext/date_and_time_behavior.rb @@ -8,31 +8,11 @@ module DateAndTimeBehavior assert_equal date_time_init(2005, 2, 28, 10, 10, 10), date_time_init(2005, 3, 2, 10, 10, 10).yesterday.yesterday end - def test_prev_day - assert_equal date_time_init(2005, 2, 24, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(-2) - assert_equal date_time_init(2005, 2, 23, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(-1) - assert_equal date_time_init(2005, 2, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(0) - assert_equal date_time_init(2005, 2, 21, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(1) - assert_equal date_time_init(2005, 2, 20, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(2) - assert_equal date_time_init(2005, 2, 21, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day - assert_equal date_time_init(2005, 2, 28, 10, 10, 10), date_time_init(2005, 3, 2, 10, 10, 10).prev_day.prev_day - end - def test_tomorrow assert_equal date_time_init(2005, 2, 23, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).tomorrow assert_equal date_time_init(2005, 3, 2, 10, 10, 10), date_time_init(2005, 2, 28, 10, 10, 10).tomorrow.tomorrow end - def test_next_day - assert_equal date_time_init(2005, 2, 20, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(-2) - assert_equal date_time_init(2005, 2, 21, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(-1) - assert_equal date_time_init(2005, 2, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(0) - assert_equal date_time_init(2005, 2, 23, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(1) - assert_equal date_time_init(2005, 2, 24, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(2) - assert_equal date_time_init(2005, 2, 23, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day - assert_equal date_time_init(2005, 3, 2, 10, 10, 10), date_time_init(2005, 2, 28, 10, 10, 10).next_day.next_day - end - def test_days_ago assert_equal date_time_init(2005, 6, 4, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).days_ago(1) assert_equal date_time_init(2005, 5, 31, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).days_ago(5) @@ -161,16 +141,6 @@ module DateAndTimeBehavior assert_equal date_time_init(2015, 1, 5, 15, 15, 10), date_time_init(2015, 1, 3, 15, 15, 10).next_weekday end - def test_next_month - assert_equal date_time_init(2004, 12, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(-2) - assert_equal date_time_init(2005, 1, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(-1) - assert_equal date_time_init(2005, 2, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(0) - assert_equal date_time_init(2005, 3, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(1) - assert_equal date_time_init(2005, 4, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(2) - assert_equal date_time_init(2005, 3, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month - assert_equal date_time_init(2005, 4, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month.next_month - end - def test_next_month_on_31st assert_equal date_time_init(2005, 9, 30, 15, 15, 10), date_time_init(2005, 8, 31, 15, 15, 10).next_month end @@ -179,16 +149,6 @@ module DateAndTimeBehavior assert_equal date_time_init(2005, 11, 30, 15, 15, 10), date_time_init(2005, 8, 31, 15, 15, 10).next_quarter end - def test_next_year - assert_equal date_time_init(2003, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(-2) - assert_equal date_time_init(2004, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(-1) - assert_equal date_time_init(2005, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(0) - assert_equal date_time_init(2006, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(1) - assert_equal date_time_init(2007, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(2) - assert_equal date_time_init(2006, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year - assert_equal date_time_init(2007, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year.next_year - end - def test_prev_week assert_equal date_time_init(2005, 2, 21, 0, 0, 0), date_time_init(2005, 3, 1, 15, 15, 10).prev_week assert_equal date_time_init(2005, 2, 22, 0, 0, 0), date_time_init(2005, 3, 1, 15, 15, 10).prev_week(:tuesday) @@ -229,16 +189,6 @@ module DateAndTimeBehavior assert_equal date_time_init(2015, 1, 2, 15, 15, 10), date_time_init(2015, 1, 4, 15, 15, 10).prev_weekday end - def test_prev_month - assert_equal date_time_init(2005, 4, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(-2) - assert_equal date_time_init(2005, 3, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(-1) - assert_equal date_time_init(2005, 2, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(0) - assert_equal date_time_init(2005, 1, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(1) - assert_equal date_time_init(2004, 12, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(2) - assert_equal date_time_init(2005, 1, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month - assert_equal date_time_init(2004, 12, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month.prev_month - end - def test_prev_month_on_31st assert_equal date_time_init(2004, 2, 29, 10, 10, 10), date_time_init(2004, 3, 31, 10, 10, 10).prev_month end @@ -247,16 +197,6 @@ module DateAndTimeBehavior assert_equal date_time_init(2004, 2, 29, 10, 10, 10), date_time_init(2004, 5, 31, 10, 10, 10).prev_quarter end - def test_prev_year - assert_equal date_time_init(2007, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(-2) - assert_equal date_time_init(2006, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(-1) - assert_equal date_time_init(2005, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(0) - assert_equal date_time_init(2004, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(1) - assert_equal date_time_init(2003, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(2) - assert_equal date_time_init(2004, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year - assert_equal date_time_init(2003, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year.prev_year - end - def test_last_month_on_31st assert_equal date_time_init(2004, 2, 29, 0, 0, 0), date_time_init(2004, 3, 31, 0, 0, 0).last_month end diff --git a/activesupport/test/core_ext/date_ext_test.rb b/activesupport/test/core_ext/date_ext_test.rb index b8652884ce..7060dd3c56 100644 --- a/activesupport/test/core_ext/date_ext_test.rb +++ b/activesupport/test/core_ext/date_ext_test.rb @@ -112,14 +112,6 @@ class DateExtCalculationsTest < ActiveSupport::TestCase assert_equal Date.new(2005, 4, 30), Date.new(2005, 4, 20).end_of_month end - def test_prev_year_in_leap_years - assert_equal Date.new(1999, 2, 28), Date.new(2000, 2, 29).prev_year - end - - def test_prev_year_in_calendar_reform - assert_equal Date.new(1582, 10, 4), Date.new(1583, 10, 14).prev_year - end - def test_last_year_in_leap_years assert_equal Date.new(1999, 2, 28), Date.new(2000, 2, 29).last_year end @@ -128,14 +120,6 @@ class DateExtCalculationsTest < ActiveSupport::TestCase assert_equal Date.new(1582, 10, 4), Date.new(1583, 10, 14).last_year end - def test_next_year_in_leap_years - assert_equal Date.new(2001, 2, 28), Date.new(2000, 2, 29).next_year - end - - def test_next_year_in_calendar_reform - assert_equal Date.new(1582, 10, 4), Date.new(1581, 10, 10).next_year - end - def test_advance assert_equal Date.new(2006, 2, 28), Date.new(2005, 2, 28).advance(years: 1) assert_equal Date.new(2005, 6, 28), Date.new(2005, 2, 28).advance(months: 4) diff --git a/activesupport/test/core_ext/module_test.rb b/activesupport/test/core_ext/module_test.rb index 6e341480d1..dd36a9373a 100644 --- a/activesupport/test/core_ext/module_test.rb +++ b/activesupport/test/core_ext/module_test.rb @@ -25,7 +25,6 @@ Someone = Struct.new(:name, :place) do delegate :bar, to: :place, allow_nil: true private - def private_name "Private" end @@ -112,6 +111,24 @@ class DecoratedReserved end end +class Maze + attr_accessor :cavern, :passages +end + +class Cavern + delegate_missing_to :target + + attr_reader :maze + + def initialize(maze) + @maze = maze + end + + def target + @maze.passages = :twisty + end +end + class Block def hello? true @@ -412,6 +429,17 @@ class ModuleTest < ActiveSupport::TestCase assert_respond_to DecoratedTester.new(@david), :extra_missing end + def test_delegate_missing_to_does_not_interfere_with_marshallization + maze = Maze.new + maze.cavern = Cavern.new(maze) + + array = [maze, nil] + serialized_array = Marshal.dump(array) + deserialized_array = Marshal.load(serialized_array) + + assert_nil deserialized_array[1] + end + def test_delegate_with_case event = Event.new(Tester.new) assert_equal 1, event.foo diff --git a/activesupport/test/core_ext/object/duplicable_test.rb b/activesupport/test/core_ext/object/duplicable_test.rb index c9af2cb624..a577c30c40 100644 --- a/activesupport/test/core_ext/object/duplicable_test.rb +++ b/activesupport/test/core_ext/object/duplicable_test.rb @@ -6,7 +6,7 @@ require "active_support/core_ext/object/duplicable" require "active_support/core_ext/numeric/time" class DuplicableTest < ActiveSupport::TestCase - RAISE_DUP = [method(:puts)] + RAISE_DUP = [method(:puts), method(:puts).unbind] ALLOW_DUP = ["1", "symbol_from_string".to_sym, Object.new, /foo/, [], {}, Time.now, Class.new, Module.new, BigDecimal("4.56"), nil, false, true, 1, 2.3, Complex(1), Rational(1)] def test_duplicable diff --git a/activesupport/test/core_ext/time_ext_test.rb b/activesupport/test/core_ext/time_ext_test.rb index 590b81b770..41ab98e721 100644 --- a/activesupport/test/core_ext/time_ext_test.rb +++ b/activesupport/test/core_ext/time_ext_test.rb @@ -949,6 +949,66 @@ class TimeExtCalculationsTest < ActiveSupport::TestCase assert_equal "invalid date", exception.message end + + def test_prev_day + assert_equal date_time_init(2005, 2, 24, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(-2) + assert_equal date_time_init(2005, 2, 23, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(-1) + assert_equal date_time_init(2005, 2, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(0) + assert_equal date_time_init(2005, 2, 21, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(1) + assert_equal date_time_init(2005, 2, 20, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day(2) + assert_equal date_time_init(2005, 2, 21, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_day + assert_equal date_time_init(2005, 2, 28, 10, 10, 10), date_time_init(2005, 3, 2, 10, 10, 10).prev_day.prev_day + end + + def test_next_day + assert_equal date_time_init(2005, 2, 20, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(-2) + assert_equal date_time_init(2005, 2, 21, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(-1) + assert_equal date_time_init(2005, 2, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(0) + assert_equal date_time_init(2005, 2, 23, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(1) + assert_equal date_time_init(2005, 2, 24, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day(2) + assert_equal date_time_init(2005, 2, 23, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_day + assert_equal date_time_init(2005, 3, 2, 10, 10, 10), date_time_init(2005, 2, 28, 10, 10, 10).next_day.next_day + end + + def test_prev_month + assert_equal date_time_init(2005, 4, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(-2) + assert_equal date_time_init(2005, 3, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(-1) + assert_equal date_time_init(2005, 2, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(0) + assert_equal date_time_init(2005, 1, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(1) + assert_equal date_time_init(2004, 12, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month(2) + assert_equal date_time_init(2005, 1, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month + assert_equal date_time_init(2004, 12, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).prev_month.prev_month + end + + def test_next_month + assert_equal date_time_init(2004, 12, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(-2) + assert_equal date_time_init(2005, 1, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(-1) + assert_equal date_time_init(2005, 2, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(0) + assert_equal date_time_init(2005, 3, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(1) + assert_equal date_time_init(2005, 4, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month(2) + assert_equal date_time_init(2005, 3, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month + assert_equal date_time_init(2005, 4, 22, 10, 10, 10), date_time_init(2005, 2, 22, 10, 10, 10).next_month.next_month + end + + def test_prev_year + assert_equal date_time_init(2007, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(-2) + assert_equal date_time_init(2006, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(-1) + assert_equal date_time_init(2005, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(0) + assert_equal date_time_init(2004, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(1) + assert_equal date_time_init(2003, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year(2) + assert_equal date_time_init(2004, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year + assert_equal date_time_init(2003, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).prev_year.prev_year + end + + def test_next_year + assert_equal date_time_init(2003, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(-2) + assert_equal date_time_init(2004, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(-1) + assert_equal date_time_init(2005, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(0) + assert_equal date_time_init(2006, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(1) + assert_equal date_time_init(2007, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year(2) + assert_equal date_time_init(2006, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year + assert_equal date_time_init(2007, 6, 5, 10, 10, 10), date_time_init(2005, 6, 5, 10, 10, 10).next_year.next_year + end end class TimeExtMarshalingTest < ActiveSupport::TestCase diff --git a/activesupport/test/deprecation/method_wrappers_test.rb b/activesupport/test/deprecation/method_wrappers_test.rb index 0aa3233aab..8c40534452 100644 --- a/activesupport/test/deprecation/method_wrappers_test.rb +++ b/activesupport/test/deprecation/method_wrappers_test.rb @@ -10,12 +10,10 @@ class MethodWrappersTest < ActiveSupport::TestCase alias_method :old_method, :new_method protected - def new_protected_method; "abc" end alias_method :old_protected_method, :new_protected_method private - def new_private_method; "abc" end alias_method :old_private_method, :new_private_method end diff --git a/activesupport/test/deprecation_test.rb b/activesupport/test/deprecation_test.rb index f25c704586..ae2f4a6e58 100644 --- a/activesupport/test/deprecation_test.rb +++ b/activesupport/test/deprecation_test.rb @@ -38,6 +38,11 @@ class Deprecatee C = 1 end A = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("Deprecatee::A", "Deprecatee::B::C") + + module New + class Descendant; end + end + Old = ActiveSupport::Deprecation::DeprecatedConstantProxy.new("Deprecatee::Old", "Deprecatee::New") end class DeprecateeWithAccessor @@ -210,6 +215,18 @@ class DeprecationTest < ActiveSupport::TestCase assert_not_deprecated { assert_equal Deprecatee::B::C.class, Deprecatee::A.class } end + def test_deprecated_constant_descendant + assert_not_deprecated { Deprecatee::New::Descendant } + + assert_deprecated("Deprecatee::Old") do + assert_equal Deprecatee::Old::Descendant, Deprecatee::New::Descendant + end + + assert_raises(NameError) do + assert_deprecated("Deprecatee::Old") { Deprecatee::Old::NON_EXISTENCE } + end + end + def test_deprecated_constant_accessor assert_not_deprecated { DeprecateeWithAccessor::B::C } assert_deprecated("DeprecateeWithAccessor::A") { assert_equal DeprecateeWithAccessor::B::C, DeprecateeWithAccessor::A } diff --git a/activesupport/test/descendants_tracker_test_cases.rb b/activesupport/test/descendants_tracker_test_cases.rb index f8752688d2..7d39783826 100644 --- a/activesupport/test/descendants_tracker_test_cases.rb +++ b/activesupport/test/descendants_tracker_test_cases.rb @@ -52,7 +52,6 @@ module DescendantsTrackerTestCases end private - def assert_equal_sets(expected, actual) assert_equal Set.new(expected), Set.new(actual) end diff --git a/activesupport/test/json/decoding_test.rb b/activesupport/test/json/decoding_test.rb index 8d9587f248..2e8ea01aca 100644 --- a/activesupport/test/json/decoding_test.rb +++ b/activesupport/test/json/decoding_test.rb @@ -113,7 +113,6 @@ class TestJSONDecoding < ActiveSupport::TestCase end private - def with_parse_json_times(value) old_value = ActiveSupport.parse_json_times ActiveSupport.parse_json_times = value diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index 7589ffd0ea..c4e0b71f26 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -466,7 +466,6 @@ EXPECTED end private - def object_keys(json_object) json_object[1..-2].scan(/([^{}:,\s]+):/).flatten.sort end diff --git a/activesupport/test/lazy_load_hooks_test.rb b/activesupport/test/lazy_load_hooks_test.rb index 50a703e49f..5e9a21f047 100644 --- a/activesupport/test/lazy_load_hooks_test.rb +++ b/activesupport/test/lazy_load_hooks_test.rb @@ -175,7 +175,6 @@ class LazyLoadHooksTest < ActiveSupport::TestCase end private - def incr_amt 5 end diff --git a/activesupport/test/logger_test.rb b/activesupport/test/logger_test.rb index 160e1156b6..6f7a186022 100644 --- a/activesupport/test/logger_test.rb +++ b/activesupport/test/logger_test.rb @@ -258,6 +258,50 @@ class LoggerTest < ActiveSupport::TestCase assert_level(Logger::INFO) end + def test_logger_level_main_fiber_safety + @logger.level = Logger::INFO + assert_level(Logger::INFO) + + fiber = Fiber.new do + assert_level(Logger::INFO) + end + + @logger.silence(Logger::ERROR) do + assert_level(Logger::ERROR) + fiber.resume + end + end + + def test_logger_level_local_fiber_safety + @logger.level = Logger::INFO + assert_level(Logger::INFO) + + another_fiber = Fiber.new do + @logger.silence(Logger::ERROR) do + assert_level(Logger::ERROR) + @logger.silence(Logger::DEBUG) do + assert_level(Logger::DEBUG) + end + end + + assert_level(Logger::INFO) + end + + Fiber.new do + @logger.silence(Logger::ERROR) do + assert_level(Logger::ERROR) + @logger.silence(Logger::DEBUG) do + another_fiber.resume + assert_level(Logger::DEBUG) + end + end + + assert_level(Logger::INFO) + end.resume + + assert_level(Logger::INFO) + end + private def level_name(level) ::Logger::Severity.constants.find do |severity| diff --git a/activesupport/test/message_encryptor_test.rb b/activesupport/test/message_encryptor_test.rb index 9edf07f762..097aa8b5f8 100644 --- a/activesupport/test/message_encryptor_test.rb +++ b/activesupport/test/message_encryptor_test.rb @@ -171,6 +171,34 @@ class MessageEncryptorTest < ActiveSupport::TestCase assert rotated end + def test_on_rotation_can_be_passed_at_the_constructor_level + older_message = ActiveSupport::MessageEncryptor.new(secrets[:older], "older sign").encrypt_and_sign(encoded: "message") + + rotated = false + encryptor = ActiveSupport::MessageEncryptor.new(@secret, on_rotation: proc { rotated = true }) + encryptor.rotate secrets[:older], "older sign" + + assert_changes(:rotated, from: false, to: true) do + message = encryptor.decrypt_and_verify(older_message) + + assert_equal({ encoded: "message" }, message) + end + end + + def test_on_rotation_option_takes_precedence_over_the_one_given_in_constructor + older_message = ActiveSupport::MessageEncryptor.new(secrets[:older], "older sign").encrypt_and_sign(encoded: "message") + + rotated = false + encryptor = ActiveSupport::MessageEncryptor.new(@secret, on_rotation: proc { rotated = true }) + encryptor.rotate secrets[:older], "older sign" + + assert_changes(:rotated, from: false, to: "Yes") do + message = encryptor.decrypt_and_verify(older_message, on_rotation: proc { rotated = "Yes" }) + + assert_equal({ encoded: "message" }, message) + end + end + def test_with_rotated_metadata old_message = ActiveSupport::MessageEncryptor.new(secrets[:old], cipher: "aes-256-gcm"). encrypt_and_sign("metadata", purpose: :rotation) diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index 5f4e3f3fd3..e0e0d9afc0 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -783,7 +783,6 @@ class MultibyteCharsExtrasTest < ActiveSupport::TestCase end private - def string_from_classes(classes) # Characters from the character classes as described in UAX #29 character_from_class = { diff --git a/activesupport/test/notifications_test.rb b/activesupport/test/notifications_test.rb index 02b90b0297..c9c63680e4 100644 --- a/activesupport/test/notifications_test.rb +++ b/activesupport/test/notifications_test.rb @@ -20,7 +20,6 @@ module Notifications end private - def event(*args) ActiveSupport::Notifications::Event.new(*args) end diff --git a/activesupport/test/parameter_filter_test.rb b/activesupport/test/parameter_filter_test.rb index d2dc71061d..e680a22479 100644 --- a/activesupport/test/parameter_filter_test.rb +++ b/activesupport/test/parameter_filter_test.rb @@ -28,10 +28,17 @@ class ParameterFilterTest < ActiveSupport::TestCase value.replace("world!") if original_params["barg"]["blah"] == "bar" && key == "hello" } + filter_words << lambda { |key, value| + value.upcase! if key == "array_elements" + } + parameter_filter = ActiveSupport::ParameterFilter.new(filter_words) before_filter["barg"] = { :bargain => "gain", "blah" => "bar", "bar" => { "bargain" => { "blah" => "foo", "hello" => "world" } } } after_filter["barg"] = { :bargain => "niag", "blah" => "[FILTERED]", "bar" => { "bargain" => { "blah" => "[FILTERED]", "hello" => "world!" } } } + before_filter["array_elements"] = %w(element1 element2) + after_filter["array_elements"] = %w(ELEMENT1 ELEMENT2) + assert_equal after_filter, parameter_filter.filter(before_filter) end end diff --git a/activesupport/test/secure_compare_rotator_test.rb b/activesupport/test/secure_compare_rotator_test.rb new file mode 100644 index 0000000000..8acf13e38f --- /dev/null +++ b/activesupport/test/secure_compare_rotator_test.rb @@ -0,0 +1,44 @@ +# frozen_string_literal: true + +require "abstract_unit" +require "active_support/secure_compare_rotator" + +class SecureCompareRotatorTest < ActiveSupport::TestCase + test "#secure_compare! works correctly after rotation" do + wrapper = ActiveSupport::SecureCompareRotator.new("old_secret") + wrapper.rotate("new_secret") + + assert_equal(true, wrapper.secure_compare!("new_secret")) + end + + test "#secure_compare! works correctly after multiple rotation" do + wrapper = ActiveSupport::SecureCompareRotator.new("old_secret") + wrapper.rotate("new_secret") + wrapper.rotate("another_secret") + wrapper.rotate("and_another_one") + + assert_equal(true, wrapper.secure_compare!("and_another_one")) + end + + test "#secure_compare! fails correctly when credential is not part of the rotation" do + wrapper = ActiveSupport::SecureCompareRotator.new("old_secret") + wrapper.rotate("new_secret") + + assert_raises(ActiveSupport::SecureCompareRotator::InvalidMatch) do + wrapper.secure_compare!("different_secret") + end + end + + test "#secure_compare! calls the on_rotation proc" do + wrapper = ActiveSupport::SecureCompareRotator.new("old_secret") + wrapper.rotate("new_secret") + wrapper.rotate("another_secret") + wrapper.rotate("and_another_one") + + @witness = nil + + assert_changes(:@witness, from: nil, to: true) do + assert_equal(true, wrapper.secure_compare!("and_another_one", on_rotation: -> { @witness = true })) + end + end +end diff --git a/activesupport/test/share_lock_test.rb b/activesupport/test/share_lock_test.rb index a40c813fe3..68e78ccc16 100644 --- a/activesupport/test/share_lock_test.rb +++ b/activesupport/test/share_lock_test.rb @@ -488,12 +488,10 @@ class ShareLockTest < ActiveSupport::TestCase end private - module CustomAssertions SUFFICIENT_TIMEOUT = 0.2 private - def assert_threads_stuck_but_releasable_by_latch(threads, latch) assert_threads_stuck threads latch.count_down diff --git a/activesupport/test/subscriber_test.rb b/activesupport/test/subscriber_test.rb index bc8d8f1c13..829fba6057 100644 --- a/activesupport/test/subscriber_test.rb +++ b/activesupport/test/subscriber_test.rb @@ -17,7 +17,6 @@ class TestSubscriber < ActiveSupport::Subscriber end private - def private_party(event) events << event end diff --git a/activesupport/test/test_case_test.rb b/activesupport/test/test_case_test.rb index 56cd2665e0..dd75548e9c 100644 --- a/activesupport/test/test_case_test.rb +++ b/activesupport/test/test_case_test.rb @@ -315,7 +315,6 @@ class SetupAndTeardownTest < ActiveSupport::TestCase end private - def reset_callback_record @called_back = [] end diff --git a/guides/assets/images/getting_started/unknown_action_create_for_articles.png b/guides/assets/images/getting_started/unknown_action_create_for_articles.png Binary files differindex ec4758e085..e75b9780cc 100644 --- a/guides/assets/images/getting_started/unknown_action_create_for_articles.png +++ b/guides/assets/images/getting_started/unknown_action_create_for_articles.png diff --git a/guides/rails_guides/generator.rb b/guides/rails_guides/generator.rb index 7d4a15962c..2b2ccfa906 100644 --- a/guides/rails_guides/generator.rb +++ b/guides/rails_guides/generator.rb @@ -43,7 +43,6 @@ module RailsGuides end private - def register_kindle_mime_types Mime::Type.register_alias("application/xml", :opf, %w(opf)) Mime::Type.register_alias("application/xml", :ncx, %w(ncx)) diff --git a/guides/rails_guides/indexer.rb b/guides/rails_guides/indexer.rb index c707464cdf..576ec85b27 100644 --- a/guides/rails_guides/indexer.rb +++ b/guides/rails_guides/indexer.rb @@ -18,7 +18,6 @@ module RailsGuides end private - def process(string, current_level = 3, counters = [1]) s = StringScanner.new(string) diff --git a/guides/rails_guides/markdown.rb b/guides/rails_guides/markdown.rb index 018f49ffd0..d926d233bb 100644 --- a/guides/rails_guides/markdown.rb +++ b/guides/rails_guides/markdown.rb @@ -30,7 +30,6 @@ module RailsGuides end private - def dom_id(nodes) dom_id = dom_id_text(nodes.last.text) diff --git a/guides/rails_guides/markdown/renderer.rb b/guides/rails_guides/markdown/renderer.rb index 7f14c28bbc..4877e806fd 100644 --- a/guides/rails_guides/markdown/renderer.rb +++ b/guides/rails_guides/markdown/renderer.rb @@ -53,7 +53,6 @@ HTML end private - def convert_footnotes(text) text.gsub(/\[<sup>(\d+)\]<\/sup>/i) do %(<sup class="footnote" id="footnote-#{$1}-ref">) + diff --git a/guides/source/2_3_release_notes.md b/guides/source/2_3_release_notes.md index ee9a499953..b46d5ee4db 100644 --- a/guides/source/2_3_release_notes.md +++ b/guides/source/2_3_release_notes.md @@ -415,7 +415,7 @@ select_datetime(DateTime.now, :prompt => ### AssetTag Timestamp Caching -You're likely familiar with Rails' practice of adding timestamps to static asset paths as a "cache buster." This helps ensure that stale copies of things like images and stylesheets don't get served out of the user's browser cache when you change them on the server. You can now modify this behavior with the `cache_asset_timestamps` configuration option for Action View. If you enable the cache, then Rails will calculate the timestamp once when it first serves an asset, and save that value. This means fewer (expensive) file system calls to serve static assets - but it also means that you can't modify any of the assets while the server is running and expect the changes to get picked up by clients. +You're likely familiar with Rails' practice of adding timestamps to static asset paths as a "cache buster". This helps ensure that stale copies of things like images and stylesheets don't get served out of the user's browser cache when you change them on the server. You can now modify this behavior with the `cache_asset_timestamps` configuration option for Action View. If you enable the cache, then Rails will calculate the timestamp once when it first serves an asset, and save that value. This means fewer (expensive) file system calls to serve static assets - but it also means that you can't modify any of the assets while the server is running and expect the changes to get picked up by clients. ### Asset Hosts as Objects diff --git a/guides/source/5_2_release_notes.md b/guides/source/5_2_release_notes.md index ac247bc3f9..7aac07dbbe 100644 --- a/guides/source/5_2_release_notes.md +++ b/guides/source/5_2_release_notes.md @@ -326,7 +326,7 @@ Please refer to the [Changelog][action-view] for detailed changes. select divider `option`. ([Pull Request](https://github.com/rails/rails/pull/31088)) -* Change `form_with` to generates ids by default. +* Change `form_with` to generate ids by default. ([Commit](https://github.com/rails/rails/commit/260d6f112a0ffdbe03e6f5051504cb441c1e94cd)) * Add `preload_link_tag` helper. diff --git a/guides/source/6_0_release_notes.md b/guides/source/6_0_release_notes.md index e421ae1ac7..7c5478a03d 100644 --- a/guides/source/6_0_release_notes.md +++ b/guides/source/6_0_release_notes.md @@ -513,7 +513,7 @@ Please refer to the [Changelog][active-record] for detailed changes. ([Pull Request](https://github.com/rails/rails/pull/34742)) * Add the ability to disable scopes generated by `ActiveRecord.enum`. - ([Pull Request](https://github.com/rails/rails/pull/34605/files)) + ([Pull Request](https://github.com/rails/rails/pull/34605)) * Make implicit ordering configurable for a column. ([Pull Request](https://github.com/rails/rails/pull/34480)) @@ -672,6 +672,12 @@ Please refer to the [Changelog][active-storage] for detailed changes. is saved instead of immediately. ([Pull Request](https://github.com/rails/rails/pull/33303)) +* Optionally replace existing files instead of adding to them when assigning to + a collection of attachments (as in `@user.update!(images: [ … ])`). Use + `config.active_storage.replace_on_assign_to_many` to control this behavior. + ([Pull Request](https://github.com/rails/rails/pull/33303), + [Pull Request](https://github.com/rails/rails/pull/36716)) + * Add the ability to reflect on defined attachments using the existing Active Record reflection mechanism. ([Pull Request](https://github.com/rails/rails/pull/33018)) @@ -686,11 +692,7 @@ Please refer to the [Changelog][active-storage] for detailed changes. * Use the `image_processing` gem for Active Storage variants. This replaces using `mini_magick` directly. - ([Pull Request](https://github.com/rails/rails/pull/32471) - -* Replace existing images instead of adding to them when updating an - attached model via `update` or `update!` with, say, `@user.update!(images: [ … ])`. - ([Pull Request](https://github.com/rails/rails/pull/33303)) + ([Pull Request](https://github.com/rails/rails/pull/32471)) Active Model ------------ diff --git a/guides/source/action_text_overview.md b/guides/source/action_text_overview.md index 07919775e2..a735ec2b0e 100644 --- a/guides/source/action_text_overview.md +++ b/guides/source/action_text_overview.md @@ -46,6 +46,8 @@ happens after every keystroke, and avoids the need to use execCommand at all. ## Installation Run `rails action_text:install` to add the Yarn package and copy over the necessary migration. +Also, you need to set up Active Storage for embedded images and other attachments. +Please refer to the [Active Storage Overview](active_storage_overview.html) guide. ## Examples diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md index a1b69edd22..dda3ae0863 100644 --- a/guides/source/action_view_overview.md +++ b/guides/source/action_view_overview.md @@ -1025,6 +1025,34 @@ If `@article.author_id` is 1, this would return: <label for="article_author_id_3">M. Clark</label> ``` +Recovering some option passed (e.g. programatically checking an object from collection): + +```ruby +collection_radio_buttons(:article, :author_id, Author.all, :id, :name_with_initial, {checked: Author.last}) +``` + +In this case, the last object from the collection will be checked: + +```html +<input id="article_author_id_1" name="article[author_id]" type="radio" value="1" /> +<label for="article_author_id_1">D. Heinemeier Hansson</label> +<input id="article_author_id_2" name="article[author_id]" type="radio" value="2" /> +<label for="article_author_id_2">D. Thomas</label> +<input id="article_author_id_3" name="article[author_id]" type="radio" value="3" checked="checked" /> +<label for="article_author_id_3">M. Clark</label> +``` + +To access the passed options programatically (e.g. adding a custom class if checked): + +**Sample html.erb** + +```html+erb +<%= collection_radio_buttons(:article, :author_id, Author.all, :id, :name_with_initial, {checked: Author.last, required: true} do |rb| %> + <%= rb.label(class: "#{'my-custom-class' if rb.value == Author.last.id}") { rb.radio_button + rb.text } %> +<% end %> +``` + + #### collection_check_boxes Returns `check_box` tags for the collection of existing return values of `method` for `object`'s class. diff --git a/guides/source/active_record_multiple_databases.md b/guides/source/active_record_multiple_databases.md index e2c7878118..07be21a254 100644 --- a/guides/source/active_record_multiple_databases.md +++ b/guides/source/active_record_multiple_databases.md @@ -32,6 +32,7 @@ The following features are not (yet) supported: * Sharding * Joining across clusters * Load balancing replicas +* Dumping schema caches for multiple databases ## Setting up your application @@ -121,6 +122,12 @@ config.active_record.writing_role = :default config.active_record.reading_role = :readonly ``` +It's important to connect to your database in a single model and then inherit from that model +for the tables rather than connect multiple individual models to the same database. Database +clients have a limit to the number of open connections there can be and if you do this it will +multiply the number of connections you have since Rails uses the model class name for the +connection specification name. + Now that we have the database.yml and the new model set up it's time to create the databases. Rails 6.0 ships with all the rails tasks you need to use multiple databases in Rails. @@ -173,7 +180,7 @@ to primary based on the HTTP verb and whether there was a recent write. If the application is receiving a POST, PUT, DELETE, or PATCH request the application will automatically write to the primary. For the specified time after the write the application -will read from the replica. For a GET or HEAD request the application will read from the +will read from the primary. For a GET or HEAD request the application will read from the replica unless there was a recent write. To activate the automatic connection switching middleware, add or uncomment the following @@ -191,7 +198,7 @@ should change this based on your database infrastructure. Rails doesn't guarante a recent write" for other users within the delay window and will send GET and HEAD requests to the replicas unless they wrote recently. -The automatic connection switching in Rails is relatively primitive and deliberatly doesn't +The automatic connection switching in Rails is relatively primitive and deliberately doesn't do a whole lot. The goal was a system that demonstrated how to do automatic connection switching that was flexible enough to be customizable by app developers. @@ -210,7 +217,7 @@ And then pass it to the middleware: ```ruby config.active_record.database_selector = { delay: 2.seconds } config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver -config.active_record.database_resolver_context = MyCookieResovler +config.active_record.database_resolver_context = MyCookieResolver ``` ## Using manual connection switching @@ -247,23 +254,35 @@ The `database` argument for `connected_to` will take a symbol or a config hash. Note that `connected_to` with a role will look up an existing connection and switch using the connection specification name. This means that if you pass an unknown role -like `connected_to(role: :nonexistent)` you will get an error like that says +like `connected_to(role: :nonexistent)` you will get an error that says `ActiveRecord::ConnectionNotEstablished (No connection pool with 'AnimalsBase' found for the 'nonexistent' role.)` ## Caveats -As noted at the top Rails doesn't (yet) support sharding. We had to do a lot of work +### Sharding + +As noted at the top, Rails doesn't (yet) support sharding. We had to do a lot of work to support multiple databases for Rails 6.0. The lack of support for sharding isn't an oversight, but does require additional work that didn't make it in for 6.0. For now if you need sharding it may be advisable to continue using one of the many gems that supports this. +### Load Balancing Replicas + Rails also doesn't support automatic load balancing of replicas. This is very dependent on your infrastructure. We may implement basic, primitive load balancing in the future, but for an application at scale this should be something your application handles outside of Rails. -Lastly, you cannot join across databases. Rails 6.1 will support using `has_many` +### Joining Across Databases + +Applications cannot join across databases. Rails 6.1 will support using `has_many` relationships and creating 2 queries instead of joining, but Rails 6.0 will require you to split the joins into 2 selects manually. + +### Schema Cache + +If you use a schema cache and multiple databases you'll need to write an initializer +that loads the schema cache from your app. This wasn't an issue we could resolve in +time for Rails 6.0 but hope to have it in a future version soon. diff --git a/guides/source/active_storage_overview.md b/guides/source/active_storage_overview.md index 2986850cef..54f8f5c2b5 100644 --- a/guides/source/active_storage_overview.md +++ b/guides/source/active_storage_overview.md @@ -41,6 +41,10 @@ application (or upgrading your application to Rails 5.2), run `rails active_storage:install` to generate a migration that creates these tables. Use `rails db:migrate` to run the migration. +WARNING: `active_storage_attachments` is a polymorphic join table that stores your model's class name. If your model's class name changes, you will need to run a migration on this table to update the underlying `record_type` to your model's new class name. + +WARNING: If you are using UUIDs instead of integers as the primary key on your models you will need to change the column type of `record_id` for the `active_storage_attachments` table in the generated migration accordingly. + Declare Active Storage services in `config/storage.yml`. For each service your application uses, provide a name and the requisite configuration. The example below declares three services named `local`, `test`, and `amazon`: @@ -396,6 +400,10 @@ helper allows you to set the disposition. rails_blob_path(user.avatar, disposition: "attachment") ``` +WARNING: To prevent XSS attacks, ActiveStorage forces the Content-Disposition header +to "attachment" for some kind of files. To change this behaviour see the +available configuration opions in [Configuring Rails Applications](configuring.html#configuring-active-storage). + If you need to create a link from outside of controller/view context (Background jobs, Cronjobs, etc.), you can access the rails_blob_path like this: diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index 21901a7158..f36cacfe8d 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -155,15 +155,6 @@ Complex(1).duplicable? # => true 1.method(:+).duplicable? # => false ``` -`duplicable?` matches the current Ruby version's `dup` behavior, -so results will vary according the version of Ruby you're using. -In Ruby 2.4, for example, Complex and Rational are not duplicable: - -```ruby -Rational(1).duplicable? # => false -Complex(1).duplicable? # => false -``` - WARNING: Any class can disallow duplication by removing `dup` and `clone` or raising exceptions from them. Thus only `rescue` can tell whether a given arbitrary object is duplicable. `duplicable?` depends on the hard-coded list above, but it is much faster than `rescue`. Use it only if you know the hard-coded list is enough in your use case. NOTE: Defined in `active_support/core_ext/object/duplicable.rb`. @@ -2358,10 +2349,6 @@ There's also a related idiom that uses the splat operator: [*object] ``` -which in Ruby 1.8 returns `[nil]` for `nil`, and calls to `Array(object)` otherwise. (Please if you know the exact behavior in 1.9 contact fxn.) - -Thus, in this case the behavior is different for `nil`, and the differences with `Kernel#Array` explained above apply to the rest of `object`s. - NOTE: Defined in `active_support/core_ext/array/wrap.rb`. ### Duplicating @@ -3416,56 +3403,56 @@ NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. #### `prev_day`, `next_day` -In Ruby 1.9 `prev_day` and `next_day` return the date in the last or next day: +`prev_day` and `next_day` return the time in the last or next day: ```ruby -d = Date.new(2010, 5, 8) # => Sat, 08 May 2010 -d.prev_day # => Fri, 07 May 2010 -d.next_day # => Sun, 09 May 2010 +t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900 +t.prev_day # => 2010-05-07 00:00:00 +0900 +t.next_day # => 2010-05-09 00:00:00 +0900 ``` -NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +NOTE: Defined in `active_support/core_ext/time/calculations.rb`. #### `prev_month`, `next_month` -In Ruby 1.9 `prev_month` and `next_month` return the date with the same day in the last or next month: +`prev_month` and `next_month` return the time with the same day in the last or next month: ```ruby -d = Date.new(2010, 5, 8) # => Sat, 08 May 2010 -d.prev_month # => Thu, 08 Apr 2010 -d.next_month # => Tue, 08 Jun 2010 +t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900 +t.prev_month # => 2010-04-08 00:00:00 +0900 +t.next_month # => 2010-06-08 00:00:00 +0900 ``` If such a day does not exist, the last day of the corresponding month is returned: ```ruby -Date.new(2000, 5, 31).prev_month # => Sun, 30 Apr 2000 -Date.new(2000, 3, 31).prev_month # => Tue, 29 Feb 2000 -Date.new(2000, 5, 31).next_month # => Fri, 30 Jun 2000 -Date.new(2000, 1, 31).next_month # => Tue, 29 Feb 2000 +Time.new(2000, 5, 31).prev_month # => 2000-04-30 00:00:00 +0900 +Time.new(2000, 3, 31).prev_month # => 2000-02-29 00:00:00 +0900 +Time.new(2000, 5, 31).next_month # => 2000-06-30 00:00:00 +0900 +Time.new(2000, 1, 31).next_month # => 2000-02-29 00:00:00 +0900 ``` -NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +NOTE: Defined in `active_support/core_ext/time/calculations.rb`. #### `prev_year`, `next_year` -In Ruby 1.9 `prev_year` and `next_year` return a date with the same day/month in the last or next year: +`prev_year` and `next_year` return a time with the same day/month in the last or next year: ```ruby -d = Date.new(2010, 5, 8) # => Sat, 08 May 2010 -d.prev_year # => Fri, 08 May 2009 -d.next_year # => Sun, 08 May 2011 +t = Time.new(2010, 5, 8) # => 2010-05-08 00:00:00 +0900 +t.prev_year # => 2009-05-08 00:00:00 +0900 +t.next_year # => 2011-05-08 00:00:00 +0900 ``` If date is the 29th of February of a leap year, you obtain the 28th: ```ruby -d = Date.new(2000, 2, 29) # => Tue, 29 Feb 2000 -d.prev_year # => Sun, 28 Feb 1999 -d.next_year # => Wed, 28 Feb 2001 +t = Time.new(2000, 2, 29) # => 2000-02-29 00:00:00 +0900 +t.prev_year # => 1999-02-28 00:00:00 +0900 +t.next_year # => 2001-02-28 00:00:00 +0900 ``` -NOTE: Defined in `active_support/core_ext/date_and_time/calculations.rb`. +NOTE: Defined in `active_support/core_ext/time/calculations.rb`. #### `prev_quarter`, `next_quarter` diff --git a/guides/source/autoloading_and_reloading_constants.md b/guides/source/autoloading_and_reloading_constants.md index 7dfc39e192..8cd2d353de 100644 --- a/guides/source/autoloading_and_reloading_constants.md +++ b/guides/source/autoloading_and_reloading_constants.md @@ -1,18 +1,18 @@ **DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.** -Autoloading and Reloading Constants -=================================== +Autoloading and Reloading Constants (Zeitwerk Mode) +====================================================== -This guide documents how constant autoloading and reloading works. +This guide documents how autoloading and reloading works in `zeitwerk` mode. After reading this guide, you will know: -* Key aspects of Ruby constants -* What are the `autoload_paths` and how does eager loading work in production? -* How constant autoloading works -* What is `require_dependency` -* How constant reloading works -* Solutions to common autoloading gotchas +* Autoloading modes +* Related Rails configuration +* Project structure +* Autoloading, reloading, and eager loading +* Single Table Inheritance +* And more -------------------------------------------------------------------------------- @@ -20,13 +20,15 @@ After reading this guide, you will know: Introduction ------------ -Ruby on Rails allows applications to be written as if their code was preloaded. +INFO. This guide documents autoloading in `zeitwerk` mode, which is new in Rails 6. If you'd like to read about `classic` mode instead, please check [Autoloading and Reloading Constants (Classic Mode)](autoloading_and_reloading_constants_classic_mode.html). -In a normal Ruby program classes need to load their dependencies: +In a normal Ruby program, dependencies need to be loaded by hand. For example, the following controller uses classes `ApplicationController` and `Post`, and normally you'd need to put `require` calls for them: ```ruby -require 'application_controller' -require 'post' +# DO NOT DO THIS. +require "application_controller" +require "post" +# DO NOT DO THIS. class PostsController < ApplicationController def index @@ -35,16 +37,7 @@ class PostsController < ApplicationController end ``` -Our Rubyist instinct quickly sees some redundancy in there: If classes were -defined in files matching their name, couldn't their loading be automated -somehow? We could save scanning the file for dependencies, which is brittle. - -Moreover, `Kernel#require` loads files once, but development is much more smooth -if code gets refreshed when it changes without restarting the server. It would -be nice to be able to use `Kernel#load` in development, and `Kernel#require` in -production. - -Indeed, those features are provided by Ruby on Rails, where we just write +This is not the case in Rails applications, where application classes and modules are just available everywhere: ```ruby class PostsController < ApplicationController @@ -54,1330 +47,255 @@ class PostsController < ApplicationController end ``` -This guide documents how that works. - - -Constants Refresher -------------------- - -While constants are trivial in most programming languages, they are a rich -topic in Ruby. - -It is beyond the scope of this guide to document Ruby constants, but we are -nevertheless going to highlight a few key topics. Truly grasping the following -sections is instrumental to understanding constant autoloading and reloading. - -### Nesting - -Class and module definitions can be nested to create namespaces: - -```ruby -module XML - class SAXParser - # (1) - end -end -``` - -The *nesting* at any given place is the collection of enclosing nested class and -module objects outwards. The nesting at any given place can be inspected with -`Module.nesting`. For example, in the previous example, the nesting at -(1) is - -```ruby -[XML::SAXParser, XML] -``` - -It is important to understand that the nesting is composed of class and module -*objects*, it has nothing to do with the constants used to access them, and is -also unrelated to their names. - -For instance, while this definition is similar to the previous one: - -```ruby -class XML::SAXParser - # (2) -end -``` - -the nesting in (2) is different: - -```ruby -[XML::SAXParser] -``` - -`XML` does not belong to it. - -We can see in this example that the name of a class or module that belongs to a -certain nesting does not necessarily correlate with the namespaces at the spot. - -Even more, they are totally independent, take for instance - -```ruby -module X - module Y - end -end - -module A - module B - end -end - -module X::Y - module A::B - # (3) - end -end -``` - -The nesting in (3) consists of two module objects: - -```ruby -[A::B, X::Y] -``` - -So, it not only doesn't end in `A`, which does not even belong to the nesting, -but it also contains `X::Y`, which is independent from `A::B`. - -The nesting is an internal stack maintained by the interpreter, and it gets -modified according to these rules: - -* The class object following a `class` keyword gets pushed when its body is -executed, and popped after it. - -* The module object following a `module` keyword gets pushed when its body is -executed, and popped after it. - -* A singleton class opened with `class << object` gets pushed, and popped later. - -* When `instance_eval` is called using a string argument, -the singleton class of the receiver is pushed to the nesting of the eval'ed -code. When `class_eval` or `module_eval` is called using a string argument, -the receiver is pushed to the nesting of the eval'ed code. - -* The nesting at the top-level of code interpreted by `Kernel#load` is empty -unless the `load` call receives a true value as second argument, in which case -a newly created anonymous module is pushed by Ruby. - -It is interesting to observe that blocks do not modify the stack. In particular -the blocks that may be passed to `Class.new` and `Module.new` do not get the -class or module being defined pushed to their nesting. That's one of the -differences between defining classes and modules in one way or another. - -### Class and Module Definitions are Constant Assignments - -Let's suppose the following snippet creates a class (rather than reopening it): - -```ruby -class C -end -``` - -Ruby creates a constant `C` in `Object` and stores in that constant a class -object. The name of the class instance is "C", a string, named after the -constant. +Idiomatic Rails applications only issue `require` calls to load stuff from their `lib` directory, the Ruby standard library, Ruby gems, etc. That is, anything that does not belong to their autoload paths, explained below. -That is, -```ruby -class Project < ApplicationRecord -end -``` +Enabling Zeitwerk Mode +---------------------- -performs a constant assignment equivalent to +The autoloading `zeitwerk` mode is enabled by default in Rails 6 applications running on CRuby: ```ruby -Project = Class.new(ApplicationRecord) +# config/application.rb +config.load_defaults "6.x" # enables zeitwerk mode in CRuby ``` -including setting the name of the class as a side-effect: +In `zeitwerk` mode, Rails uses [Zeitwerk](https://github.com/fxn/zeitwerk) internally to autoload, reload, and eager load. Rails instantiates and configures a dedicated Zeitwerk instance that manages the project. -```ruby -Project.name # => "Project" -``` +INFO. You do not configure Zeitwerk manually in a Rails application. Rather, you configure the application using the portable configuration points explained in this guide, and Rails translates that to Zeitwerk on your behalf. -Constant assignment has a special rule to make that happen: if the object -being assigned is an anonymous class or module, Ruby sets the object's name to -the name of the constant. +Project Structure +----------------- -INFO. From then on, what happens to the constant and the instance does not -matter. For example, the constant could be deleted, the class object could be -assigned to a different constant, be stored in no constant anymore, etc. Once -the name is set, it doesn't change. +In a Rails application file names have to match the constants they define, with directories acting as namespaces. -Similarly, module creation using the `module` keyword as in +For example, the file `app/helpers/users_helper.rb` should define `UsersHelper` and the file `app/controllers/admin/payments_controller.rb` should define `Admin::PaymentsController`. -```ruby -module Admin -end -``` - -performs a constant assignment equivalent to +Rails configures Zeitwerk to inflect file names with `String#camelize`. For example, it expects that `app/controllers/users_controller.rb` defines the constant `UsersController` because ```ruby -Admin = Module.new +"users_controller".camelize # => UsersController ``` -including setting the name as a side-effect: +If you need to customize any of these inflections, for example to add an acronym, please have a look at `config/initializers/inflections.rb`. -```ruby -Admin.name # => "Admin" -``` +Please, check the [Zeitwerk documentation](https://github.com/fxn/zeitwerk#file-structure) for further details. -WARNING. The execution context of a block passed to `Class.new` or `Module.new` -is not entirely equivalent to the one of the body of the definitions using the -`class` and `module` keywords. But both idioms result in the same constant -assignment. - -Thus, an informal expression like "the `String` class" technically means the -class object stored in the constant called "String". That constant, in turn, -belongs to the class object stored in the constant called "Object". - -`String` is an ordinary constant, and everything related to them such as -resolution algorithms applies to it. - -Likewise, in the controller - -```ruby -class PostsController < ApplicationController - def index - @posts = Post.all - end -end -``` - -`Post` is not syntax for a class. Rather, `Post` is a regular Ruby constant. If -all is good, the constant is evaluated to an object that responds to `all`. +Autoload paths +-------------- -That is why we talk about *constant* autoloading, Rails has the ability to -load constants on the fly. +We call _autoload paths_ to the list of application directories whose contents are to be autoloaded. For example, `app/models`. Such directories represent the root namespace: `Object`. -### Constants are Stored in Modules +INFO. Autoload paths are called _root directories_ in Zeitwerk documentation, but we'll stay with "autoload path" in this guide. -Constants belong to modules in a very literal sense. Classes and modules have -a constant table; think of it as a hash table. +Within an autoload path, file names must match the constants they define as documented [here](https://github.com/fxn/zeitwerk#file-structure). -Let's analyze an example to really understand what that means. While common -abuses of language like "the `String` class" are convenient, the exposition is -going to be precise here for didactic purposes. +By default, the autoload paths of an application consist of all the subdirectories of `app` that exist when the application boots ---except for `aasets`, `javascripts`, `views`,--- plus the autoload paths of engines it might depend on. -Let's consider the following module definition: +For example, if `UsersHelper` is implemented in `app/helpers/users_helper.rb`, the module is autoloadable, you do not need (and should not write) a `require` call for it: -```ruby -module Colors - RED = '0xff0000' -end ``` - -First, when the `module` keyword is processed, the interpreter creates a new -entry in the constant table of the class object stored in the `Object` constant. -Said entry associates the name "Colors" to a newly created module object. -Furthermore, the interpreter sets the name of the new module object to be the -string "Colors". - -Later, when the body of the module definition is interpreted, a new entry is -created in the constant table of the module object stored in the `Colors` -constant. That entry maps the name "RED" to the string "0xff0000". - -In particular, `Colors::RED` is totally unrelated to any other `RED` constant -that may live in any other class or module object. If there were any, they -would have separate entries in their respective constant tables. - -Pay special attention in the previous paragraphs to the distinction between -class and module objects, constant names, and value objects associated to them -in constant tables. - -### Resolution Algorithms - -#### Resolution Algorithm for Relative Constants - -At any given place in the code, let's define *cref* to be the first element of -the nesting if it is not empty, or `Object` otherwise. - -Without getting too much into the details, the resolution algorithm for relative -constant references goes like this: - -1. If the nesting is not empty the constant is looked up in its elements and in -order. The ancestors of those elements are ignored. - -2. If not found, then the algorithm walks up the ancestor chain of the cref. - -3. If not found and the cref is a module, the constant is looked up in `Object`. - -4. If not found, `const_missing` is invoked on the cref. The default -implementation of `const_missing` raises `NameError`, but it can be overridden. - -Rails autoloading **does not emulate this algorithm**, but its starting point is -the name of the constant to be autoloaded, and the cref. See more in [Relative -References](#autoloading-algorithms-relative-references). - -#### Resolution Algorithm for Qualified Constants - -Qualified constants look like this: - -```ruby -Billing::Invoice +$ bin/rails runner 'p UsersHelper' +UsersHelper ``` -`Billing::Invoice` is composed of two constants: `Billing` is relative and is -resolved using the algorithm of the previous section. - -INFO. Leading colons would make the first segment absolute rather than -relative: `::Billing::Invoice`. That would force `Billing` to be looked up -only as a top-level constant. - -`Invoice` on the other hand is qualified by `Billing` and we are going to see -its resolution next. Let's define *parent* to be that qualifying class or module -object, that is, `Billing` in the example above. The algorithm for qualified -constants goes like this: - -1. The constant is looked up in the parent and its ancestors. In Ruby >= 2.5, -`Object` is skipped if present among the ancestors. `Kernel` and `BasicObject` -are still checked though. +Autoload paths automatically pick any custom directories under `app`. For example, if your application has `app/presenters`, or `app/services`, etc., they are added to autoload paths. -2. If the lookup fails, `const_missing` is invoked in the parent. The default -implementation of `const_missing` raises `NameError`, but it can be overridden. +The array of autoload paths can be extended by mutating `config.autoload_paths`, in `config/application.rb`, but nowadays this is discouraged. -INFO. In Ruby < 2.5 `String::Hash` evaluates to `Hash` and the interpreter -issues a warning: "toplevel constant Hash referenced by String::Hash". Starting -with 2.5, `String::Hash` raises `NameError` because `Object` is skipped. +WARNING. Please, do not mutate `ActiveSupport::Dependencies.autoload_paths`, the public interface to change autoload paths is `config.autoload_paths`. -As you see, this algorithm is simpler than the one for relative constants. In -particular, the nesting plays no role here, and modules are not special-cased, -if neither they nor their ancestors have the constants, `Object` is **not** -checked. -Rails autoloading **does not emulate this algorithm**, but its starting point is -the name of the constant to be autoloaded, and the parent. See more in -[Qualified References](#autoloading-algorithms-qualified-references). - - -Vocabulary +$LOAD_PATH ---------- -### Parent Namespaces - -Given a string with a constant path we define its *parent namespace* to be the -string that results from removing its rightmost segment. - -For example, the parent namespace of the string "A::B::C" is the string "A::B", -the parent namespace of "A::B" is "A", and the parent namespace of "A" is "". - -The interpretation of a parent namespace when thinking about classes and modules -is tricky though. Let's consider a module M named "A::B": - -* The parent namespace, "A", may not reflect nesting at a given spot. - -* The constant `A` may no longer exist, some code could have removed it from -`Object`. - -* If `A` exists, the class or module that was originally in `A` may not be there -anymore. For example, if after a constant removal there was another constant -assignment there would generally be a different object in there. - -* In such case, it could even happen that the reassigned `A` held a new class or -module called also "A"! - -* In the previous scenarios M would no longer be reachable through `A::B` but -the module object itself could still be alive somewhere and its name would -still be "A::B". - -The idea of a parent namespace is at the core of the autoloading algorithms -and helps explain and understand their motivation intuitively, but as you see -that metaphor leaks easily. Given an edge case to reason about, take always into -account that by "parent namespace" the guide means exactly that specific string -derivation. - -### Loading Mechanism - -Rails autoloads files with `Kernel#load` when `config.cache_classes` is false, -the default in development mode, and with `Kernel#require` otherwise, the -default in production mode. - -`Kernel#load` allows Rails to execute files more than once if [constant -reloading](#constant-reloading) is enabled. - -This guide uses the word "load" freely to mean a given file is interpreted, but -the actual mechanism can be `Kernel#load` or `Kernel#require` depending on that -flag. - - -Autoloading Availability ------------------------- - -Rails is always able to autoload provided its environment is in place. For -example the `runner` command autoloads: - -``` -$ rails runner 'p User.column_names' -["id", "email", "created_at", "updated_at"] -``` - -The console autoloads, the test suite autoloads, and of course the application -autoloads. - -By default, Rails eager loads the application files when it boots in production -mode, so most of the autoloading going on in development does not happen. But -autoloading may still be triggered during eager loading. - -For example, given - -```ruby -class BeachHouse < House -end -``` - -if `House` is still unknown when `app/models/beach_house.rb` is being eager -loaded, Rails autoloads it. - - -autoload_paths and eager_load_paths ------------------------------------ - -As you probably know, when `require` gets a relative file name: +Autoload paths are added to `$LOAD_PATH` by default. However, Zeitwerk uses absolute file names internally, and your application should not issue `require` calls for autoloadable files, so those directories are actually not needed there. You can opt-out with this flag: ```ruby -require 'erb' +config.add_autoload_paths_to_load_path = false ``` -Ruby looks for the file in the directories listed in `$LOAD_PATH`. That is, Ruby -iterates over all its directories and for each one of them checks whether they -have a file called "erb.rb", or "erb.so", or "erb.o", or "erb.dll". If it finds -any of them, the interpreter loads it and ends the search. Otherwise, it tries -again in the next directory of the list. If the list gets exhausted, `LoadError` -is raised. - -We are going to cover how constant autoloading works in more detail later, but -the idea is that when a constant like `Post` is hit and missing, if there's a -`post.rb` file for example in `app/models` Rails is going to find it, evaluate -it, and have `Post` defined as a side-effect. - -All right, Rails has a collection of directories similar to `$LOAD_PATH` in which -to look up `post.rb`. That collection is called `autoload_paths` and by -default it contains: - -* All subdirectories of `app` in the application and engines present at boot - time. For example, `app/controllers`. They do not need to be the default - ones, any custom directories like `app/workers` belong automatically to - `autoload_paths`. +That may speed legit `require` calls a bit, since there are less lookups. Also, if your application uses [Bootsnap](https://github.com/Shopify/bootsnap), that saves the library from building unnecessary indexes, and saves the RAM they would need. -* Any existing second level directories called `app/*/concerns` in the - application and engines. -* The directory `test/mailers/previews`. +Reloading +--------- -`eager_load_paths` is initially the `app` paths above +Rails automatically reloads classes and modules if application files change. -How files are autoloaded depends on `eager_load` and `cache_classes` config settings which typically vary in development, production, and test modes: +More precisely, if the web server is running and application files have been modified, Rails unloads all autoloaded constants just before the next request is processed. That way, application classes or modules used during that request are going to be autoloaded, thus picking up their current implementation in the file system. - * In **development**, you want quicker startup with incremental loading of application code. So `eager_load` should be set to `false`, and Rails will autoload files as needed (see [Autoloading Algorithms](#autoloading-algorithms) below) -- and then reload them when they change (see [Constant Reloading](#constant-reloading) below). - * In **production**, however, you want consistency and thread-safety and can live with a longer boot time. So `eager_load` is set to `true`, and then during boot (before the app is ready to receive requests) Rails loads all files in the `eager_load_paths` and then turns off auto loading (NB: autoloading may be needed during eager loading). Not autoloading after boot is a `good thing`, as autoloading can cause the app to be have thread-safety problems. - * In **test**, for speed of execution (of individual tests) `eager_load` is `false`, so Rails follows development behaviour. +Reloading can be enabled or disabled. The setting that controls this behavior is `config.cache_classes`, which is false by default in `development` mode (reloading enabled), and true by default in `production` mode (reloading disabled). -What is described above are the defaults with a newly generated Rails app. There are multiple ways this can be configured differently (see [Configuring Rails Applications](configuring.html#rails-general-configuration). -). But using `autoload_paths` on its own in the past (before Rails 5) developers might configure `autoload_paths` to add in extra locations (e.g. `lib` which used to be an autoload path list years ago, but no longer is). However this is now discouraged for most purposes, as it is likely to lead to production-only errors. It is possible to add new locations to both `config.eager_load_paths` and `config.autoload_paths` but use at your own risk. +Rails detects files have changed using an evented file monitor (default), or walking the autoload paths, depending on `config.file_watcher`. -See also [Autoloading in the Test Environment](#autoloading-in-the-test-environment). +In a Rails console there is no file watcher active regardless of the value of `config.cache_classes`. This is so because, normally, it would be confusing to have code reloaded in the middle of a console session, the same way you generally want an individual request to be served by a consistent, non-changing set of application classes and modules. -`config.autoload_paths` is not changeable from environment-specific configuration files. - -The value of `autoload_paths` can be inspected. In a just-generated application -it is (edited): +However, you can force a reload in the console executing `reload!`: ``` -$ rails r 'puts ActiveSupport::Dependencies.autoload_paths' -.../app/assets -.../app/channels -.../app/controllers -.../app/controllers/concerns -.../app/helpers -.../app/jobs -.../app/mailers -.../app/models -.../app/models/concerns -.../activestorage/app/assets -.../activestorage/app/controllers -.../activestorage/app/javascript -.../activestorage/app/jobs -.../activestorage/app/models -.../actioncable/app/assets -.../actionview/app/assets -.../test/mailers/previews +$ bin/rails c +Loading development environment (Rails 6.0.0) +irb(main):001:0> User.object_id +=> 70136277390120 +irb(main):002:0> reload! +Reloading... +=> true +irb(main):003:0> User.object_id +=> 70136284426020 ``` -INFO. `autoload_paths` is computed and cached during the initialization process. -The application needs to be restarted to reflect any changes in the directory -structure. +as you can see, the class object stored in the `User` constant is different after reloading. +### Reloading and Stale Objects -Autoloading Algorithms ----------------------- +It is very important to understand that Ruby does not have a way to truly reload classes and modules in memory, and have that reflected everywhere they are already used. Technically, "unloading" the `User` class means removing the `User` constant via `Object.send(:remove_const, "User")`. -### Relative References +Therefore, if you store a reloadable class or module object in a place that is not reloaded, that value is going to become stale. -A relative constant reference may appear in several places, for example, in +For example, if an initializer stores and caches a certain class object ```ruby -class PostsController < ApplicationController - def index - @posts = Post.all - end -end +# config/initializers/configure_payment_gateway.rb +# DO NOT DO THIS. +$PAYMENT_GATEWAY = Rails.env.production? ? RealGateway : MockedGateway +# DO NOT DO THIS. ``` -all three constant references are relative. - -#### Constants after the `class` and `module` Keywords - -Ruby performs a lookup for the constant that follows a `class` or `module` -keyword because it needs to know if the class or module is going to be created -or reopened. - -If the constant is not defined at that point it is not considered to be a -missing constant, autoloading is **not** triggered. - -So, in the previous example, if `PostsController` is not defined when the file -is interpreted Rails autoloading is not going to be triggered, Ruby will just -define the controller. - -#### Top-Level Constants - -On the contrary, if `ApplicationController` is unknown, the constant is -considered missing and an autoload is going to be attempted by Rails. - -In order to load `ApplicationController`, Rails iterates over `autoload_paths`. -First it checks if `app/assets/application_controller.rb` exists. If it does not, -which is normally the case, it continues and finds -`app/controllers/application_controller.rb`. +and `MockedGateway` gets reloaded, `$PAYMENT_GATEWAY` still stores the class object `MockedGateway` evaluated to when the initializer ran. Reloading does not change the class object stored in `$PAYMENT_GATEWAY`. -If the file defines the constant `ApplicationController` all is fine, otherwise -`LoadError` is raised: +Similarly, in the Rails console, if you have a user instance and reload: ``` -unable to autoload constant ApplicationController, expected -<full path to application_controller.rb> to define it (LoadError) +> user = User.new +> reload! ``` -INFO. Rails does not require the value of autoloaded constants to be a class or -module object. For example, if the file `app/models/max_clients.rb` defines -`MAX_CLIENTS = 100` autoloading `MAX_CLIENTS` works just fine. - -#### Namespaces +the `user` object is instance of a stale class object. Ruby gives you a new class if you evaluate `User` again, but does not update the class `user` is instance of. -Autoloading `ApplicationController` looks directly under the directories of -`autoload_paths` because the nesting in that spot is empty. The situation of -`Post` is different, the nesting in that line is `[PostsController]` and support -for namespaces comes into play. - -The basic idea is that given +Another use case of this gotcha is subclassing reloadable classes in a place that is not reloaded: ```ruby -module Admin - class BaseController < ApplicationController - @@all_roles = Role.all - end +# lib/vip_user.rb +class VipUser < User end ``` -to autoload `Role` we are going to check if it is defined in the current or -parent namespaces, one at a time. So, conceptually we want to try to autoload -any of - -``` -Admin::BaseController::Role -Admin::Role -Role -``` - -in that order. That's the idea. To do so, Rails looks in `autoload_paths` -respectively for file names like these: - -``` -admin/base_controller/role.rb -admin/role.rb -role.rb -``` - -modulus some additional directory lookups we are going to cover soon. - -INFO. `'Constant::Name'.underscore` gives the relative path without extension of -the file name where `Constant::Name` is expected to be defined. - -Let's see how Rails autoloads the `Post` constant in the `PostsController` -above assuming the application has a `Post` model defined in -`app/models/post.rb`. - -First it checks for `posts_controller/post.rb` in `autoload_paths`: - -``` -app/assets/posts_controller/post.rb -app/controllers/posts_controller/post.rb -app/helpers/posts_controller/post.rb -... -test/mailers/previews/posts_controller/post.rb -``` - -Since the lookup is exhausted without success, a similar search for a directory -is performed, we are going to see why in the [next section](#automatic-modules): +if `User` is reloaded, since `VipUser` is not, the superclass of `VipUser` is the original stale class object. -``` -app/assets/posts_controller/post -app/controllers/posts_controller/post -app/helpers/posts_controller/post -... -test/mailers/previews/posts_controller/post -``` +Bottom line: **do not cache reloadable classes or modules**. -If all those attempts fail, then Rails starts the lookup again in the parent -namespace. In this case only the top-level remains: -``` -app/assets/post.rb -app/controllers/post.rb -app/helpers/post.rb -app/mailers/post.rb -app/models/post.rb -``` +Eager Loading +------------- -A matching file is found in `app/models/post.rb`. The lookup stops there and the -file is loaded. If the file actually defines `Post` all is fine, otherwise -`LoadError` is raised. +In production-like environments it is generally better to load all the application code when the application boots. Eager loading puts everything in memory ready to serve requests right away, and it is also [CoW](https://en.wikipedia.org/wiki/Copy-on-write)-friendly. -### Qualified References +Eager loading is controlled by the flag `config.eager_load`, which is enabled by default in `production` mode. -When a qualified constant is missing Rails does not look for it in the parent -namespaces. But there is a caveat: when a constant is missing, Rails is -unable to tell if the trigger was a relative reference or a qualified one. +The order in which files are eager loaded is undefined. -For example, consider +if the `Zeitwerk` constant is defined, Rails invokes `Zeitwerk::Loader.eager_load_all` regardless of the application autoloading mode. That ensures dependencies managed by Zeitwerk are eager loaded. -```ruby -module Admin - User -end -``` -and - -```ruby -Admin::User -``` - -If `User` is missing, in either case all Rails knows is that a constant called -"User" was missing in a module called "Admin". +Single Table Inheritance +------------------------ -If there is a top-level `User` Ruby would resolve it in the former example, but -wouldn't in the latter. In general, Rails does not emulate the Ruby constant -resolution algorithms, but in this case it tries using the following heuristic: +Single Table Inheritance is a feature that doesn't play well with lazy loading. Reason is, its API generally needs to be able to enumerate the STI hierarchy to work correctly, whereas lazy loading defers loading classes until they are referenced. You can't enumerate what you haven't referenced yet. -> If none of the parent namespaces of the class or module has the missing -> constant then Rails assumes the reference is relative. Otherwise qualified. +In a sense, applications need to eager load STI hierarchies regardless of the loading mode. -For example, if this code triggers autoloading +Of course, if the application eager loads on boot, that is already accomplished. When it does not, it is in practice enough to instantiate the existing types in the database, which in development or test modes is usually fine. One way to do that is to throw this module into the `lib` directory: ```ruby -Admin::User -``` - -and the `User` constant is already present in `Object`, it is not possible that -the situation is - -```ruby -module Admin - User -end -``` - -because otherwise Ruby would have resolved `User` and no autoloading would have -been triggered in the first place. Thus, Rails assumes a qualified reference and -considers the file `admin/user.rb` and directory `admin/user` to be the only -valid options. - -In practice, this works quite well as long as the nesting matches all parent -namespaces respectively and the constants that make the rule apply are known at -that time. - -However, autoloading happens on demand. If by chance the top-level `User` was -not yet loaded, then Rails assumes a relative reference by contract. - -Naming conflicts of this kind are rare in practice, but if one occurs, -`require_dependency` provides a solution by ensuring that the constant needed -to trigger the heuristic is defined in the conflicting place. - -### Automatic Modules - -When a module acts as a namespace, Rails does not require the application to -define a file for it, a directory matching the namespace is enough. +module StiPreload + unless Rails.application.config.eager_load + extend ActiveSupport::Concern -Suppose an application has a back office whose controllers are stored in -`app/controllers/admin`. If the `Admin` module is not yet loaded when -`Admin::UsersController` is hit, Rails needs first to autoload the constant -`Admin`. - -If `autoload_paths` has a file called `admin.rb` Rails is going to load that -one, but if there's no such file and a directory called `admin` is found, Rails -creates an empty module and assigns it to the `Admin` constant on the fly. - -### Generic Procedure - -Relative references are reported to be missing in the cref where they were hit, -and qualified references are reported to be missing in their parent (see -[Resolution Algorithm for Relative -Constants](#resolution-algorithm-for-relative-constants) at the beginning of -this guide for the definition of *cref*, and [Resolution Algorithm for Qualified -Constants](#resolution-algorithm-for-qualified-constants) for the definition of -*parent*). - -The procedure to autoload constant `C` in an arbitrary situation is as follows: - -``` -if the class or module in which C is missing is Object - let ns = '' -else - let M = the class or module in which C is missing - - if M is anonymous - let ns = '' - else - let ns = M.name - end -end - -loop do - # Look for a regular file. - for dir in autoload_paths - if the file "#{dir}/#{ns.underscore}/c.rb" exists - load/require "#{dir}/#{ns.underscore}/c.rb" - - if C is now defined - return - else - raise LoadError - end + included do + cattr_accessor :preloaded, instance_accessor: false end - end - # Look for an automatic module. - for dir in autoload_paths - if the directory "#{dir}/#{ns.underscore}/c" exists - if ns is an empty string - let C = Module.new in Object and return - else - let C = Module.new in ns.constantize and return + class_methods do + def descendants + preload_sti unless preloaded + super end - end - end - - if ns is empty - # We reached the top-level without finding the constant. - raise NameError - else - if C exists in any of the parent namespaces - # Qualified constants heuristic. - raise NameError - else - # Try again in the parent namespace. - let ns = the parent namespace of ns and retry - end - end -end -``` - - -require_dependency ------------------- - -Constant autoloading is triggered on demand and therefore code that uses a -certain constant may have it already defined or may trigger an autoload. That -depends on the execution path and it may vary between runs. - -There are times, however, in which you want to make sure a certain constant is -known when the execution reaches some code. `require_dependency` provides a way -to load a file using the current [loading mechanism](#loading-mechanism), and -keeping track of constants defined in that file as if they were autoloaded to -have them reloaded as needed. - -`require_dependency` is rarely needed, but see a couple of use cases in -[Autoloading and STI](#autoloading-and-sti) and [When Constants aren't -Triggered](#when-constants-aren-t-missed). - -WARNING. Unlike autoloading, `require_dependency` does not expect the file to -define any particular constant. Exploiting this behavior would be a bad practice -though, file and constant paths should match. - - -Constant Reloading ------------------- - -When `config.cache_classes` is false Rails is able to reload autoloaded -constants. -For example, if you're in a console session and edit some file behind the -scenes, the code can be reloaded with the `reload!` command: - -``` -> reload! -``` - -When the application runs, code is reloaded when something relevant to this -logic changes. In order to do that, Rails monitors a number of things: - -* `config/routes.rb`. - -* Locales. - -* Ruby files under `autoload_paths`. - -* `db/schema.rb` and `db/structure.sql`. - -If anything in there changes, there is a middleware that detects it and reloads -the code. - -Autoloading keeps track of autoloaded constants. Reloading is implemented by -removing them all from their respective classes and modules using -`Module#remove_const`. That way, when the code goes on, those constants are -going to be unknown again, and files reloaded on demand. - -INFO. This is an all-or-nothing operation, Rails does not attempt to reload only -what changed since dependencies between classes makes that really tricky. -Instead, everything is wiped. - - -Module#autoload isn't Involved ------------------------------- - -`Module#autoload` provides a lazy way to load constants that is fully integrated -with the Ruby constant lookup algorithms, dynamic constant API, etc. It is quite -transparent. - -Rails internals make extensive use of it to defer as much work as possible from -the boot process. But constant autoloading in Rails is **not** implemented with -`Module#autoload`. - -One possible implementation based on `Module#autoload` would be to walk the -application tree and issue `autoload` calls that map existing file names to -their conventional constant name. - -There are a number of reasons that prevent Rails from using that implementation. - -For example, `Module#autoload` is only capable of loading files using `require`, -so reloading would not be possible. Not only that, it uses an internal `require` -which is not `Kernel#require`. - -Then, it provides no way to remove declarations in case a file is deleted. If a -constant gets removed with `Module#remove_const` its `autoload` is not triggered -again. Also, it doesn't support qualified names, so files with namespaces should -be interpreted during the walk tree to install their own `autoload` calls, but -those files could have constant references not yet configured. - -An implementation based on `Module#autoload` would be awesome but, as you see, -at least as of today it is not possible. Constant autoloading in Rails is -implemented with `Module#const_missing`, and that's why it has its own contract, -documented in this guide. - - -Common Gotchas --------------- - -### Nesting and Qualified Constants - -Let's consider - -```ruby -module Admin - class UsersController < ApplicationController - def index - @users = User.all + # Constantizes all types present in the database. There might be more on + # disk, but that does not matter in practice as far as the STI API is + # concerned. + # + # Assumes store_full_sti_class is true, the default. + def preload_sti + types_in_db = \ + base_class. + select(inheritance_column). + distinct. + pluck(inheritance_column). + compact. + each(&:constantize) + + types_in_db.each do |type| + logger.debug("Preloading STI type #{type}") + type.constantize + end + + self.preloaded = true + end end end end ``` -and +and then include it in the STI root classes of your project: ```ruby -class Admin::UsersController < ApplicationController - def index - @users = User.all - end -end -``` - -To resolve `User` Ruby checks `Admin` in the former case, but it does not in -the latter because it does not belong to the nesting (see [Nesting](#nesting) -and [Resolution Algorithms](#resolution-algorithms)). - -Unfortunately Rails autoloading does not know the nesting in the spot where the -constant was missing and so it is not able to act as Ruby would. In particular, -`Admin::User` will get autoloaded in either case. - -Albeit qualified constants with `class` and `module` keywords may technically -work with autoloading in some cases, it is preferable to use relative constants -instead: +# app/models/shape.rb +require "sti_preload" -```ruby -module Admin - class UsersController < ApplicationController - def index - @users = User.all - end - end +class Shape < ApplicationRecord + include StiPreload # Only in the root class. end -``` -### Autoloading and STI - -Single Table Inheritance (STI) is a feature of Active Record that enables -storing a hierarchy of models in one single table. The API of such models is -aware of the hierarchy and encapsulates some common needs. For example, given -these classes: - -```ruby # app/models/polygon.rb -class Polygon < ApplicationRecord +class Polygon < Shape end # app/models/triangle.rb class Triangle < Polygon end - -# app/models/rectangle.rb -class Rectangle < Polygon -end -``` - -`Triangle.create` creates a row that represents a triangle, and -`Rectangle.create` creates a row that represents a rectangle. If `id` is the -ID of an existing record, `Polygon.find(id)` returns an object of the correct -type. - -Methods that operate on collections are also aware of the hierarchy. For -example, `Polygon.all` returns all the records of the table, because all -rectangles and triangles are polygons. Active Record takes care of returning -instances of their corresponding class in the result set. - -Types are autoloaded as needed. For example, if `Polygon.first` is a rectangle -and `Rectangle` has not yet been loaded, Active Record autoloads it and the -record is correctly instantiated. - -All good, but if instead of performing queries based on the root class we need -to work on some subclass, things get interesting. - -While working with `Polygon` you do not need to be aware of all its descendants, -because anything in the table is by definition a polygon, but when working with -subclasses Active Record needs to be able to enumerate the types it is looking -for. Let's see an example. - -`Rectangle.all` only loads rectangles by adding a type constraint to the query: - -```sql -SELECT "polygons".* FROM "polygons" -WHERE "polygons"."type" IN ("Rectangle") -``` - -Let's introduce now a subclass of `Rectangle`: - -```ruby -# app/models/square.rb -class Square < Rectangle -end -``` - -`Rectangle.all` should now return rectangles **and** squares: - -```sql -SELECT "polygons".* FROM "polygons" -WHERE "polygons"."type" IN ("Rectangle", "Square") -``` - -But there's a caveat here: How does Active Record know that the class `Square` -exists at all? - -Even if the file `app/models/square.rb` exists and defines the `Square` class, -if no code yet used that class, `Rectangle.all` issues the query - -```sql -SELECT "polygons".* FROM "polygons" -WHERE "polygons"."type" IN ("Rectangle") -``` - -That is not a bug, the query includes all *known* descendants of `Rectangle`. - -A way to ensure this works correctly regardless of the order of execution is to -manually load the direct subclasses at the bottom of the file that defines each -intermediate class: - -```ruby -# app/models/rectangle.rb -class Rectangle < Polygon -end -require_dependency 'square' -``` - -This needs to happen for every intermediate (non-root and non-leaf) class. The -root class does not scope the query by type, and therefore does not necessarily -have to know all its descendants. - -### Autoloading and `require` - -Files defining constants to be autoloaded should never be `require`d: - -```ruby -require 'user' # DO NOT DO THIS - -class UsersController < ApplicationController - ... -end -``` - -There are two possible gotchas here in development mode: - -1. If `User` is autoloaded before reaching the `require`, `app/models/user.rb` -runs again because `load` does not update `$LOADED_FEATURES`. - -2. If the `require` runs first Rails does not mark `User` as an autoloaded -constant and changes to `app/models/user.rb` aren't reloaded. - -Just follow the flow and use constant autoloading always, never mix -autoloading and `require`. As a last resort, if some file absolutely needs to -load a certain file use `require_dependency` to play nice with constant -autoloading. This option is rarely needed in practice, though. - -Of course, using `require` in autoloaded files to load ordinary 3rd party -libraries is fine, and Rails is able to distinguish their constants, they are -not marked as autoloaded. - -### Autoloading and Initializers - -Consider this assignment in `config/initializers/set_auth_service.rb`: - -```ruby -AUTH_SERVICE = if Rails.env.production? - RealAuthService -else - MockedAuthService -end -``` - -The purpose of this setup would be that the application uses the class that -corresponds to the environment via `AUTH_SERVICE`. In development mode -`MockedAuthService` gets autoloaded when the initializer runs. Let's suppose -we do some requests, change its implementation, and hit the application again. -To our surprise the changes are not reflected. Why? - -As [we saw earlier](#constant-reloading), Rails removes autoloaded constants, -but `AUTH_SERVICE` stores the original class object. Stale, non-reachable -using the original constant, but perfectly functional. - -The following code summarizes the situation: - -```ruby -class C - def quack - 'quack!' - end -end - -X = C -Object.instance_eval { remove_const(:C) } -X.new.quack # => quack! -X.name # => C -C # => uninitialized constant C (NameError) -``` - -Because of that, it is not a good idea to autoload constants on application -initialization. - -In the case above we could implement a dynamic access point: - -```ruby -# app/models/auth_service.rb -class AuthService - if Rails.env.production? - def self.instance - RealAuthService - end - else - def self.instance - MockedAuthService - end - end -end -``` - -and have the application use `AuthService.instance` instead. `AuthService` -would be loaded on demand and be autoload-friendly. - -### `require_dependency` and Initializers - -As we saw before, `require_dependency` loads files in an autoloading-friendly -way. Normally, though, such a call does not make sense in an initializer. - -One could think about doing some [`require_dependency`](#require-dependency) -calls in an initializer to make sure certain constants are loaded upfront, for -example as an attempt to address the [gotcha with STIs](#autoloading-and-sti). - -Problem is, in development mode [autoloaded constants are wiped](#constant-reloading) -if there is any relevant change in the file system. If that happens then -we are in the very same situation the initializer wanted to avoid! - -Calls to `require_dependency` have to be strategically written in autoloaded -spots. - -### When Constants aren't Missed - -#### Relative References - -Let's consider a flight simulator. The application has a default flight model - -```ruby -# app/models/flight_model.rb -class FlightModel -end -``` - -that can be overridden by each airplane, for instance - -```ruby -# app/models/bell_x1/flight_model.rb -module BellX1 - class FlightModel < FlightModel - end -end - -# app/models/bell_x1/aircraft.rb -module BellX1 - class Aircraft - def initialize - @flight_model = FlightModel.new - end - end -end -``` - -The initializer wants to create a `BellX1::FlightModel` and nesting has -`BellX1`, that looks good. But if the default flight model is loaded and the -one for the Bell-X1 is not, the interpreter is able to resolve the top-level -`FlightModel` and autoloading is thus not triggered for `BellX1::FlightModel`. - -That code depends on the execution path. - -These kind of ambiguities can often be resolved using qualified constants: - -```ruby -module BellX1 - class Plane - def flight_model - @flight_model ||= BellX1::FlightModel.new - end - end -end -``` - -Also, `require_dependency` is a solution: - -```ruby -require_dependency 'bell_x1/flight_model' - -module BellX1 - class Plane - def flight_model - @flight_model ||= FlightModel.new - end - end -end -``` - -#### Qualified References - -WARNING. This gotcha is only possible in Ruby < 2.5. - -Given - -```ruby -# app/models/hotel.rb -class Hotel -end - -# app/models/image.rb -class Image -end - -# app/models/hotel/image.rb -class Hotel - class Image < Image - end -end -``` - -the expression `Hotel::Image` is ambiguous because it depends on the execution -path. - -As [we saw before](#resolution-algorithm-for-qualified-constants), Ruby looks -up the constant in `Hotel` and its ancestors. If `app/models/image.rb` has -been loaded but `app/models/hotel/image.rb` hasn't, Ruby does not find `Image` -in `Hotel`, but it does in `Object`: - -``` -$ rails r 'Image; p Hotel::Image' 2>/dev/null -Image # NOT Hotel::Image! -``` - -The code evaluating `Hotel::Image` needs to make sure -`app/models/hotel/image.rb` has been loaded, possibly with -`require_dependency`. - -In these cases the interpreter issues a warning though: - -``` -warning: toplevel constant Image referenced by Hotel::Image -``` - -This surprising constant resolution can be observed with any qualifying class: - -``` -2.1.5 :001 > String::Array -(irb):1: warning: toplevel constant Array referenced by String::Array - => Array -``` - -WARNING. To find this gotcha the qualifying namespace has to be a class, -`Object` is not an ancestor of modules. - -### Autoloading within Singleton Classes - -Let's suppose we have these class definitions: - -```ruby -# app/models/hotel/services.rb -module Hotel - class Services - end -end - -# app/models/hotel/geo_location.rb -module Hotel - class GeoLocation - class << self - Services - end - end -end ``` -If `Hotel::Services` is known by the time `app/models/hotel/geo_location.rb` -is being loaded, `Services` is resolved by Ruby because `Hotel` belongs to the -nesting when the singleton class of `Hotel::GeoLocation` is opened. +Rails.autoloaders +----------------- -But if `Hotel::Services` is not known, Rails is not able to autoload it, the -application raises `NameError`. - -The reason is that autoloading is triggered for the singleton class, which is -anonymous, and as [we saw before](#generic-procedure), Rails only checks the -top-level namespace in that edge case. - -An easy solution to this caveat is to qualify the constant: +The Zeitwerk instances managing your application are availabe at ```ruby -module Hotel - class GeoLocation - class << self - Hotel::Services - end - end -end +Rails.autoloaders.main +Rails.autoloaders.once ``` -### Autoloading in `BasicObject` - -Direct descendants of `BasicObject` do not have `Object` among their ancestors -and cannot resolve top-level constants: - -```ruby -class C < BasicObject - String # NameError: uninitialized constant C::String -end -``` +The former is the main one. The latter is there mostly for backwards compatibily reasons, in case the application has something in `config.autoload_once_paths` (this is discouraged nowadays). -When autoloading is involved that plot has a twist. Let's consider: +You can check if `zeitwerk` mode is enabled with ```ruby -class C < BasicObject - def user - User # WRONG - end -end +Rails.autoloaders.zeitwerk_enabled? ``` -Since Rails checks the top-level namespace `User` gets autoloaded just fine the -first time the `user` method is invoked. You only get the exception if the -`User` constant is known at that point, in particular in a *second* call to -`user`: - -```ruby -c = C.new -c.user # surprisingly fine, User -c.user # NameError: uninitialized constant C::User -``` - -because it detects that a parent namespace already has the constant (see [Qualified -References](#autoloading-algorithms-qualified-references)). - -As with pure Ruby, within the body of a direct descendant of `BasicObject` use -always absolute constant paths: - -```ruby -class C < BasicObject - ::String # RIGHT - - def user - ::User # RIGHT - end -end -``` - -### Autoloading in the Test Environment - -When configuring the `test` environment for autoloading you might consider multiple factors. - -For example it might be worth running your tests with an identical setup to production (`config.eager_load = true`, `config.cache_classes = true`) in order to catch any problems before they hit production (this is compensation for the lack of dev-prod parity). However this will slow down the boot time for individual tests on a dev machine (and is not immediately compatible with spring see below). So one possibility is to do this on a -[CI](https://en.wikipedia.org/wiki/Continuous_integration) machine only (which should run without spring). - -On a development machine you can then have your tests running with whatever is fastest (ideally `config.eager_load = false`). - -With the [Spring](https://github.com/rails/spring) pre-loader (included with new Rails apps), you ideally keep `config.eager_load = false` as per development. Sometimes you may end up with a hybrid configuration (`config.eager_load = true`, `config.cache_classes = true` AND `config.enable_dependency_loading = true`), see [spring issue](https://github.com/rails/spring/issues/519#issuecomment-348324369). However it might be simpler to keep the same configuration as development, and work out whatever it is that is causing autoloading to fail (perhaps by the results of your CI test results). - -Occasionally you may need to explicitly eager_load by using `Rails -.application.eager_load!` in the setup of your tests -- this might occur if your [tests involve multithreading](https://stackoverflow.com/questions/25796409/in-rails-how-can-i-eager-load-all-code-before-a-specific-rspec-test). - -## Troubleshooting - -### Tracing Autoloads - -Active Support is able to report constants as they are autoloaded. To enable these traces in a Rails application, put the following two lines in some initializer: - -```ruby -ActiveSupport::Dependencies.logger = Rails.logger -ActiveSupport::Dependencies.verbose = true -``` - -### Where is a Given Autoload Triggered? +Opting Out +---------- -If constant `Foo` is being autoloaded, and you'd like to know where is that autoload coming from, just throw +Applications can load Rails 6 defaults and still use the classic autoloader this way: ```ruby -puts caller +# config/application.rb +config.load_defaults "6.x" +config.autoloader = :classic ``` -at the top of `foo.rb` and inspect the printed stack trace. - -### Which Constants Have Been Autoloaded? - -At any given time, - -```ruby -ActiveSupport::Dependencies.autoloaded_constants -``` +That may be handy if upgrading to Rails 6 in different phases, but classic mode is discouraged for new applications. -has the collection of constants that have been autoloaded so far. +`zeitwerk` mode is not available in versions of Rails previous to 6.0. diff --git a/guides/source/autoloading_and_reloading_constants_classic_mode.md b/guides/source/autoloading_and_reloading_constants_classic_mode.md new file mode 100644 index 0000000000..d0d9e076d6 --- /dev/null +++ b/guides/source/autoloading_and_reloading_constants_classic_mode.md @@ -0,0 +1,1351 @@ +**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.** + +Autoloading and Reloading Constants (Classic Mode) +================================================== + +This guide documents how constant autoloading and reloading works in `classic` mode. + +After reading this guide, you will know: + +* Key aspects of Ruby constants +* What are the `autoload_paths` and how does eager loading work in production? +* How constant autoloading works +* What is `require_dependency` +* How constant reloading works +* Solutions to common autoloading gotchas + +-------------------------------------------------------------------------------- + + +Introduction +------------ + +INFO. This guide documents autoloading in `classic` mode, which is the traditional one. If you'd like to read about `zeiwerk` mode instead, the new one in Rails 6, please check [Autoloading and Reloading Constants (Zeitwerk Mode)](autoloading_and_reloading_constants.html). + +Ruby on Rails allows applications to be written as if their code was preloaded. + +In a normal Ruby program classes need to load their dependencies: + +```ruby +require 'application_controller' +require 'post' + +class PostsController < ApplicationController + def index + @posts = Post.all + end +end +``` + +Our Rubyist instinct quickly sees some redundancy in there: If classes were +defined in files matching their name, couldn't their loading be automated +somehow? We could save scanning the file for dependencies, which is brittle. + +Moreover, `Kernel#require` loads files once, but development is much more smooth +if code gets refreshed when it changes without restarting the server. It would +be nice to be able to use `Kernel#load` in development, and `Kernel#require` in +production. + +Indeed, those features are provided by Ruby on Rails, where we just write + +```ruby +class PostsController < ApplicationController + def index + @posts = Post.all + end +end +``` + +This guide documents how that works. + + +Constants Refresher +------------------- + +While constants are trivial in most programming languages, they are a rich +topic in Ruby. + +It is beyond the scope of this guide to document Ruby constants, but we are +nevertheless going to highlight a few key topics. Truly grasping the following +sections is instrumental to understanding constant autoloading and reloading. + +### Nesting + +Class and module definitions can be nested to create namespaces: + +```ruby +module XML + class SAXParser + # (1) + end +end +``` + +The *nesting* at any given place is the collection of enclosing nested class and +module objects outwards. The nesting at any given place can be inspected with +`Module.nesting`. For example, in the previous example, the nesting at +(1) is + +```ruby +[XML::SAXParser, XML] +``` + +It is important to understand that the nesting is composed of class and module +*objects*, it has nothing to do with the constants used to access them, and is +also unrelated to their names. + +For instance, while this definition is similar to the previous one: + +```ruby +class XML::SAXParser + # (2) +end +``` + +the nesting in (2) is different: + +```ruby +[XML::SAXParser] +``` + +`XML` does not belong to it. + +We can see in this example that the name of a class or module that belongs to a +certain nesting does not necessarily correlate with the namespaces at the spot. + +Even more, they are totally independent, take for instance + +```ruby +module X + module Y + end +end + +module A + module B + end +end + +module X::Y + module A::B + # (3) + end +end +``` + +The nesting in (3) consists of two module objects: + +```ruby +[A::B, X::Y] +``` + +So, it not only doesn't end in `A`, which does not even belong to the nesting, +but it also contains `X::Y`, which is independent from `A::B`. + +The nesting is an internal stack maintained by the interpreter, and it gets +modified according to these rules: + +* The class object following a `class` keyword gets pushed when its body is +executed, and popped after it. + +* The module object following a `module` keyword gets pushed when its body is +executed, and popped after it. + +* A singleton class opened with `class << object` gets pushed, and popped later. + +* When `instance_eval` is called using a string argument, +the singleton class of the receiver is pushed to the nesting of the eval'ed +code. When `class_eval` or `module_eval` is called using a string argument, +the receiver is pushed to the nesting of the eval'ed code. + +* The nesting at the top-level of code interpreted by `Kernel#load` is empty +unless the `load` call receives a true value as second argument, in which case +a newly created anonymous module is pushed by Ruby. + +It is interesting to observe that blocks do not modify the stack. In particular +the blocks that may be passed to `Class.new` and `Module.new` do not get the +class or module being defined pushed to their nesting. That's one of the +differences between defining classes and modules in one way or another. + +### Class and Module Definitions are Constant Assignments + +Let's suppose the following snippet creates a class (rather than reopening it): + +```ruby +class C +end +``` + +Ruby creates a constant `C` in `Object` and stores in that constant a class +object. The name of the class instance is "C", a string, named after the +constant. + +That is, + +```ruby +class Project < ApplicationRecord +end +``` + +performs a constant assignment equivalent to + +```ruby +Project = Class.new(ApplicationRecord) +``` + +including setting the name of the class as a side-effect: + +```ruby +Project.name # => "Project" +``` + +Constant assignment has a special rule to make that happen: if the object +being assigned is an anonymous class or module, Ruby sets the object's name to +the name of the constant. + +INFO. From then on, what happens to the constant and the instance does not +matter. For example, the constant could be deleted, the class object could be +assigned to a different constant, be stored in no constant anymore, etc. Once +the name is set, it doesn't change. + +Similarly, module creation using the `module` keyword as in + +```ruby +module Admin +end +``` + +performs a constant assignment equivalent to + +```ruby +Admin = Module.new +``` + +including setting the name as a side-effect: + +```ruby +Admin.name # => "Admin" +``` + +WARNING. The execution context of a block passed to `Class.new` or `Module.new` +is not entirely equivalent to the one of the body of the definitions using the +`class` and `module` keywords. But both idioms result in the same constant +assignment. + +Thus, an informal expression like "the `String` class" technically means the +class object stored in the constant called "String". That constant, in turn, +belongs to the class object stored in the constant called "Object". + +`String` is an ordinary constant, and everything related to them such as +resolution algorithms applies to it. + +Likewise, in the controller + +```ruby +class PostsController < ApplicationController + def index + @posts = Post.all + end +end +``` + +`Post` is not syntax for a class. Rather, `Post` is a regular Ruby constant. If +all is good, the constant is evaluated to an object that responds to `all`. + +That is why we talk about *constant* autoloading, Rails has the ability to +load constants on the fly. + +### Constants are Stored in Modules + +Constants belong to modules in a very literal sense. Classes and modules have +a constant table; think of it as a hash table. + +Let's analyze an example to really understand what that means. While common +abuses of language like "the `String` class" are convenient, the exposition is +going to be precise here for didactic purposes. + +Let's consider the following module definition: + +```ruby +module Colors + RED = '0xff0000' +end +``` + +First, when the `module` keyword is processed, the interpreter creates a new +entry in the constant table of the class object stored in the `Object` constant. +Said entry associates the name "Colors" to a newly created module object. +Furthermore, the interpreter sets the name of the new module object to be the +string "Colors". + +Later, when the body of the module definition is interpreted, a new entry is +created in the constant table of the module object stored in the `Colors` +constant. That entry maps the name "RED" to the string "0xff0000". + +In particular, `Colors::RED` is totally unrelated to any other `RED` constant +that may live in any other class or module object. If there were any, they +would have separate entries in their respective constant tables. + +Pay special attention in the previous paragraphs to the distinction between +class and module objects, constant names, and value objects associated to them +in constant tables. + +### Resolution Algorithms + +#### Resolution Algorithm for Relative Constants + +At any given place in the code, let's define *cref* to be the first element of +the nesting if it is not empty, or `Object` otherwise. + +Without getting too much into the details, the resolution algorithm for relative +constant references goes like this: + +1. If the nesting is not empty the constant is looked up in its elements and in +order. The ancestors of those elements are ignored. + +2. If not found, then the algorithm walks up the ancestor chain of the cref. + +3. If not found and the cref is a module, the constant is looked up in `Object`. + +4. If not found, `const_missing` is invoked on the cref. The default +implementation of `const_missing` raises `NameError`, but it can be overridden. + +Rails autoloading **does not emulate this algorithm**, but its starting point is +the name of the constant to be autoloaded, and the cref. See more in [Relative +References](#autoloading-algorithms-relative-references). + +#### Resolution Algorithm for Qualified Constants + +Qualified constants look like this: + +```ruby +Billing::Invoice +``` + +`Billing::Invoice` is composed of two constants: `Billing` is relative and is +resolved using the algorithm of the previous section. + +INFO. Leading colons would make the first segment absolute rather than +relative: `::Billing::Invoice`. That would force `Billing` to be looked up +only as a top-level constant. + +`Invoice` on the other hand is qualified by `Billing` and we are going to see +its resolution next. Let's define *parent* to be that qualifying class or module +object, that is, `Billing` in the example above. The algorithm for qualified +constants goes like this: + +1. The constant is looked up in the parent and its ancestors. In Ruby >= 2.5, +`Object` is skipped if present among the ancestors. `Kernel` and `BasicObject` +are still checked though. + +2. If the lookup fails, `const_missing` is invoked in the parent. The default +implementation of `const_missing` raises `NameError`, but it can be overridden. + +INFO. In Ruby < 2.5 `String::Hash` evaluates to `Hash` and the interpreter +issues a warning: "toplevel constant Hash referenced by String::Hash". Starting +with 2.5, `String::Hash` raises `NameError` because `Object` is skipped. + +As you see, this algorithm is simpler than the one for relative constants. In +particular, the nesting plays no role here, and modules are not special-cased, +if neither they nor their ancestors have the constants, `Object` is **not** +checked. + +Rails autoloading **does not emulate this algorithm**, but its starting point is +the name of the constant to be autoloaded, and the parent. See more in +[Qualified References](#autoloading-algorithms-qualified-references). + + +Vocabulary +---------- + +### Parent Namespaces + +Given a string with a constant path we define its *parent namespace* to be the +string that results from removing its rightmost segment. + +For example, the parent namespace of the string "A::B::C" is the string "A::B", +the parent namespace of "A::B" is "A", and the parent namespace of "A" is "". + +The interpretation of a parent namespace when thinking about classes and modules +is tricky though. Let's consider a module M named "A::B": + +* The parent namespace, "A", may not reflect nesting at a given spot. + +* The constant `A` may no longer exist, some code could have removed it from +`Object`. + +* If `A` exists, the class or module that was originally in `A` may not be there +anymore. For example, if after a constant removal there was another constant +assignment there would generally be a different object in there. + +* In such case, it could even happen that the reassigned `A` held a new class or +module called also "A"! + +* In the previous scenarios M would no longer be reachable through `A::B` but +the module object itself could still be alive somewhere and its name would +still be "A::B". + +The idea of a parent namespace is at the core of the autoloading algorithms +and helps explain and understand their motivation intuitively, but as you see +that metaphor leaks easily. Given an edge case to reason about, take always into +account that by "parent namespace" the guide means exactly that specific string +derivation. + +### Loading Mechanism + +Rails autoloads files with `Kernel#load` when `config.cache_classes` is false, +the default in development mode, and with `Kernel#require` otherwise, the +default in production mode. + +`Kernel#load` allows Rails to execute files more than once if [constant +reloading](#constant-reloading) is enabled. + +This guide uses the word "load" freely to mean a given file is interpreted, but +the actual mechanism can be `Kernel#load` or `Kernel#require` depending on that +flag. + + +Autoloading Availability +------------------------ + +Rails is always able to autoload provided its environment is in place. For +example the `runner` command autoloads: + +``` +$ rails runner 'p User.column_names' +["id", "email", "created_at", "updated_at"] +``` + +The console autoloads, the test suite autoloads, and of course the application +autoloads. + +By default, Rails eager loads the application files when it boots in production +mode, so most of the autoloading going on in development does not happen. But +autoloading may still be triggered during eager loading. + +For example, given + +```ruby +class BeachHouse < House +end +``` + +if `House` is still unknown when `app/models/beach_house.rb` is being eager +loaded, Rails autoloads it. + + +autoload_paths and eager_load_paths +----------------------------------- + +As you probably know, when `require` gets a relative file name: + +```ruby +require 'erb' +``` + +Ruby looks for the file in the directories listed in `$LOAD_PATH`. That is, Ruby +iterates over all its directories and for each one of them checks whether they +have a file called "erb.rb", or "erb.so", or "erb.o", or "erb.dll". If it finds +any of them, the interpreter loads it and ends the search. Otherwise, it tries +again in the next directory of the list. If the list gets exhausted, `LoadError` +is raised. + +We are going to cover how constant autoloading works in more detail later, but +the idea is that when a constant like `Post` is hit and missing, if there's a +`post.rb` file for example in `app/models` Rails is going to find it, evaluate +it, and have `Post` defined as a side-effect. + +All right, Rails has a collection of directories similar to `$LOAD_PATH` in which +to look up `post.rb`. That collection is called `autoload_paths` and by +default it contains: + +* All subdirectories of `app` in the application and engines present at boot + time. For example, `app/controllers`. They do not need to be the default + ones, any custom directories like `app/workers` belong automatically to + `autoload_paths`. + +* Any existing second level directories called `app/*/concerns` in the + application and engines. + +* The directory `test/mailers/previews`. + +`eager_load_paths` is initially the `app` paths above + +How files are autoloaded depends on `eager_load` and `cache_classes` config settings which typically vary in development, production, and test modes: + + * In **development**, you want quicker startup with incremental loading of application code. So `eager_load` should be set to `false`, and Rails will autoload files as needed (see [Autoloading Algorithms](#autoloading-algorithms) below) -- and then reload them when they change (see [Constant Reloading](#constant-reloading) below). + * In **production**, however, you want consistency and thread-safety and can live with a longer boot time. So `eager_load` is set to `true`, and then during boot (before the app is ready to receive requests) Rails loads all files in the `eager_load_paths` and then turns off auto loading (NB: autoloading may be needed during eager loading). Not autoloading after boot is a `good thing`, as autoloading can cause the app to be have thread-safety problems. + * In **test**, for speed of execution (of individual tests) `eager_load` is `false`, so Rails follows development behaviour. + +What is described above are the defaults with a newly generated Rails app. There are multiple ways this can be configured differently (see [Configuring Rails Applications](configuring.html#rails-general-configuration). +). But using `autoload_paths` on its own in the past (before Rails 5) developers might configure `autoload_paths` to add in extra locations (e.g. `lib` which used to be an autoload path list years ago, but no longer is). However this is now discouraged for most purposes, as it is likely to lead to production-only errors. It is possible to add new locations to both `config.eager_load_paths` and `config.autoload_paths` but use at your own risk. + +See also [Autoloading in the Test Environment](#autoloading-in-the-test-environment). + +`config.autoload_paths` is not changeable from environment-specific configuration files. + +The value of `autoload_paths` can be inspected. In a just-generated application +it is (edited): + +``` +$ rails r 'puts ActiveSupport::Dependencies.autoload_paths' +.../app/assets +.../app/channels +.../app/controllers +.../app/controllers/concerns +.../app/helpers +.../app/jobs +.../app/mailers +.../app/models +.../app/models/concerns +.../activestorage/app/assets +.../activestorage/app/controllers +.../activestorage/app/javascript +.../activestorage/app/jobs +.../activestorage/app/models +.../actioncable/app/assets +.../actionview/app/assets +.../test/mailers/previews +``` + +INFO. `autoload_paths` is computed and cached during the initialization process. +The application needs to be restarted to reflect any changes in the directory +structure. + + +Autoloading Algorithms +---------------------- + +### Relative References + +A relative constant reference may appear in several places, for example, in + +```ruby +class PostsController < ApplicationController + def index + @posts = Post.all + end +end +``` + +all three constant references are relative. + +#### Constants after the `class` and `module` Keywords + +Ruby performs a lookup for the constant that follows a `class` or `module` +keyword because it needs to know if the class or module is going to be created +or reopened. + +If the constant is not defined at that point it is not considered to be a +missing constant, autoloading is **not** triggered. + +So, in the previous example, if `PostsController` is not defined when the file +is interpreted Rails autoloading is not going to be triggered, Ruby will just +define the controller. + +#### Top-Level Constants + +On the contrary, if `ApplicationController` is unknown, the constant is +considered missing and an autoload is going to be attempted by Rails. + +In order to load `ApplicationController`, Rails iterates over `autoload_paths`. +First it checks if `app/assets/application_controller.rb` exists. If it does not, +which is normally the case, it continues and finds +`app/controllers/application_controller.rb`. + +If the file defines the constant `ApplicationController` all is fine, otherwise +`LoadError` is raised: + +``` +unable to autoload constant ApplicationController, expected +<full path to application_controller.rb> to define it (LoadError) +``` + +INFO. Rails does not require the value of autoloaded constants to be a class or +module object. For example, if the file `app/models/max_clients.rb` defines +`MAX_CLIENTS = 100` autoloading `MAX_CLIENTS` works just fine. + +#### Namespaces + +Autoloading `ApplicationController` looks directly under the directories of +`autoload_paths` because the nesting in that spot is empty. The situation of +`Post` is different, the nesting in that line is `[PostsController]` and support +for namespaces comes into play. + +The basic idea is that given + +```ruby +module Admin + class BaseController < ApplicationController + @@all_roles = Role.all + end +end +``` + +to autoload `Role` we are going to check if it is defined in the current or +parent namespaces, one at a time. So, conceptually we want to try to autoload +any of + +``` +Admin::BaseController::Role +Admin::Role +Role +``` + +in that order. That's the idea. To do so, Rails looks in `autoload_paths` +respectively for file names like these: + +``` +admin/base_controller/role.rb +admin/role.rb +role.rb +``` + +modulus some additional directory lookups we are going to cover soon. + +INFO. `'Constant::Name'.underscore` gives the relative path without extension of +the file name where `Constant::Name` is expected to be defined. + +Let's see how Rails autoloads the `Post` constant in the `PostsController` +above assuming the application has a `Post` model defined in +`app/models/post.rb`. + +First it checks for `posts_controller/post.rb` in `autoload_paths`: + +``` +app/assets/posts_controller/post.rb +app/controllers/posts_controller/post.rb +app/helpers/posts_controller/post.rb +... +test/mailers/previews/posts_controller/post.rb +``` + +Since the lookup is exhausted without success, a similar search for a directory +is performed, we are going to see why in the [next section](#automatic-modules): + +``` +app/assets/posts_controller/post +app/controllers/posts_controller/post +app/helpers/posts_controller/post +... +test/mailers/previews/posts_controller/post +``` + +If all those attempts fail, then Rails starts the lookup again in the parent +namespace. In this case only the top-level remains: + +``` +app/assets/post.rb +app/controllers/post.rb +app/helpers/post.rb +app/mailers/post.rb +app/models/post.rb +``` + +A matching file is found in `app/models/post.rb`. The lookup stops there and the +file is loaded. If the file actually defines `Post` all is fine, otherwise +`LoadError` is raised. + +### Qualified References + +When a qualified constant is missing Rails does not look for it in the parent +namespaces. But there is a caveat: when a constant is missing, Rails is +unable to tell if the trigger was a relative reference or a qualified one. + +For example, consider + +```ruby +module Admin + User +end +``` + +and + +```ruby +Admin::User +``` + +If `User` is missing, in either case all Rails knows is that a constant called +"User" was missing in a module called "Admin". + +If there is a top-level `User` Ruby would resolve it in the former example, but +wouldn't in the latter. In general, Rails does not emulate the Ruby constant +resolution algorithms, but in this case it tries using the following heuristic: + +> If none of the parent namespaces of the class or module has the missing +> constant then Rails assumes the reference is relative. Otherwise qualified. + +For example, if this code triggers autoloading + +```ruby +Admin::User +``` + +and the `User` constant is already present in `Object`, it is not possible that +the situation is + +```ruby +module Admin + User +end +``` + +because otherwise Ruby would have resolved `User` and no autoloading would have +been triggered in the first place. Thus, Rails assumes a qualified reference and +considers the file `admin/user.rb` and directory `admin/user` to be the only +valid options. + +In practice, this works quite well as long as the nesting matches all parent +namespaces respectively and the constants that make the rule apply are known at +that time. + +However, autoloading happens on demand. If by chance the top-level `User` was +not yet loaded, then Rails assumes a relative reference by contract. + +Naming conflicts of this kind are rare in practice, but if one occurs, +`require_dependency` provides a solution by ensuring that the constant needed +to trigger the heuristic is defined in the conflicting place. + +### Automatic Modules + +When a module acts as a namespace, Rails does not require the application to +define a file for it, a directory matching the namespace is enough. + +Suppose an application has a back office whose controllers are stored in +`app/controllers/admin`. If the `Admin` module is not yet loaded when +`Admin::UsersController` is hit, Rails needs first to autoload the constant +`Admin`. + +If `autoload_paths` has a file called `admin.rb` Rails is going to load that +one, but if there's no such file and a directory called `admin` is found, Rails +creates an empty module and assigns it to the `Admin` constant on the fly. + +### Generic Procedure + +Relative references are reported to be missing in the cref where they were hit, +and qualified references are reported to be missing in their parent (see +[Resolution Algorithm for Relative +Constants](#resolution-algorithm-for-relative-constants) at the beginning of +this guide for the definition of *cref*, and [Resolution Algorithm for Qualified +Constants](#resolution-algorithm-for-qualified-constants) for the definition of +*parent*). + +The procedure to autoload constant `C` in an arbitrary situation is as follows: + +``` +if the class or module in which C is missing is Object + let ns = '' +else + let M = the class or module in which C is missing + + if M is anonymous + let ns = '' + else + let ns = M.name + end +end + +loop do + # Look for a regular file. + for dir in autoload_paths + if the file "#{dir}/#{ns.underscore}/c.rb" exists + load/require "#{dir}/#{ns.underscore}/c.rb" + + if C is now defined + return + else + raise LoadError + end + end + end + + # Look for an automatic module. + for dir in autoload_paths + if the directory "#{dir}/#{ns.underscore}/c" exists + if ns is an empty string + let C = Module.new in Object and return + else + let C = Module.new in ns.constantize and return + end + end + end + + if ns is empty + # We reached the top-level without finding the constant. + raise NameError + else + if C exists in any of the parent namespaces + # Qualified constants heuristic. + raise NameError + else + # Try again in the parent namespace. + let ns = the parent namespace of ns and retry + end + end +end +``` + + +require_dependency +------------------ + +Constant autoloading is triggered on demand and therefore code that uses a +certain constant may have it already defined or may trigger an autoload. That +depends on the execution path and it may vary between runs. + +There are times, however, in which you want to make sure a certain constant is +known when the execution reaches some code. `require_dependency` provides a way +to load a file using the current [loading mechanism](#loading-mechanism), and +keeping track of constants defined in that file as if they were autoloaded to +have them reloaded as needed. + +`require_dependency` is rarely needed, but see a couple of use cases in +[Autoloading and STI](#autoloading-and-sti) and [When Constants aren't +Triggered](#when-constants-aren-t-missed). + +WARNING. Unlike autoloading, `require_dependency` does not expect the file to +define any particular constant. Exploiting this behavior would be a bad practice +though, file and constant paths should match. + + +Constant Reloading +------------------ + +When `config.cache_classes` is false Rails is able to reload autoloaded +constants. + +For example, if you're in a console session and edit some file behind the +scenes, the code can be reloaded with the `reload!` command: + +``` +> reload! +``` + +When the application runs, code is reloaded when something relevant to this +logic changes. In order to do that, Rails monitors a number of things: + +* `config/routes.rb`. + +* Locales. + +* Ruby files under `autoload_paths`. + +* `db/schema.rb` and `db/structure.sql`. + +If anything in there changes, there is a middleware that detects it and reloads +the code. + +Autoloading keeps track of autoloaded constants. Reloading is implemented by +removing them all from their respective classes and modules using +`Module#remove_const`. That way, when the code goes on, those constants are +going to be unknown again, and files reloaded on demand. + +INFO. This is an all-or-nothing operation, Rails does not attempt to reload only +what changed since dependencies between classes makes that really tricky. +Instead, everything is wiped. + +Common Gotchas +-------------- + +### Nesting and Qualified Constants + +Let's consider + +```ruby +module Admin + class UsersController < ApplicationController + def index + @users = User.all + end + end +end +``` + +and + +```ruby +class Admin::UsersController < ApplicationController + def index + @users = User.all + end +end +``` + +To resolve `User` Ruby checks `Admin` in the former case, but it does not in +the latter because it does not belong to the nesting (see [Nesting](#nesting) +and [Resolution Algorithms](#resolution-algorithms)). + +Unfortunately Rails autoloading does not know the nesting in the spot where the +constant was missing and so it is not able to act as Ruby would. In particular, +`Admin::User` will get autoloaded in either case. + +Albeit qualified constants with `class` and `module` keywords may technically +work with autoloading in some cases, it is preferable to use relative constants +instead: + +```ruby +module Admin + class UsersController < ApplicationController + def index + @users = User.all + end + end +end +``` + +### Autoloading and STI + +Single Table Inheritance (STI) is a feature of Active Record that enables +storing a hierarchy of models in one single table. The API of such models is +aware of the hierarchy and encapsulates some common needs. For example, given +these classes: + +```ruby +# app/models/polygon.rb +class Polygon < ApplicationRecord +end + +# app/models/triangle.rb +class Triangle < Polygon +end + +# app/models/rectangle.rb +class Rectangle < Polygon +end +``` + +`Triangle.create` creates a row that represents a triangle, and +`Rectangle.create` creates a row that represents a rectangle. If `id` is the +ID of an existing record, `Polygon.find(id)` returns an object of the correct +type. + +Methods that operate on collections are also aware of the hierarchy. For +example, `Polygon.all` returns all the records of the table, because all +rectangles and triangles are polygons. Active Record takes care of returning +instances of their corresponding class in the result set. + +Types are autoloaded as needed. For example, if `Polygon.first` is a rectangle +and `Rectangle` has not yet been loaded, Active Record autoloads it and the +record is correctly instantiated. + +All good, but if instead of performing queries based on the root class we need +to work on some subclass, things get interesting. + +While working with `Polygon` you do not need to be aware of all its descendants, +because anything in the table is by definition a polygon, but when working with +subclasses Active Record needs to be able to enumerate the types it is looking +for. Let's see an example. + +`Rectangle.all` only loads rectangles by adding a type constraint to the query: + +```sql +SELECT "polygons".* FROM "polygons" +WHERE "polygons"."type" IN ("Rectangle") +``` + +Let's introduce now a subclass of `Rectangle`: + +```ruby +# app/models/square.rb +class Square < Rectangle +end +``` + +`Rectangle.all` should now return rectangles **and** squares: + +```sql +SELECT "polygons".* FROM "polygons" +WHERE "polygons"."type" IN ("Rectangle", "Square") +``` + +But there's a caveat here: How does Active Record know that the class `Square` +exists at all? + +Even if the file `app/models/square.rb` exists and defines the `Square` class, +if no code yet used that class, `Rectangle.all` issues the query + +```sql +SELECT "polygons".* FROM "polygons" +WHERE "polygons"."type" IN ("Rectangle") +``` + +That is not a bug, the query includes all *known* descendants of `Rectangle`. + +A way to ensure this works correctly regardless of the order of execution is to +manually load the direct subclasses at the bottom of the file that defines each +intermediate class: + +```ruby +# app/models/rectangle.rb +class Rectangle < Polygon +end +require_dependency 'square' +``` + +This needs to happen for every intermediate (non-root and non-leaf) class. The +root class does not scope the query by type, and therefore does not necessarily +have to know all its descendants. + +### Autoloading and `require` + +Files defining constants to be autoloaded should never be `require`d: + +```ruby +require 'user' # DO NOT DO THIS + +class UsersController < ApplicationController + ... +end +``` + +There are two possible gotchas here in development mode: + +1. If `User` is autoloaded before reaching the `require`, `app/models/user.rb` +runs again because `load` does not update `$LOADED_FEATURES`. + +2. If the `require` runs first Rails does not mark `User` as an autoloaded +constant and changes to `app/models/user.rb` aren't reloaded. + +Just follow the flow and use constant autoloading always, never mix +autoloading and `require`. As a last resort, if some file absolutely needs to +load a certain file use `require_dependency` to play nice with constant +autoloading. This option is rarely needed in practice, though. + +Of course, using `require` in autoloaded files to load ordinary 3rd party +libraries is fine, and Rails is able to distinguish their constants, they are +not marked as autoloaded. + +### Autoloading and Initializers + +Consider this assignment in `config/initializers/set_auth_service.rb`: + +```ruby +AUTH_SERVICE = if Rails.env.production? + RealAuthService +else + MockedAuthService +end +``` + +The purpose of this setup would be that the application uses the class that +corresponds to the environment via `AUTH_SERVICE`. In development mode +`MockedAuthService` gets autoloaded when the initializer runs. Let's suppose +we do some requests, change its implementation, and hit the application again. +To our surprise the changes are not reflected. Why? + +As [we saw earlier](#constant-reloading), Rails removes autoloaded constants, +but `AUTH_SERVICE` stores the original class object. Stale, non-reachable +using the original constant, but perfectly functional. + +The following code summarizes the situation: + +```ruby +class C + def quack + 'quack!' + end +end + +X = C +Object.instance_eval { remove_const(:C) } +X.new.quack # => quack! +X.name # => C +C # => uninitialized constant C (NameError) +``` + +Because of that, it is not a good idea to autoload constants on application +initialization. + +In the case above we could implement a dynamic access point: + +```ruby +# app/models/auth_service.rb +class AuthService + if Rails.env.production? + def self.instance + RealAuthService + end + else + def self.instance + MockedAuthService + end + end +end +``` + +and have the application use `AuthService.instance` instead. `AuthService` +would be loaded on demand and be autoload-friendly. + +### `require_dependency` and Initializers + +As we saw before, `require_dependency` loads files in an autoloading-friendly +way. Normally, though, such a call does not make sense in an initializer. + +One could think about doing some [`require_dependency`](#require-dependency) +calls in an initializer to make sure certain constants are loaded upfront, for +example as an attempt to address the [gotcha with STIs](#autoloading-and-sti). + +Problem is, in development mode [autoloaded constants are wiped](#constant-reloading) +if there is any relevant change in the file system. If that happens then +we are in the very same situation the initializer wanted to avoid! + +Calls to `require_dependency` have to be strategically written in autoloaded +spots. + +### When Constants aren't Missed + +#### Relative References + +Let's consider a flight simulator. The application has a default flight model + +```ruby +# app/models/flight_model.rb +class FlightModel +end +``` + +that can be overridden by each airplane, for instance + +```ruby +# app/models/bell_x1/flight_model.rb +module BellX1 + class FlightModel < FlightModel + end +end + +# app/models/bell_x1/aircraft.rb +module BellX1 + class Aircraft + def initialize + @flight_model = FlightModel.new + end + end +end +``` + +The initializer wants to create a `BellX1::FlightModel` and nesting has +`BellX1`, that looks good. But if the default flight model is loaded and the +one for the Bell-X1 is not, the interpreter is able to resolve the top-level +`FlightModel` and autoloading is thus not triggered for `BellX1::FlightModel`. + +That code depends on the execution path. + +These kind of ambiguities can often be resolved using qualified constants: + +```ruby +module BellX1 + class Plane + def flight_model + @flight_model ||= BellX1::FlightModel.new + end + end +end +``` + +Also, `require_dependency` is a solution: + +```ruby +require_dependency 'bell_x1/flight_model' + +module BellX1 + class Plane + def flight_model + @flight_model ||= FlightModel.new + end + end +end +``` + +#### Qualified References + +WARNING. This gotcha is only possible in Ruby < 2.5. + +Given + +```ruby +# app/models/hotel.rb +class Hotel +end + +# app/models/image.rb +class Image +end + +# app/models/hotel/image.rb +class Hotel + class Image < Image + end +end +``` + +the expression `Hotel::Image` is ambiguous because it depends on the execution +path. + +As [we saw before](#resolution-algorithm-for-qualified-constants), Ruby looks +up the constant in `Hotel` and its ancestors. If `app/models/image.rb` has +been loaded but `app/models/hotel/image.rb` hasn't, Ruby does not find `Image` +in `Hotel`, but it does in `Object`: + +``` +$ rails r 'Image; p Hotel::Image' 2>/dev/null +Image # NOT Hotel::Image! +``` + +The code evaluating `Hotel::Image` needs to make sure +`app/models/hotel/image.rb` has been loaded, possibly with +`require_dependency`. + +In these cases the interpreter issues a warning though: + +``` +warning: toplevel constant Image referenced by Hotel::Image +``` + +This surprising constant resolution can be observed with any qualifying class: + +``` +2.1.5 :001 > String::Array +(irb):1: warning: toplevel constant Array referenced by String::Array + => Array +``` + +WARNING. To find this gotcha the qualifying namespace has to be a class, +`Object` is not an ancestor of modules. + +### Autoloading within Singleton Classes + +Let's suppose we have these class definitions: + +```ruby +# app/models/hotel/services.rb +module Hotel + class Services + end +end + +# app/models/hotel/geo_location.rb +module Hotel + class GeoLocation + class << self + Services + end + end +end +``` + +If `Hotel::Services` is known by the time `app/models/hotel/geo_location.rb` +is being loaded, `Services` is resolved by Ruby because `Hotel` belongs to the +nesting when the singleton class of `Hotel::GeoLocation` is opened. + +But if `Hotel::Services` is not known, Rails is not able to autoload it, the +application raises `NameError`. + +The reason is that autoloading is triggered for the singleton class, which is +anonymous, and as [we saw before](#generic-procedure), Rails only checks the +top-level namespace in that edge case. + +An easy solution to this caveat is to qualify the constant: + +```ruby +module Hotel + class GeoLocation + class << self + Hotel::Services + end + end +end +``` + +### Autoloading in `BasicObject` + +Direct descendants of `BasicObject` do not have `Object` among their ancestors +and cannot resolve top-level constants: + +```ruby +class C < BasicObject + String # NameError: uninitialized constant C::String +end +``` + +When autoloading is involved that plot has a twist. Let's consider: + +```ruby +class C < BasicObject + def user + User # WRONG + end +end +``` + +Since Rails checks the top-level namespace `User` gets autoloaded just fine the +first time the `user` method is invoked. You only get the exception if the +`User` constant is known at that point, in particular in a *second* call to +`user`: + +```ruby +c = C.new +c.user # surprisingly fine, User +c.user # NameError: uninitialized constant C::User +``` + +because it detects that a parent namespace already has the constant (see [Qualified +References](#autoloading-algorithms-qualified-references)). + +As with pure Ruby, within the body of a direct descendant of `BasicObject` use +always absolute constant paths: + +```ruby +class C < BasicObject + ::String # RIGHT + + def user + ::User # RIGHT + end +end +``` + +### Autoloading in the Test Environment + +When configuring the `test` environment for autoloading you might consider multiple factors. + +For example it might be worth running your tests with an identical setup to production (`config.eager_load = true`, `config.cache_classes = true`) in order to catch any problems before they hit production (this is compensation for the lack of dev-prod parity). However this will slow down the boot time for individual tests on a dev machine (and is not immediately compatible with spring see below). So one possibility is to do this on a +[CI](https://en.wikipedia.org/wiki/Continuous_integration) machine only (which should run without spring). + +On a development machine you can then have your tests running with whatever is fastest (ideally `config.eager_load = false`). + +With the [Spring](https://github.com/rails/spring) pre-loader (included with new Rails apps), you ideally keep `config.eager_load = false` as per development. Sometimes you may end up with a hybrid configuration (`config.eager_load = true`, `config.cache_classes = true` AND `config.enable_dependency_loading = true`), see [spring issue](https://github.com/rails/spring/issues/519#issuecomment-348324369). However it might be simpler to keep the same configuration as development, and work out whatever it is that is causing autoloading to fail (perhaps by the results of your CI test results). + +Occasionally you may need to explicitly eager_load by using `Rails +.application.eager_load!` in the setup of your tests -- this might occur if your [tests involve multithreading](https://stackoverflow.com/questions/25796409/in-rails-how-can-i-eager-load-all-code-before-a-specific-rspec-test). + +## Troubleshooting + +### Tracing Autoloads + +Active Support is able to report constants as they are autoloaded. To enable these traces in a Rails application, put the following two lines in some initializer: + +```ruby +ActiveSupport::Dependencies.logger = Rails.logger +ActiveSupport::Dependencies.verbose = true +``` + +### Where is a Given Autoload Triggered? + +If constant `Foo` is being autoloaded, and you'd like to know where is that autoload coming from, just throw + +```ruby +puts caller +``` + +at the top of `foo.rb` and inspect the printed stack trace. + +### Which Constants Have Been Autoloaded? + +At any given time, + +```ruby +ActiveSupport::Dependencies.autoloaded_constants +``` + +has the collection of constants that have been autoloaded so far. diff --git a/guides/source/command_line.md b/guides/source/command_line.md index 4681574edd..60d0de17bc 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -601,6 +601,8 @@ The `tmp:` namespaced commands will help you clear and create the `Rails.root/tm ### Miscellaneous +* `rails initializers` prints out all defined initializers in the order they are invoked by Rails. +* `rails middleware` lists Rack middleware stack enabled for your app. * `rails stats` is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio. * `rails secret` will give you a pseudo-random key to use for your session secret. * `rails time:zones:all` lists all the timezones Rails knows about. diff --git a/guides/source/configuring.md b/guides/source/configuring.md index cc64c7eac6..c5d3d09bd0 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -353,7 +353,7 @@ All these configuration options are delegated to the `I18n` library. * `config.active_record.lock_optimistically` controls whether Active Record will use optimistic locking and is `true` by default. -* `config.active_record.cache_timestamp_format` controls the format of the timestamp value in the cache key. Default is `:nsec`. +* `config.active_record.cache_timestamp_format` controls the format of the timestamp value in the cache key. Default is `:usec`. * `config.active_record.record_timestamps` is a boolean value which controls whether or not timestamping of `create` and `update` operations on a model occur. The default value is `true`. @@ -553,6 +553,10 @@ Defaults to `'signed cookie'`. Any exceptions that are not configured will be mapped to 500 Internal Server Error. +* `config.action_dispatch.return_only_media_type_on_content_type` change the + return value of `ActionDispatch::Response#content_type` to the Content-Type + header without modification. Defaults to `false`. + * `ActionDispatch::Callbacks.before` takes a block of code to run before the request. * `ActionDispatch::Callbacks.after` takes a block of code to run after the request. @@ -835,10 +839,12 @@ You can find more detailed configuration options in the config.active_storage.paths[:ffprobe] = '/usr/local/bin/ffprobe' ``` -* `config.active_storage.variable_content_types` accepts an array of strings indicating the content types that Active Storage can transform through ImageMagick. The default is `%w(image/png image/gif image/jpg image/jpeg image/pjpeg image/tiff image/vnd.adobe.photoshop image/vnd.microsoft.icon)`. +* `config.active_storage.variable_content_types` accepts an array of strings indicating the content types that Active Storage can transform through ImageMagick. The default is `%w(image/png image/gif image/jpg image/jpeg image/pjpeg image/tiff image/bmp image/vnd.adobe.photoshop image/vnd.microsoft.icon)`. * `config.active_storage.content_types_to_serve_as_binary` accepts an array of strings indicating the content types that Active Storage will always serve as an attachment, rather than inline. The default is `%w(text/html -text/javascript image/svg+xml application/postscript application/x-shockwave-flash text/xml application/xml application/xhtml+xml)`. +text/javascript image/svg+xml application/postscript application/x-shockwave-flash text/xml application/xml application/xhtml+xml application/mathml+xml text/cache-manifest)`. + +* `config.active_storage.content_types_allowed_inline` accepts an array of strings indicating the content types that Active Storage allows to serve as inline. The default is `%w(image/png image/gif image/jpg image/jpeg image/vnd.adobe.photoshop image/vnd.microsoft.icon application/pdf)`. * `config.active_storage.queues.analysis` accepts a symbol indicating the Active Job queue to use for analysis jobs. When this option is `nil`, analysis jobs are sent to the default Active Job queue (see `config.active_job.default_queue_name`). @@ -877,7 +883,11 @@ text/javascript image/svg+xml application/postscript application/x-shockwave-fla config.active_storage.routes_prefix = '/files' ``` - The default is `/rails/active_storage` + The default is `/rails/active_storage`. + +* `config.active_storage.replace_on_assign_to_many` determines whether assigning to a collection of attachments declared with `has_many_attached` replaces any existing attachments or appends to them. The default is `true`. + +* `config.active_storage.draw_routes` can be used to toggle Active Storage route generation. The default is `true`. ### Results of `load_defaults` @@ -897,7 +907,7 @@ text/javascript image/svg+xml application/postscript application/x-shockwave-fla #### With '5.2': - `config.active_record.cache_versioning`: `true` -- `action_dispatch.use_authenticated_cookie_encryption`: `true` +- `config.action_dispatch.use_authenticated_cookie_encryption`: `true` - `config.active_support.use_authenticated_message_encryption`: `true` - `config.active_support.use_sha1_digests`: `true` - `config.action_controller.default_protect_from_forgery`: `true` @@ -908,10 +918,12 @@ text/javascript image/svg+xml application/postscript application/x-shockwave-fla - `config.autoloader`: `:zeitwerk` - `config.action_view.default_enforce_utf8`: `false` - `config.action_dispatch.use_cookies_with_metadata`: `true` +- `config.action_dispatch.return_only_media_type_on_content_type`: `false` - `config.action_mailer.delivery_job`: `"ActionMailer::MailDeliveryJob"` - `config.active_job.return_false_on_aborted_enqueue`: `true` - `config.active_storage.queues.analysis`: `:active_storage_analysis` - `config.active_storage.queues.purge`: `:active_storage_purge` +- `config.active_storage.replace_on_assign_to_many`: `true` - `config.active_record.collection_cache_versioning`: `true` ### Configuring a Database @@ -1536,7 +1548,7 @@ Disallow: / ``` To block just specific pages, it's necessary to use a more complex syntax. Learn -it on the [official documentation](http://www.robotstxt.org/robotstxt.html). +it on the [official documentation](https://www.robotstxt.org/robotstxt.html). Evented File System Monitor --------------------------- diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md index a6eb9907a0..9c28ff6a9c 100644 --- a/guides/source/contributing_to_ruby_on_rails.md +++ b/guides/source/contributing_to_ruby_on_rails.md @@ -13,7 +13,7 @@ After reading this guide, you will know: * How to contribute to the Ruby on Rails documentation. * How to contribute to the Ruby on Rails code. -Ruby on Rails is not "someone else's framework." Over the years, thousands 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. +Ruby on Rails is not "someone else's framework". Over the years, thousands 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' 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](https://rubyonrails.org/conduct/). @@ -76,7 +76,7 @@ a patch, please send an email to the [rails-core mailing list](https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core). You might get no response, which means that everyone is indifferent. You might find someone who's also interested in building that feature. You might get a "This -won't be accepted." But it's the proper place to discuss new ideas. GitHub +won't be accepted". But it's the proper place to discuss new ideas. GitHub Issues are not a particularly good venue for the sometimes long and involved discussions new features require. @@ -139,7 +139,7 @@ changes to the master branch. When working with documentation, please take into account the [API Documentation Guidelines](api_documentation_guidelines.html) and the [Ruby on Rails Guides Guidelines](ruby_on_rails_guides_guidelines.html). -NOTE: To help our CI servers you should add [ci skip] to your documentation commit message to skip build on that commit. Please remember to use it for commits containing only documentation changes. +NOTE: For documentation changes, your commit message should include [ci skip]. This will skip running the test suite, helping us to cut down on our server costs. Keep in mind that you should only skip CI when your change touches documentation exclusively. Translating Rails Guides ------------------------ diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml index 90674e8456..da11236064 100644 --- a/guides/source/documents.yaml +++ b/guides/source/documents.yaml @@ -139,9 +139,13 @@ url: initialization.html description: This guide explains the internals of the Rails initialization process. - - name: Autoloading and Reloading Constants + name: Autoloading and Reloading Constants (Zeitwerk Mode) url: autoloading_and_reloading_constants.html - description: This guide documents how autoloading and reloading constants work. + description: This guide documents how autoloading and reloading constants work (Zeitwerk mode). + - + name: Autoloading and Reloading Constants (Classic Mode) + url: autoloading_and_reloading_constants_classic_mode.html + description: This guide documents how autoloading and reloading constants work (Classic mode). - name: "Caching with Rails: An Overview" url: caching_with_rails.html @@ -198,7 +202,7 @@ - name: Contributing to Ruby on Rails url: contributing_to_ruby_on_rails.html - description: Rails is not 'somebody else's framework.' This guide covers a variety of ways that you can get involved in the ongoing development of Rails. + description: Rails is not "someone else's framework". This guide covers a variety of ways that you can get involved in the ongoing development of Rails. - name: API Documentation Guidelines url: api_documentation_guidelines.html diff --git a/guides/source/engines.md b/guides/source/engines.md index 90b08b00f0..8961a079b5 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -220,7 +220,7 @@ Inside the `app` directory are the standard `assets`, `controllers`, `helpers`, `jobs`, `mailers`, `models`, and `views` directories that you should be familiar with from an application. We'll look more into models in a future section, when we're writing the engine. -Within the `app/assets` directory, there are the `images`, `javascripts` and +Within the `app/assets` directory, there are the `images` and `stylesheets` directories which, again, you should be familiar with due to their similarity to an application. One difference here, however, is that each directory contains a sub-directory with the engine name. Because this engine is diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index e8b224a1a3..ce45dbb2a7 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -28,7 +28,7 @@ curve diving straight into Rails. There are several curated lists of online reso for learning Ruby: * [Official Ruby Programming Language website](https://www.ruby-lang.org/en/documentation/) -* [List of Free Programming Books](https://github.com/vhf/free-programming-books/blob/master/free-programming-books.md#ruby) +* [List of Free Programming Books](https://github.com/EbookFoundation/free-programming-books/blob/master/free-programming-books.md#ruby) Be aware that some resources, while still excellent, cover versions of Ruby as old as 1.6, and commonly 1.8, and will not include some syntax that you will see in day-to-day @@ -55,7 +55,7 @@ The Rails philosophy includes two major guiding principles: * **Don't Repeat Yourself:** DRY is a principle of software development which states that "Every piece of knowledge must have a single, unambiguous, authoritative - representation within a system." By not writing the same information over and over + representation within a system". By not writing the same information over and over again, our code is more maintainable, more extensible, and less buggy. * **Convention Over Configuration:** Rails has opinions about the best way to do many things in a web application, and defaults to this set of conventions, rather than diff --git a/guides/source/initialization.md b/guides/source/initialization.md index c41eae18cf..556c85cc0f 100644 --- a/guides/source/initialization.md +++ b/guides/source/initialization.md @@ -108,6 +108,8 @@ A standard Rails application depends on several gems, specifically: * activerecord * activestorage * activesupport +* actionmailbox +* actiontext * arel * builder * bundler @@ -160,8 +162,8 @@ namespace and executes the command if found. If Rails doesn't recognize the command, it hands the reins over to Rake to run a task of the same name. -As shown, `Rails::Command` displays the help output automatically if the `args` -are empty. +As shown, `Rails::Command` displays the help output automatically if the `namespace` +is empty. ```ruby module Rails::Command @@ -289,7 +291,7 @@ def default_options environment: (ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development").dup, daemonize: false, caching: nil, - pid: Options::DEFAULT_PID_PATH, + pid: ENV.fetch("PIDFILE", Options::DEFAULT_PIDFILE).dup, restart_cmd: restart_command) end ``` @@ -538,6 +540,8 @@ require "rails" action_mailer/railtie active_job/railtie action_cable/engine + action_mailbox/engine + action_text/engine rails/test_unit/railtie sprockets/railtie ).each do |railtie| diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md index 39935cd2ef..ce90a60e36 100644 --- a/guides/source/layouts_and_rendering.md +++ b/guides/source/layouts_and_rendering.md @@ -149,25 +149,6 @@ Rails knows that this view belongs to a different controller because of the embe render template: "products/show" ``` -#### Rendering an Arbitrary File - -The `render` method can also use a view that's entirely outside of your application: - -```ruby -render file: "/u/apps/warehouse_app/current/app/views/products/show" -``` - -The `:file` option takes an absolute file-system path. Of course, you need to have rights -to the view that you're using to render the content. - -NOTE: Using the `:file` option in combination with users input can lead to security problems -since an attacker could use this action to access security sensitive files in your file system. - -NOTE: By default, the file is rendered using the current layout. - -TIP: If you're running Rails on Microsoft Windows, you should use the `:file` option to -render a file, because Windows filenames do not have the same format as Unix filenames. - #### Wrapping it up The above three ways of rendering (rendering another template within the controller, rendering a template within another controller, and rendering an arbitrary file on the file system) are actually variants of the same action. @@ -178,17 +159,9 @@ In fact, in the BooksController class, inside of the update action where we want render :edit render action: :edit render "edit" -render "edit.html.erb" render action: "edit" -render action: "edit.html.erb" render "books/edit" -render "books/edit.html.erb" render template: "books/edit" -render template: "books/edit.html.erb" -render "/path/to/rails/app/views/books/edit" -render "/path/to/rails/app/views/books/edit.html.erb" -render file: "/path/to/rails/app/views/books/edit" -render file: "/path/to/rails/app/views/books/edit.html.erb" ``` Which one you use is really a matter of style and convention, but the rule of thumb is to use the simplest one that makes sense for the code you are writing. @@ -287,6 +260,23 @@ time. NOTE: Unless overridden, your response returned from this render option will be `text/plain`, as that is the default content type of Action Dispatch response. +#### Rendering raw file + +Rails can render a raw file from an absolute path. This is useful for +conditionally rendering static files like error pages. + +```ruby +render file: "#{Rails.root}/public/404.html", layout: false +``` + +This renders the raw file (it doesn't support ERB or other handlers). By +default it is rendered within the current layout. + +WARNING: Using the `:file` option in combination with users input can lead to security problems +since an attacker could use this action to access security sensitive files in your file system. + +TIP: `send_file` is often a faster and better option if a layout isn't required. + #### Options for `render` Calls to the `render` method generally accept five options: @@ -303,7 +293,7 @@ Calls to the `render` method generally accept five options: By default, Rails will serve the results of a rendering operation with the MIME content-type of `text/html` (or `application/json` if you use the `:json` option, or `application/xml` for the `:xml` option.). There are times when you might like to change this, and you can do so by setting the `:content_type` option: ```ruby -render file: filename, content_type: "application/rss" +render template: "feed", content_type: "application/rss" ``` ##### The `:layout` Option diff --git a/guides/source/rails_application_templates.md b/guides/source/rails_application_templates.md index 982df26987..e0e79fc41b 100644 --- a/guides/source/rails_application_templates.md +++ b/guides/source/rails_application_templates.md @@ -82,10 +82,10 @@ end Adds the given source to the generated application's `Gemfile`. -For example, if you need to source a gem from `"http://code.whytheluckystiff.net"`: +For example, if you need to source a gem from `"http://gems.github.com"`: ```ruby -add_source "http://code.whytheluckystiff.net" +add_source "http://gems.github.com" ``` If block is given, gem entries in block are wrapped into the source group. diff --git a/guides/source/security.md b/guides/source/security.md index 22c122d4b9..5bb7a51524 100644 --- a/guides/source/security.md +++ b/guides/source/security.md @@ -1211,4 +1211,4 @@ The security landscape shifts and it is important to keep up to date, because mi * Subscribe to the Rails security [mailing list](https://groups.google.com/forum/#!forum/rubyonrails-security). * [Brakeman - Rails Security Scanner](https://brakemanscanner.org/) - To perform static security analysis for Rails applications. * [Keep up to date on the other application layers](http://secunia.com/) (they have a weekly newsletter, too). -* A [good security blog](https://www.owasp.org) including the [Cross-Site scripting Cheat Sheet](https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet). +* A [good security blog](https://www.owasp.org) including the [Cross-Site scripting Cheat Sheet](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.md). diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 54f014293d..05980d1614 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -184,41 +184,21 @@ That may be handy if you need to preload STIs or configure a custom inflector, f If the application being upgraded autoloads correctly, the project structure should be already mostly compatible. -However, `classic` mode infers file names from missing constant names (`underscore`), whereas `zeitwerk` mode infers constant names from file names (`camelize`). These helpers are not always inverse of each other, in particular if acronyms are involved. For instance, `"FOO".underscore` is `"foo"`, but `"foo".camelize` is `"Foo"`, not `"FOO"`. Compatibility can be checked by setting `classic` mode first temporarily: +However, `classic` mode infers file names from missing constant names (`underscore`), whereas `zeitwerk` mode infers constant names from file names (`camelize`). These helpers are not always inverse of each other, in particular if acronyms are involved. For instance, `"FOO".underscore` is `"foo"`, but `"foo".camelize` is `"Foo"`, not `"FOO"`. -```ruby -# config/application.rb +Compatibility can be checked with the `zeitwerk:check` task: -config.load_defaults "6.0" -config.autoloader = :classic ``` - -and then running - +$ bin/rails zeitwerk:check +Hold on, I am eager loading the application. +All is good! ``` -bin/rails zeitwerk:check -``` - -When all is good, you can delete `config.autoloader = :classic`. #### require_dependency All known use cases of `require_dependency` have been eliminated, you should grep the project and delete them. -In the case of STIs with a hierarchy of more than two levels, you can preload the leaves of the hierarchy in an initializer: - -```ruby -# config/initializers/preload_stis.rb - -# By preloading leaves, the hierarchy is loaded upwards following -# the references to superclasses in the class definitions. -sti_leaves = %w( - app/models/leaf1.rb - app/models/leaf2.rb - app/models/leaf3.rb -) -Rails.autoloaders.main.preload(sti_leaves) -``` +If your application has STIs, please check their section in the guide [Autoloading and Reloading Constants (Zeitwerk Mode)](autoloading_and_reloading_constants.html#single-table-inheritance). #### Qualified names in class and module definitions @@ -270,6 +250,16 @@ In that case, `app/models/concerns` is assumed to be a root directory (because i The `Concerns::` namespace worked with the classic autoloader as a side-effect of the implementation, but it was not really an intended behavior. An application using `Concerns::` needs to rename those classes and modules to be able to run in `zeitwerk` mode. +#### Having `app` in the autoload paths + +Some projects want something like `app/api/base.rb` to define `API::Base`, and add `app` to the autoload paths to accomplish that in `classic` mode. Since Rails adds all subdirectories of `app` to the autoload paths automatically, we have another situation in which there are nested root directories, so that setup no longer works. Similar principle we explained above with `concerns`. + +If you want to keep that structure, you'll need to delete the subdirectory from the autoload paths in an initializer: + +```ruby +ActiveSupport::Dependencies.autoload_paths.delete("#{Rails.root}/app/api") +``` + #### Autoloaded Constants and Explicit Namespaces If a namespace is defined in a file, as `Hotel` is here: @@ -391,6 +381,12 @@ To fix this, just remove the wildcards: config.autoload_paths << "#{config.root}/lib" ``` +#### Eager loading and autoloading are consistent + +In `classic` mode, if `app/models/foo.rb` defines `Bar`, you won't be able to autoload that file, but eager loading will work because it loads files recursively blindly. This can be a source of errors if you test things first eager loading, execution may fail later autoloading. + +In `zeitwerk` mode both loading modes are consistent, they fail and err in the same files. + #### How to Use the Classic Autoloader in Rails 6 Applications can load Rails 6 defaults and still use the classic autoloader by setting `config.autoloader` this way: @@ -402,6 +398,54 @@ config.load_defaults "6.0" config.autoloader = :classic ``` +### Active Storage assignment behavior change + +In Rails 5.2, assigning to a collection of attachments declared with `has_many_attached` appended new files: + +```ruby +class User < ApplicationRecord + has_many_attached :highlights +end + +user.highlights.attach(filename: "funky.jpg", ...) +user.higlights.count # => 1 + +blob = ActiveStorage::Blob.create_after_upload!(filename: "town.jpg", ...) +user.update!(highlights: [ blob ]) + +user.highlights.count # => 2 +user.highlights.first.filename # => "funky.jpg" +user.highlights.second.filename # => "town.jpg" +``` + +With the default configuration for Rails 6.0, assigning to a collection of attachments replaces existing files +instead of appending to them. This matches Active Record behavior when assigning to a collection association: + +```ruby +user.highlights.attach(filename: "funky.jpg", ...) +user.highlights.count # => 1 + +blob = ActiveStorage::Blob.create_after_upload!(filename: "town.jpg", ...) +user.update!(highlights: [ blob ]) + +user.highlights.count # => 1 +user.highlights.first.filename # => "town.jpg" +``` + +`#attach` can be used to add new attachments without removing the existing ones: + +```ruby +blob = ActiveStorage::Blob.create_after_upload!(filename: "town.jpg", ...) +user.highlights.attach(blob) + +user.highlights.count # => 2 +user.highlights.first.filename # => "funky.jpg" +user.highlights.second.filename # => "town.jpg" +``` + +Opt in to the new default behavior by setting `config.active_storage.replace_on_assign_to_many` to `true`. +The old behavior will be deprecated in Rails 6.1 and removed in a subsequent release. + Upgrading from Rails 5.1 to Rails 5.2 ------------------------------------- diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md index 7bc7391f9e..cfb30719da 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -1,3 +1,5 @@ +* Support using environment variable to set pidfile + *Ben Thorner* Please check [6-0-stable](https://github.com/rails/rails/blob/6-0-stable/railties/CHANGELOG.md) for previous changes. diff --git a/railties/lib/rails.rb b/railties/lib/rails.rb index 1f533a8c04..440d2953c3 100644 --- a/railties/lib/rails.rb +++ b/railties/lib/rails.rb @@ -5,7 +5,6 @@ require "rails/ruby_version_check" require "pathname" require "active_support" -require "active_support/dependencies/autoload" require "active_support/core_ext/kernel/reporting" require "active_support/core_ext/module/delegation" require "active_support/core_ext/array/extract_options" diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index 038284ebdd..cbaab6cc33 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -270,7 +270,9 @@ module Rails "action_dispatch.use_cookies_with_metadata" => config.action_dispatch.use_cookies_with_metadata, "action_dispatch.content_security_policy" => config.content_security_policy, "action_dispatch.content_security_policy_report_only" => config.content_security_policy_report_only, - "action_dispatch.content_security_policy_nonce_generator" => config.content_security_policy_nonce_generator + "action_dispatch.content_security_policy_nonce_generator" => config.content_security_policy_nonce_generator, + "action_dispatch.content_security_policy_nonce_directives" => config.content_security_policy_nonce_directives, + "action_dispatch.feature_policy" => config.feature_policy, ) end end @@ -501,7 +503,6 @@ module Rails end protected - alias :build_middleware_stack :app def run_tasks_blocks(app) #:nodoc: @@ -581,7 +582,6 @@ module Rails end private - def generate_development_secret if secrets.secret_key_base.nil? key_file = Rails.root.join("tmp/development_secret.txt") @@ -623,7 +623,6 @@ module Rails end private - def convert_key(key) unless key.kind_of?(Symbol) ActiveSupport::Deprecation.warn(<<~MESSAGE.squish) diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index da1c433e52..934578e9f1 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -18,8 +18,8 @@ module Rails :session_options, :time_zone, :reload_classes_only_on_change, :beginning_of_week, :filter_redirect, :x, :enable_dependency_loading, :read_encrypted_secrets, :log_level, :content_security_policy_report_only, - :content_security_policy_nonce_generator, :require_master_key, :credentials, - :disable_sandbox, :add_autoload_paths_to_load_path + :content_security_policy_nonce_generator, :content_security_policy_nonce_directives, + :require_master_key, :credentials, :disable_sandbox, :add_autoload_paths_to_load_path attr_reader :encoding, :api_only, :loaded_config_version, :autoloader @@ -60,6 +60,7 @@ module Rails @content_security_policy = nil @content_security_policy_report_only = false @content_security_policy_nonce_generator = nil + @content_security_policy_nonce_directives = nil @require_master_key = false @loaded_config_version = nil @credentials = ActiveSupport::OrderedOptions.new @@ -68,6 +69,7 @@ module Rails @autoloader = :classic @disable_sandbox = false @add_autoload_paths_to_load_path = true + @feature_policy = nil end def load_defaults(target_version) @@ -129,6 +131,7 @@ module Rails if respond_to?(:action_dispatch) action_dispatch.use_cookies_with_metadata = true + action_dispatch.return_only_media_type_on_content_type = false end if respond_to?(:action_mailer) @@ -142,6 +145,8 @@ module Rails if respond_to?(:active_storage) active_storage.queues.analysis = :active_storage_analysis active_storage.queues.purge = :active_storage_purge + + active_storage.replace_on_assign_to_many = true end if respond_to?(:active_record) @@ -207,7 +212,7 @@ module Rails yaml = Pathname.new(path) erb = DummyERB.new(yaml.read) - YAML.load(erb.result) + YAML.load(erb.result) || {} else {} end @@ -299,6 +304,14 @@ module Rails end end + def feature_policy(&block) + if block_given? + @feature_policy = ActionDispatch::FeaturePolicy.new(&block) + else + @feature_policy + end + end + def autoloader=(autoloader) case autoloader when :classic diff --git a/railties/lib/rails/application/default_middleware_stack.rb b/railties/lib/rails/application/default_middleware_stack.rb index 9800b19274..572f51fca2 100644 --- a/railties/lib/rails/application/default_middleware_stack.rb +++ b/railties/lib/rails/application/default_middleware_stack.rb @@ -68,6 +68,7 @@ module Rails unless config.api_only middleware.use ::ActionDispatch::ContentSecurityPolicy::Middleware + middleware.use ::ActionDispatch::FeaturePolicy::Middleware end middleware.use ::Rack::Head @@ -79,7 +80,6 @@ module Rails end private - def load_rack_cache rack_cache = config.action_dispatch.rack_cache return unless rack_cache diff --git a/railties/lib/rails/application/routes_reloader.rb b/railties/lib/rails/application/routes_reloader.rb index 3ecb8e264e..1070362253 100644 --- a/railties/lib/rails/application/routes_reloader.rb +++ b/railties/lib/rails/application/routes_reloader.rb @@ -25,7 +25,6 @@ module Rails end private - def updater @updater ||= ActiveSupport::FileUpdateChecker.new(paths) { reload! } end diff --git a/railties/lib/rails/application_controller.rb b/railties/lib/rails/application_controller.rb index b3fe822218..8c00633515 100644 --- a/railties/lib/rails/application_controller.rb +++ b/railties/lib/rails/application_controller.rb @@ -12,7 +12,6 @@ class Rails::ApplicationController < ActionController::Base # :nodoc: end private - def require_local! unless local_request? render html: "<p>For security purposes, this information is only available to local requests.</p>".html_safe, status: :forbidden diff --git a/railties/lib/rails/command.rb b/railties/lib/rails/command.rb index f09aa3ae0d..7e6e968c92 100644 --- a/railties/lib/rails/command.rb +++ b/railties/lib/rails/command.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true require "active_support" -require "active_support/dependencies/autoload" require "active_support/core_ext/enumerable" require "active_support/core_ext/object/blank" diff --git a/railties/lib/rails/command/spellchecker.rb b/railties/lib/rails/command/spellchecker.rb index 085d5b16df..c5d0253185 100644 --- a/railties/lib/rails/command/spellchecker.rb +++ b/railties/lib/rails/command/spellchecker.rb @@ -13,7 +13,6 @@ module Rails end private - # This code is based directly on the Text gem implementation. # Copyright (c) 2006-2013 Paul Battley, Michael Neumann, Tim Fletcher. # diff --git a/railties/lib/rails/commands/server/server_command.rb b/railties/lib/rails/commands/server/server_command.rb index 982b83ead5..84248e03c1 100644 --- a/railties/lib/rails/commands/server/server_command.rb +++ b/railties/lib/rails/commands/server/server_command.rb @@ -99,7 +99,7 @@ module Rails RACK_SERVERS = %w(cgi fastcgi webrick lsws scgi thin puma unicorn) DEFAULT_PORT = 3000 - DEFAULT_PID_PATH = "tmp/pids/server.pid" + DEFAULT_PIDFILE = "tmp/pids/server.pid" argument :using, optional: true @@ -114,8 +114,8 @@ module Rails desc: "Runs server as a Daemon." class_option :using, aliases: "-u", type: :string, desc: "Specifies the Rack server used to run the application (thin/puma/webrick).", banner: :name - class_option :pid, aliases: "-P", type: :string, default: DEFAULT_PID_PATH, - desc: "Specifies the PID file." + class_option :pid, aliases: "-P", type: :string, + desc: "Specifies the PID file - defaults to #{DEFAULT_PIDFILE}." class_option :dev_caching, aliases: "-C", type: :boolean, default: nil, desc: "Specifies whether to perform caching in development." class_option :restart, type: :boolean, default: nil, hide: true @@ -207,6 +207,7 @@ module Rails end user_supplied_options << :Host if ENV["HOST"] || ENV["BINDING"] user_supplied_options << :Port if ENV["PORT"] + user_supplied_options << :pid if ENV["PIDFILE"] user_supplied_options.uniq end end @@ -253,7 +254,7 @@ module Rails end def pid - File.expand_path(options[:pid]) + File.expand_path(options[:pid] || ENV.fetch("PIDFILE", DEFAULT_PIDFILE)) end def self.banner(*) @@ -261,7 +262,7 @@ module Rails end def prepare_restart - FileUtils.rm_f(options[:pid]) if options[:restart] + FileUtils.rm_f(pid) if options[:restart] end def deprecate_positional_rack_server_and_rewrite_to_option(original_options) diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index d1b8c7803f..46f1d38b96 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -654,14 +654,12 @@ module Rails end protected - def run_tasks_blocks(*) #:nodoc: super paths["lib/tasks"].existent.sort.each { |ext| load(ext) } end private - def load_config_initializer(initializer) # :doc: ActiveSupport::Notifications.instrument("load_config_initializer.railties", initializer: initializer) do load(initializer) diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index 0be00d5151..436315ce1e 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -6,8 +6,6 @@ $:.unshift(activesupport_path) if File.directory?(activesupport_path) && !$:.inc require "thor/group" require "rails/command" -require "active_support" -require "active_support/core_ext/object/blank" require "active_support/core_ext/kernel/singleton_class" require "active_support/core_ext/array/extract_options" require "active_support/core_ext/hash/deep_merge" @@ -287,7 +285,6 @@ module Rails end private - def print_list(base, namespaces) # :doc: namespaces = namespaces.reject { |n| hidden_namespaces.include?(n) } super diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index 1a5f2ff203..b6225cd8c0 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -40,8 +40,7 @@ module Rails in_root do str = "gem #{parts.join(", ")}" str = indentation + str - str = "\n" + str - append_file "Gemfile", str, verbose: false + append_file_with_newline "Gemfile", str, verbose: false end end @@ -58,9 +57,9 @@ module Rails log :gemfile, "group #{str}" in_root do - append_file "Gemfile", "\ngroup #{str} do", force: true + append_file_with_newline "Gemfile", "\ngroup #{str} do", force: true with_indentation(&block) - append_file "Gemfile", "\nend\n", force: true + append_file_with_newline "Gemfile", "end", force: true end end @@ -71,9 +70,13 @@ module Rails log :github, "github #{str}" in_root do - append_file "Gemfile", "\n#{indentation}github #{str} do", force: true + if @indentation.zero? + append_file_with_newline "Gemfile", "\ngithub #{str} do", force: true + else + append_file_with_newline "Gemfile", "#{indentation}github #{str} do", force: true + end with_indentation(&block) - append_file "Gemfile", "\n#{indentation}end", force: true + append_file_with_newline "Gemfile", "#{indentation}end", force: true end end @@ -91,9 +94,9 @@ module Rails in_root do if block - append_file "Gemfile", "\nsource #{quote(source)} do", force: true + append_file_with_newline "Gemfile", "\nsource #{quote(source)} do", force: true with_indentation(&block) - append_file "Gemfile", "\nend\n", force: true + append_file_with_newline "Gemfile", "end", force: true else prepend_file "Gemfile", "source #{quote(source)}\n", verbose: false end @@ -268,7 +271,6 @@ module Rails end private - # Define log for backwards compatibility. If just one argument is sent, # invoke say, otherwise invoke say_status. Differently from say and # similarly to say_status, this method respects the quiet? option given. @@ -345,6 +347,13 @@ module Rails ensure @indentation -= 1 end + + # Append string to a file with a newline if necessary + def append_file_with_newline(path, str, options = {}) + gsub_file path, /\n?\z/, options do |match| + match.end_with?("\n") ? "" : "\n#{str}\n" + end + end end end end diff --git a/railties/lib/rails/generators/actions/create_migration.rb b/railties/lib/rails/generators/actions/create_migration.rb index 05bc242447..67a8139cd3 100644 --- a/railties/lib/rails/generators/actions/create_migration.rb +++ b/railties/lib/rails/generators/actions/create_migration.rb @@ -40,7 +40,6 @@ module Rails alias :exists? :existing_migration private - def on_conflict_behavior # :doc: options = base.options.merge(config) if identical? diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index 303073d867..dbfb7337f0 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -108,7 +108,6 @@ module Rails end private - def gemfile_entry(name, *args) # :doc: options = args.extract_options! version = args.first diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb index 5523a3f659..a153923ce3 100644 --- a/railties/lib/rails/generators/base.rb +++ b/railties/lib/rails/generators/base.rb @@ -20,6 +20,8 @@ module Rails class_option :skip_namespace, type: :boolean, default: false, desc: "Skip namespace (affects only isolated applications)" + class_option :skip_collision_check, type: :boolean, default: false, + desc: "Skip collision check" add_runtime_options! strict_args_position! @@ -245,11 +247,11 @@ module Rails end private - # Check whether the given class names are already taken by user # application or Ruby on Rails. def class_collisions(*class_names) return unless behavior == :invoke + return if options.skip_collision_check? class_names.flatten.each do |class_name| class_name = class_name.to_s @@ -262,8 +264,8 @@ module Rails if last && last.const_defined?(last_name.camelize, false) raise Error, "The name '#{class_name}' is either already used in your application " \ - "or reserved by Ruby on Rails. Please choose an alternative and run " \ - "this generator again." + "or reserved by Ruby on Rails. Please choose an alternative or use --skip-collision-check " \ + "to skip this check and run this generator again." end end end diff --git a/railties/lib/rails/generators/erb.rb b/railties/lib/rails/generators/erb.rb index ba20bcd32a..aab2d634d3 100644 --- a/railties/lib/rails/generators/erb.rb +++ b/railties/lib/rails/generators/erb.rb @@ -6,7 +6,6 @@ module Erb # :nodoc: module Generators # :nodoc: class Base < Rails::Generators::NamedBase #:nodoc: private - def formats [format] end diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb index 997602cb8c..f66be1ee44 100644 --- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb @@ -29,7 +29,6 @@ module Erb # :nodoc: end private - def formats [:text, :html] end diff --git a/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb index 2fc04e4094..6d3bccab0b 100644 --- a/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb +++ b/railties/lib/rails/generators/erb/scaffold/scaffold_generator.rb @@ -24,7 +24,6 @@ module Erb # :nodoc: end private - def available_views %w(index edit show new _form) end diff --git a/railties/lib/rails/generators/generated_attribute.rb b/railties/lib/rails/generators/generated_attribute.rb index 1a80e71eae..4e348be9be 100644 --- a/railties/lib/rails/generators/generated_attribute.rb +++ b/railties/lib/rails/generators/generated_attribute.rb @@ -39,7 +39,6 @@ module Rails end private - # parse possible attribute options like :limit for string/text/binary/integer, :precision/:scale for decimals or :polymorphic for references/belongs_to # when declaring options curly brackets should be used def parse_type_and_options(type) diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index 578881d1ac..ea3968bf39 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -497,7 +497,6 @@ module Rails # :startdoc: private - # Define file as an alias to create_file for backwards compatibility. def file(*args, &block) create_file(*args, &block) @@ -542,7 +541,6 @@ module Rails end private - def handle_version_request!(argument) if ["--version", "-v"].include?(argument) require "rails/version" diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/content_security_policy.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/content_security_policy.rb.tt index c517b0f96b..3d468f7633 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/content_security_policy.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/content_security_policy.rb.tt @@ -23,6 +23,9 @@ # If you are using UJS then enable automatic nonce generation # Rails.application.config.content_security_policy_nonce_generator = -> request { SecureRandom.base64(16) } +# Set the nonce only to specific directives +# Rails.application.config.content_security_policy_nonce_directives = %w(script-src) + # Report CSP violations to a specified URI # For further information see the following documentation: # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy-Report-Only diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/feature_policy.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/feature_policy.rb.tt new file mode 100644 index 0000000000..a1c46695d2 --- /dev/null +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/feature_policy.rb.tt @@ -0,0 +1,11 @@ +# Define an application-wide HTTP feature policy. For further +# information see https://developers.google.com/web/updates/2018/06/feature-policy +# +# Rails.application.config.feature_policy do |f| +# f.camera :none +# f.gyroscope :none +# f.microphone :none +# f.usb :none +# f.fullscreen :self +# f.payment :self, "https://secure.example.com" +# end diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb.tt index 4a994e1e7b..eea99edb65 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/filter_parameter_logging.rb.tt @@ -1,4 +1,6 @@ # Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. -Rails.application.config.filter_parameters += [:password] +Rails.application.config.filter_parameters += [ + :password, :secret, :token, :_key, :auth, :crypt, :salt, :certificate, :otp, :access, :private, :protected, :ssn +] diff --git a/railties/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults_6_0.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults_6_0.rb.tt index d25552e923..ffe53497bf 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults_6_0.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/initializers/new_framework_defaults_6_0.rb.tt @@ -16,6 +16,9 @@ # It's best enabled when your entire app is migrated and stable on 6.0. # Rails.application.config.action_dispatch.use_cookies_with_metadata = true +# Change the return value of `ActionDispatch::Response#content_type` to Content-Type header without modification. +# Rails.application.config.action_dispatch.return_only_media_type_on_content_type = true + # Return false instead of self when enqueuing is aborted from a callback. # Rails.application.config.active_job.return_false_on_aborted_enqueue = true @@ -23,6 +26,10 @@ # Rails.application.config.active_storage.queues.analysis = :active_storage_analysis # Rails.application.config.active_storage.queues.purge = :active_storage_purge +# When assigning to a collection of attachments declared via `has_many_attached`, replace existing +# attachments instead of appending. Use #attach to add new attachments without replacing existing ones. +# Rails.application.config.active_storage.replace_on_assign_to_many = true + # Use ActionMailer::MailDeliveryJob for sending parameterized and normal mail. # # The default delivery jobs (ActionMailer::Parameterized::DeliveryJob, ActionMailer::DeliveryJob), diff --git a/railties/lib/rails/generators/rails/app/templates/config/puma.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/puma.rb.tt index 649253aeca..5ed4437744 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/puma.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/puma.rb.tt @@ -16,6 +16,9 @@ port ENV.fetch("PORT") { 3000 } # environment ENV.fetch("RAILS_ENV") { "development" } +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } + # Specifies the number of `workers` to boot in clustered mode. # Workers are forked web server processes. If using threads and workers together # the concurrency of the application would be max `threads` * `workers`. diff --git a/railties/lib/rails/generators/rails/app/templates/public/robots.txt b/railties/lib/rails/generators/rails/app/templates/public/robots.txt index 37b576a4a0..c19f78ab68 100644 --- a/railties/lib/rails/generators/rails/app/templates/public/robots.txt +++ b/railties/lib/rails/generators/rails/app/templates/public/robots.txt @@ -1 +1 @@ -# See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/railties/lib/rails/generators/rails/controller/controller_generator.rb b/railties/lib/rails/generators/rails/controller/controller_generator.rb index eb75e7e661..88729545f3 100644 --- a/railties/lib/rails/generators/rails/controller/controller_generator.rb +++ b/railties/lib/rails/generators/rails/controller/controller_generator.rb @@ -25,7 +25,6 @@ module Rails end private - def file_name @_file_name ||= remove_possible_suffix(super) end diff --git a/railties/lib/rails/generators/rails/generator/generator_generator.rb b/railties/lib/rails/generators/rails/generator/generator_generator.rb index 747acd68d1..b0146641b4 100644 --- a/railties/lib/rails/generators/rails/generator/generator_generator.rb +++ b/railties/lib/rails/generators/rails/generator/generator_generator.rb @@ -15,7 +15,6 @@ module Rails hook_for :test_framework private - def generator_dir if options[:namespace] File.join("lib", "generators", regular_class_path, file_name) diff --git a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb index 895b3b2e92..4c18bdb430 100644 --- a/railties/lib/rails/generators/rails/plugin/plugin_generator.rb +++ b/railties/lib/rails/generators/rails/plugin/plugin_generator.rb @@ -269,7 +269,6 @@ task default: :test end private - def create_dummy_app(path = nil) dummy_path(path) if path diff --git a/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb b/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb index e1ca54ec91..b2cdeee6d1 100644 --- a/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb +++ b/railties/lib/rails/generators/rails/scaffold_controller/scaffold_controller_generator.rb @@ -34,7 +34,6 @@ module Rails end private - def permitted_params attachments, others = attributes_names.partition { |name| attachments?(name) } params = others.map { |name| ":#{name}" } diff --git a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb.tt b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb.tt index ff41fef9e9..a69a24e281 100644 --- a/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb.tt +++ b/railties/lib/rails/generators/test_unit/controller/templates/functional_test.rb.tt @@ -16,7 +16,7 @@ class <%= class_name %>ControllerTest < ActionDispatch::IntegrationTest get <%= url_helper_prefix %>_<%= action %>_url assert_response :success end - +<%= "\n" unless action == actions.last -%> <% end -%> <% end -%> end diff --git a/railties/lib/rails/generators/test_unit/generator/generator_generator.rb b/railties/lib/rails/generators/test_unit/generator/generator_generator.rb index 19be4f2f51..ae7e28580e 100644 --- a/railties/lib/rails/generators/test_unit/generator/generator_generator.rb +++ b/railties/lib/rails/generators/test_unit/generator/generator_generator.rb @@ -15,7 +15,6 @@ module TestUnit # :nodoc: end private - def generator_path if options[:namespace] File.join("generators", regular_class_path, file_name, "#{file_name}_generator") diff --git a/railties/lib/rails/generators/test_unit/integration/integration_generator.rb b/railties/lib/rails/generators/test_unit/integration/integration_generator.rb index ba27ed329b..86fea3f677 100644 --- a/railties/lib/rails/generators/test_unit/integration/integration_generator.rb +++ b/railties/lib/rails/generators/test_unit/integration/integration_generator.rb @@ -12,7 +12,6 @@ module TestUnit # :nodoc: end private - def file_name @_file_name ||= super.sub(/_test\z/i, "") end diff --git a/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb index 26002a0704..a4bc81cad6 100644 --- a/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb +++ b/railties/lib/rails/generators/test_unit/scaffold/scaffold_generator.rb @@ -38,7 +38,6 @@ module TestUnit # :nodoc: end private - def attributes_string attributes_hash.map { |k, v| "#{k}: #{v}" }.join(", ") end diff --git a/railties/lib/rails/generators/testing/behaviour.rb b/railties/lib/rails/generators/testing/behaviour.rb index ec29ad12ba..a092faec89 100644 --- a/railties/lib/rails/generators/testing/behaviour.rb +++ b/railties/lib/rails/generators/testing/behaviour.rb @@ -88,7 +88,6 @@ module Rails end private - def destination_root_is_set? raise "You need to configure your Rails::Generators::TestCase destination root." unless destination_root end diff --git a/railties/lib/rails/info_controller.rb b/railties/lib/rails/info_controller.rb index f74d979721..d51010d422 100644 --- a/railties/lib/rails/info_controller.rb +++ b/railties/lib/rails/info_controller.rb @@ -33,7 +33,6 @@ class Rails::InfoController < Rails::ApplicationController # :nodoc: end private - def match_route _routes.routes.select { |route| yield route.path diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb index 8367ac8980..838fe55acc 100644 --- a/railties/lib/rails/paths.rb +++ b/railties/lib/rails/paths.rb @@ -98,7 +98,6 @@ module Rails end private - def filter_by(&block) all_paths.find_all(&block).flat_map { |path| paths = path.existent @@ -223,7 +222,6 @@ module Rails alias to_a expanded private - def files_in(path) Dir.chdir(path) do files = Dir.glob(@glob) diff --git a/railties/lib/rails/rack/logger.rb b/railties/lib/rails/rack/logger.rb index 3a95b55811..8d69663dbd 100644 --- a/railties/lib/rails/rack/logger.rb +++ b/railties/lib/rails/rack/logger.rb @@ -30,7 +30,6 @@ module Rails end private - def call_app(request, env) # :doc: instrumenter = ActiveSupport::Notifications.instrumenter instrumenter.start "request.action_dispatch", request: request diff --git a/railties/lib/rails/railtie.rb b/railties/lib/rails/railtie.rb index a67b90e285..178c584f95 100644 --- a/railties/lib/rails/railtie.rb +++ b/railties/lib/rails/railtie.rb @@ -228,7 +228,6 @@ module Rails end protected - def run_console_blocks(app) #:nodoc: each_registered_block(:console) { |block| block.call(app) } end @@ -247,7 +246,6 @@ module Rails end private - # run `&block` in every registered block in `#register_block_for` def each_registered_block(type, &block) klass = self.class diff --git a/railties/lib/rails/railtie/configurable.rb b/railties/lib/rails/railtie/configurable.rb index 7f42fae10a..ba14089a2a 100644 --- a/railties/lib/rails/railtie/configurable.rb +++ b/railties/lib/rails/railtie/configurable.rb @@ -27,7 +27,6 @@ module Rails end private - def method_missing(*args, &block) instance.send(*args, &block) end diff --git a/railties/lib/rails/railtie/configuration.rb b/railties/lib/rails/railtie/configuration.rb index 70274b948c..c90fcac51a 100644 --- a/railties/lib/rails/railtie/configuration.rb +++ b/railties/lib/rails/railtie/configuration.rb @@ -87,7 +87,6 @@ module Rails end private - def method_missing(name, *args, &blk) if name.to_s =~ /=$/ @@options[$`.to_sym] = args.first diff --git a/railties/lib/rails/source_annotation_extractor.rb b/railties/lib/rails/source_annotation_extractor.rb index 9ce22b96a6..77a99036ec 100644 --- a/railties/lib/rails/source_annotation_extractor.rb +++ b/railties/lib/rails/source_annotation_extractor.rb @@ -2,11 +2,6 @@ require "active_support/deprecation" -# Remove this deprecated class in the next minor version -#:nodoc: -SourceAnnotationExtractor = ActiveSupport::Deprecation::DeprecatedConstantProxy. - new("SourceAnnotationExtractor", "Rails::SourceAnnotationExtractor") - module Rails # Implements the logic behind <tt>Rails::Command::NotesCommand</tt>. See <tt>rails notes --help</tt> for usage information. # @@ -160,3 +155,8 @@ module Rails end end end + +# Remove this deprecated class in the next minor version +#:nodoc: +SourceAnnotationExtractor = ActiveSupport::Deprecation::DeprecatedConstantProxy. + new("SourceAnnotationExtractor", "Rails::SourceAnnotationExtractor") diff --git a/railties/lib/rails/tasks/zeitwerk.rake b/railties/lib/rails/tasks/zeitwerk.rake index e748a479a7..5421af6e8b 100644 --- a/railties/lib/rails/tasks/zeitwerk.rake +++ b/railties/lib/rails/tasks/zeitwerk.rake @@ -1,62 +1,14 @@ # frozen_string_literal: true -indent = " " * 2 - -ensure_classic_mode = ->() do - if Rails.autoloaders.zeitwerk_enabled? - abort <<~EOS - Please, enable temporarily :classic mode: - - # config/application.rb - config.autoloader = :classic - - and try again. When all is good, you can delete that line. - EOS +ensure_zeitwerk_mode = ->() do + unless Rails.autoloaders.zeitwerk_enabled? + abort "Please, enable :zeitwerk mode in config/application.rb and try again." end end eager_load = ->() do - Rails.configuration.eager_load_namespaces.each(&:eager_load!) -end - -check_directory = ->(directory, parent, mismatches) do - # test/mailers/previews might not exist. - return unless File.exist?(directory) - - Dir.foreach(directory) do |entry| - next if entry.start_with?(".") - next if parent == Object && entry == "concerns" - - abspath = File.join(directory, entry) - - if File.directory?(abspath) || abspath.end_with?(".rb") - print "." - cname = File.basename(abspath, ".rb").camelize.to_sym - if parent.const_defined?(cname, false) - if File.directory?(abspath) - check_directory[abspath, parent.const_get(cname), mismatches] - end - else - mismatches << [abspath, parent, cname] - end - end - end -end - -report_mismatches = ->(mismatches) do - puts - rails_root_prefix_re = %r{\A#{Regexp.escape(Rails.root.to_path)}/} - mismatches.each do |abspath, parent, cname| - relpath = abspath.sub(rails_root_prefix_re, "") - cpath = parent == Object ? cname : "#{parent.name}::#{cname}" - puts indent + "Mismatch: Expected #{relpath} to define #{cpath}" - end - puts - - puts <<~EOS - Please revise the reported mismatches. You can normally fix them by adding - acronyms to config/initializers/inflections.rb or renaming the constants. - EOS + puts "Hold on, I am eager loading the application." + Zeitwerk::Loader.eager_load_all end report_not_checked = ->(not_checked) do @@ -67,47 +19,48 @@ report_not_checked = ->(not_checked) do EOS puts - not_checked.each { |dir| puts indent + dir } + not_checked.each { |dir| puts " #{dir}" } puts puts <<~EOS You may verify them manually, or add them to config.eager_load_paths in config/application.rb and run zeitwerk:check again. EOS + puts end -report = ->(mismatches, not_checked) do - puts - if mismatches.empty? && not_checked.empty? - puts "All is good!" - puts "Please, remember to delete `config.autoloader = :classic` from config/application.rb." +report = ->(not_checked) do + if not_checked.any? + report_not_checked[not_checked] + puts "Otherwise, all is good!" else - report_mismatches[mismatches] if mismatches.any? - report_not_checked[not_checked] if not_checked.any? + puts "All is good!" end end namespace :zeitwerk do desc "Checks project structure for Zeitwerk compatibility" task check: :environment do - ensure_classic_mode[] - eager_load[] + ensure_zeitwerk_mode[] + + begin + eager_load[] + rescue NameError => e + if e.message =~ /expected file .*? to define constant \S+/ + abort $&.sub(/#{Regexp.escape(Rails.root.to_s)}./, "") + else + raise + end + end eager_load_paths = Rails.configuration.eager_load_namespaces.map do |eln| eln.config.eager_load_paths if eln.respond_to?(:config) end.compact.flatten - mismatches = [] - - $stdout.sync = true - eager_load_paths.each do |eager_load_path| - check_directory[eager_load_path, Object, mismatches] - end - not_checked = ActiveSupport::Dependencies.autoload_paths - eager_load_paths not_checked.select! { |dir| Dir.exist?(dir) } not_checked.reject! { |dir| Dir.empty?(dir) } - report[mismatches, not_checked] + report[not_checked] end end diff --git a/railties/test/application/assets_test.rb b/railties/test/application/assets_test.rb index a80581211b..a7dd233f3d 100644 --- a/railties/test/application/assets_test.rb +++ b/railties/test/application/assets_test.rb @@ -491,7 +491,6 @@ module ApplicationTests end private - def app_with_assets_in_view app_file "app/assets/javascripts/application.js", "//= require_tree ." app_file "app/assets/javascripts/xmlhr.js", "function f1() { alert(); }" diff --git a/railties/test/application/bin_setup_test.rb b/railties/test/application/bin_setup_test.rb index aa0da0931d..d84ab61cf9 100644 --- a/railties/test/application/bin_setup_test.rb +++ b/railties/test/application/bin_setup_test.rb @@ -31,7 +31,7 @@ module ApplicationTests Dir.chdir(app_path) do # SQLite3 seems to auto-create the database on first checkout. rails "db:system:change", "--to=postgresql" - rails "db:drop" + rails "db:drop", allow_failure: true app_file "db/schema.rb", "" diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 6f9711cb37..96678c395c 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -1793,6 +1793,11 @@ module ApplicationTests assert_equal [X, D], C.descendants end + test "load_database_yaml returns blank hash if configuration file is blank" do + app_file "config/database.yml", "" + app "development" + assert_equal({}, Rails.application.config.load_database_yaml) + end test "raises with proper error message if no database configuration found" do FileUtils.rm("#{app_path}/config/database.yml") @@ -2436,6 +2441,33 @@ module ApplicationTests assert_nil ActiveStorage.queues[:purge] end + test "ActionDispatch::Response.return_only_media_type_on_content_type is false by default" do + app "development" + + assert_equal false, ActionDispatch::Response.return_only_media_type_on_content_type + end + + test "ActionDispatch::Response.return_only_media_type_on_content_type is true in the 5.x defaults" do + remove_from_config '.*config\.load_defaults.*\n' + add_to_config 'config.load_defaults "5.2"' + + app "development" + + assert_equal true, ActionDispatch::Response.return_only_media_type_on_content_type + end + + test "ActionDispatch::Response.return_only_media_type_on_content_type can be configured in the new framework defaults" do + remove_from_config '.*config\.load_defaults.*\n' + + app_file "config/initializers/new_framework_defaults_6_0.rb", <<-RUBY + Rails.application.config.action_dispatch.return_only_media_type_on_content_type = true + RUBY + + app "development" + + assert_equal true, ActionDispatch::Response.return_only_media_type_on_content_type + end + test "ActionMailbox.logger is Rails.logger by default" do app "development" @@ -2561,6 +2593,21 @@ module ApplicationTests MESSAGE end + test "ActiveStorage.draw_routes can be configured via config.active_storage.draw_routes" do + app_file "config/environments/development.rb", <<-RUBY + Rails.application.configure do + config.active_storage.draw_routes = false + end + RUBY + + output = rails("routes") + assert_not_includes(output, "rails_service_blob") + assert_not_includes(output, "rails_blob_representation") + assert_not_includes(output, "rails_disk_service") + assert_not_includes(output, "update_rails_disk_service") + assert_not_includes(output, "rails_direct_uploads") + end + test "hosts include .localhost in development" do app "development" assert_includes Rails.application.config.hosts, ".localhost" diff --git a/railties/test/application/content_security_policy_test.rb b/railties/test/application/content_security_policy_test.rb index 0d28df16f8..0bb6ee917a 100644 --- a/railties/test/application/content_security_policy_test.rb +++ b/railties/test/application/content_security_policy_test.rb @@ -119,6 +119,38 @@ module ApplicationTests assert_policy "default-src 'self' https:", report_only: true end + test "global content security policy nonce directives in an initializer" do + controller :pages, <<-RUBY + class PagesController < ApplicationController + def index + render html: "<h1>Welcome to Rails!</h1>" + end + end + RUBY + + app_file "config/initializers/content_security_policy.rb", <<-RUBY + Rails.application.config.content_security_policy do |p| + p.default_src :self, :https + p.script_src :self, :https + p.style_src :self, :https + end + + Rails.application.config.content_security_policy_nonce_generator = proc { "iyhD0Yc0W+c=" } + Rails.application.config.content_security_policy_nonce_directives = %w(script-src) + RUBY + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + root to: "pages#index" + end + RUBY + + app("development") + + get "/" + assert_policy "default-src 'self' https:; script-src 'self' https: 'nonce-iyhD0Yc0W+c='; style-src 'self' https:" + end + test "override content security policy in a controller" do controller :pages, <<-RUBY class PagesController < ApplicationController @@ -204,7 +236,6 @@ module ApplicationTests end private - def assert_policy(expected, report_only: false) assert_equal 200, last_response.status diff --git a/railties/test/application/feature_policy_test.rb b/railties/test/application/feature_policy_test.rb new file mode 100644 index 0000000000..e751d782ee --- /dev/null +++ b/railties/test/application/feature_policy_test.rb @@ -0,0 +1,191 @@ +# frozen_string_literal: true + +require "isolation/abstract_unit" +require "rack/test" + +module ApplicationTests + class FeaturePolicyTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + include Rack::Test::Methods + + def setup + build_app + end + + def teardown + teardown_app + end + + test "feature policy is not enabled by default" do + controller :pages, <<-RUBY + class PagesController < ApplicationController + def index + render html: "<h1>Welcome to Rails!</h1>" + end + end + RUBY + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + root to: "pages#index" + end + RUBY + + app("development") + + get "/" + assert_nil last_response.headers["Feature-Policy"] + end + + test "global feature policy in an initializer" do + controller :pages, <<-RUBY + class PagesController < ApplicationController + def index + render html: "<h1>Welcome to Rails!</h1>" + end + end + RUBY + + app_file "config/initializers/feature_policy.rb", <<-RUBY + Rails.application.config.feature_policy do |p| + p.geolocation :none + end + RUBY + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + root to: "pages#index" + end + RUBY + + app("development") + + get "/" + assert_policy "geolocation 'none'" + end + + test "override feature policy using same directive in a controller" do + controller :pages, <<-RUBY + class PagesController < ApplicationController + feature_policy do |p| + p.geolocation "https://example.com" + end + + def index + render html: "<h1>Welcome to Rails!</h1>" + end + end + RUBY + + app_file "config/initializers/feature_policy.rb", <<-RUBY + Rails.application.config.feature_policy do |p| + p.geolocation :none + end + RUBY + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + root to: "pages#index" + end + RUBY + + app("development") + + get "/" + assert_policy "geolocation https://example.com" + end + + test "override feature policy by unsetting a directive in a controller" do + controller :pages, <<-RUBY + class PagesController < ApplicationController + feature_policy do |p| + p.geolocation nil + end + + def index + render html: "<h1>Welcome to Rails!</h1>" + end + end + RUBY + + app_file "config/initializers/feature_policy.rb", <<-RUBY + Rails.application.config.feature_policy do |p| + p.geolocation :none + end + RUBY + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + root to: "pages#index" + end + RUBY + + app("development") + + get "/" + assert_equal 200, last_response.status + assert_nil last_response.headers["Feature-Policy"] + end + + test "override feature policy using different directives in a controller" do + controller :pages, <<-RUBY + class PagesController < ApplicationController + feature_policy do |p| + p.geolocation nil + p.payment "https://secure.example.com" + p.autoplay :none + end + + def index + render html: "<h1>Welcome to Rails!</h1>" + end + end + RUBY + + app_file "config/initializers/feature_policy.rb", <<-RUBY + Rails.application.config.feature_policy do |p| + p.geolocation :none + end + RUBY + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + root to: "pages#index" + end + RUBY + + app("development") + + get "/" + assert_policy "payment https://secure.example.com; autoplay 'none'" + end + + test "global feature policy added to rack app" do + app_file "config/initializers/feature_policy.rb", <<-RUBY + Rails.application.config.feature_policy do |p| + p.payment :none + end + RUBY + + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + app = ->(env) { + [200, { "Content-Type" => "text/html" }, ["<p>Hello, World!</p>"]] + } + root to: app + end + RUBY + + app("development") + + get "/" + assert_policy "payment 'none'" + end + + private + def assert_policy(expected) + assert_equal 200, last_response.status + assert_equal expected, last_response.headers["Feature-Policy"] + end + end +end diff --git a/railties/test/application/generators_test.rb b/railties/test/application/generators_test.rb index e5e557d204..8ec26db772 100644 --- a/railties/test/application/generators_test.rb +++ b/railties/test/application/generators_test.rb @@ -198,5 +198,15 @@ module ApplicationTests assert_no_match "active_record:migration", output end end + + test "skip collision check" do + rails("generate", "model", "post", "title:string") + + output = rails("generate", "model", "post", "title:string", "body:string") + assert_match(/The name 'Post' is either already used in your application or reserved/, output) + + output = rails("generate", "model", "post", "title:string", "body:string", "--skip-collision-check") + assert_no_match(/The name 'Post' is either already used in your application or reserved/, output) + end end end diff --git a/railties/test/application/initializers/frameworks_test.rb b/railties/test/application/initializers/frameworks_test.rb index a35247fc43..05978e1d99 100644 --- a/railties/test/application/initializers/frameworks_test.rb +++ b/railties/test/application/initializers/frameworks_test.rb @@ -218,8 +218,9 @@ module ApplicationTests rails %w(generate model post title:string) rails %w(db:migrate db:schema:cache:dump) require "#{app_path}/config/environment" - ActiveRecord::Base.connection.drop_table("posts") # force drop posts table for test. assert ActiveRecord::Base.connection.schema_cache.data_sources("posts") + ensure + ActiveRecord::Base.connection.drop_table("posts", if_exists: true) # force drop posts table for test. end test "expire schema cache dump" do diff --git a/railties/test/application/loading_test.rb b/railties/test/application/loading_test.rb index 9c98489590..9ab400acfc 100644 --- a/railties/test/application/loading_test.rb +++ b/railties/test/application/loading_test.rb @@ -116,7 +116,7 @@ class LoadingTest < ActiveSupport::TestCase RUBY app_file "app/models/post.rb", <<-MODEL - class Post < ActiveRecord::Base + class Post < ApplicationRecord end MODEL @@ -133,11 +133,12 @@ class LoadingTest < ActiveSupport::TestCase require "#{rails_root}/config/environment" setup_ar! - assert_equal [ActiveStorage::Blob, ActiveStorage::Attachment, ActiveRecord::SchemaMigration, ActiveRecord::InternalMetadata].collect(&:to_s).sort, ActiveRecord::Base.descendants.collect(&:to_s).sort + initial = [ActiveStorage::Blob, ActiveStorage::Attachment, ActiveRecord::SchemaMigration, ActiveRecord::InternalMetadata, ApplicationRecord, "primary::SchemaMigration"].collect(&:to_s).sort + assert_equal initial, ActiveRecord::Base.descendants.collect(&:to_s).sort get "/load" - assert_equal [ActiveStorage::Blob, ActiveStorage::Attachment, ActiveRecord::SchemaMigration, ActiveRecord::InternalMetadata, Post].collect(&:to_s).sort, ActiveRecord::Base.descendants.collect(&:to_s).sort + assert_equal [Post].collect(&:to_s).sort, ActiveRecord::Base.descendants.collect(&:to_s).sort - initial get "/unload" - assert_equal [ActiveStorage::Blob, ActiveStorage::Attachment, ActiveRecord::SchemaMigration, ActiveRecord::InternalMetadata].collect(&:to_s).sort, ActiveRecord::Base.descendants.collect(&:to_s).sort + assert_equal ["ActiveRecord::InternalMetadata", "ActiveRecord::SchemaMigration", "primary::SchemaMigration"], ActiveRecord::Base.descendants.collect(&:to_s).sort.uniq end test "initialize cant be called twice" do @@ -454,7 +455,6 @@ class LoadingTest < ActiveSupport::TestCase end private - def setup_ar! ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") ActiveRecord::Migration.verbose = false diff --git a/railties/test/application/middleware_test.rb b/railties/test/application/middleware_test.rb index 54b2e95d75..e93f2f5aa4 100644 --- a/railties/test/application/middleware_test.rb +++ b/railties/test/application/middleware_test.rb @@ -46,6 +46,7 @@ module ApplicationTests "ActionDispatch::Session::CookieStore", "ActionDispatch::Flash", "ActionDispatch::ContentSecurityPolicy::Middleware", + "ActionDispatch::FeaturePolicy::Middleware", "Rack::Head", "Rack::ConditionalGet", "Rack::ETag", @@ -309,7 +310,6 @@ module ApplicationTests end private - def boot! require "#{app_path}/config/environment" end diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb index e08cd09abd..c9931c45a6 100644 --- a/railties/test/application/rake/dbs_test.rb +++ b/railties/test/application/rake/dbs_test.rb @@ -40,6 +40,15 @@ module ApplicationTests end end + def db_create_with_warning(expected_database) + Dir.chdir(app_path) do + output = rails("db:create") + assert_match(/Rails couldn't infer whether you are using multiple databases/, output) + assert_match(/Created database/, output) + assert File.exist?(expected_database) + end + end + test "db:create and db:drop without database URL" do require "#{app_path}/config/environment" db_create_and_drop ActiveRecord::Base.configurations[Rails.env]["database"] @@ -86,6 +95,25 @@ module ApplicationTests db_create_and_drop("db/development.sqlite3", environment_loaded: false) end + test "db:create and db:drop show warning but doesn't raise errors when loading YAML with alias ERB" do + app_file "config/database.yml", <<-YAML + sqlite: &sqlite + adapter: sqlite3 + database: db/development.sqlite3 + + development: + <<: *<%= ENV["DB"] || "sqlite" %> + YAML + + app_file "config/environments/development.rb", <<-RUBY + Rails.application.configure do + config.database = "db/development.sqlite3" + end + RUBY + + db_create_with_warning("db/development.sqlite3") + end + test "db:create and db:drop don't raise errors when loading YAML containing conditional statements in ERB" do app_file "config/database.yml", <<-YAML development: @@ -602,6 +630,22 @@ module ApplicationTests assert_match(/CreateRecipes: migrated/, output) end end + + test "db:prepare does not touch schema when dumping is disabled" do + Dir.chdir(app_path) do + rails "generate", "model", "book", "title:string" + rails "db:create", "db:migrate" + + app_file "db/schema.rb", "Not touched" + app_file "config/initializers/disable_dumping_schema.rb", <<-RUBY + Rails.application.config.active_record.dump_schema_after_migration = false + RUBY + + rails "db:prepare" + + assert_equal("Not touched", File.read("db/schema.rb").strip) + end + end end end end diff --git a/railties/test/application/rake/multi_dbs_test.rb b/railties/test/application/rake/multi_dbs_test.rb index 31ea2246a9..2606e64424 100644 --- a/railties/test/application/rake/multi_dbs_test.rb +++ b/railties/test/application/rake/multi_dbs_test.rb @@ -299,10 +299,56 @@ module ApplicationTests db_migrate_and_schema_cache_dump_and_schema_cache_clear end + test "db:abort_if_pending_migrations works on all databases" do + require "#{app_path}/config/environment" + + app_file "db/animals_migrate/02_two_migration.rb", <<-MIGRATION + class TwoMigration < ActiveRecord::Migration::Current + end + MIGRATION + + output = rails("db:abort_if_pending_migrations", allow_failure: true) + assert_match(/You have 1 pending migration/, output) + end + + test "db:abort_if_pending_migrations:namespace works" do + require "#{app_path}/config/environment" + + app_file "db/animals_migrate/02_two_migration.rb", <<-MIGRATION + class TwoMigration < ActiveRecord::Migration::Current + end + MIGRATION + + output = rails("db:abort_if_pending_migrations:primary") + assert_no_match(/You have \d+ pending migration/, output) + output = rails("db:abort_if_pending_migrations:animals", allow_failure: true) + assert_match(/You have 1 pending migration/, output) + end + test "db:prepare works on all databases" do require "#{app_path}/config/environment" db_prepare end + + test "db:prepare setups missing database without clearing existing one" do + require "#{app_path}/config/environment" + Dir.chdir(app_path) do + # Bug not visible on SQLite3. Can be simplified when https://github.com/rails/rails/issues/36383 resolved + use_postgresql(multi_db: true) + generate_models_for_animals + + rails "db:create:animals", "db:migrate:animals", "db:create:primary", "db:migrate:primary", "db:schema:dump" + rails "db:drop:primary" + Dog.create! + output = rails("db:prepare") + + assert_match(/Created database/, output) + assert_equal 1, Dog.count + ensure + Dog.connection.disconnect! + rails "db:drop" rescue nil + end + end end end end diff --git a/railties/test/application/rake/notes_test.rb b/railties/test/application/rake/notes_test.rb index 60802ef7c4..47822e55b9 100644 --- a/railties/test/application/rake/notes_test.rb +++ b/railties/test/application/rake/notes_test.rb @@ -159,7 +159,6 @@ module ApplicationTests end private - def run_rake_notes(command = "bin/rake notes") Dir.chdir(app_path) do output = `#{command}` diff --git a/railties/test/application/system_test_case_test.rb b/railties/test/application/system_test_case_test.rb new file mode 100644 index 0000000000..d15a0d9210 --- /dev/null +++ b/railties/test/application/system_test_case_test.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true + +require "isolation/abstract_unit" +require "rack/test" + +class SystemTestCaseTest < ActiveSupport::TestCase + include ActiveSupport::Testing::Isolation + + def setup + build_app + end + + def teardown + teardown_app + end + + test "url helpers are delegated to a proxy class" do + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + get 'foo', to: 'foo#index', as: 'test_foo' + end + RUBY + + app("test") + + assert_not_includes(ActionDispatch::SystemTestCase.runnable_methods, :test_foo_url) + end + + test "system tests set the Capybara host in the url_options by default" do + app_file "config/routes.rb", <<-RUBY + Rails.application.routes.draw do + get 'foo', to: 'foo#index', as: 'test_foo' + end + RUBY + + app("test") + system_test = ActionDispatch::SystemTestCase.new("my_test") + previous_app_host = ::Capybara.app_host + ::Capybara.app_host = "https://my_test_example.com" + + assert_equal("https://my_test_example.com/foo", system_test.test_foo_url) + ensure + ::Capybara.app_host = previous_app_host + end +end diff --git a/railties/test/commands/console_test.rb b/railties/test/commands/console_test.rb index f6df2b694a..ee4335e31d 100644 --- a/railties/test/commands/console_test.rb +++ b/railties/test/commands/console_test.rb @@ -116,7 +116,6 @@ class Rails::ConsoleTest < ActiveSupport::TestCase private :output private - def start(argv = []) rails_console = Rails::Console.new(app, parse_arguments(argv)) @output = capture(:stdout) { rails_console.start } diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb index 76a7cd055f..45b72fd909 100644 --- a/railties/test/commands/dbconsole_test.rb +++ b/railties/test/commands/dbconsole_test.rb @@ -275,7 +275,6 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase private :aborted, :output private - def app_db_config(results) Rails.application.config.stub(:database_configuration, results || {}) do yield diff --git a/railties/test/commands/server_test.rb b/railties/test/commands/server_test.rb index b78370a233..c9026e2d95 100644 --- a/railties/test/commands/server_test.rb +++ b/railties/test/commands/server_test.rb @@ -116,6 +116,13 @@ class Rails::Command::ServerCommandTest < ActiveSupport::TestCase end end + def test_environment_with_pidfile + switch_env "PIDFILE", "/tmp/rails.pid" do + options = parse_arguments + assert_equal "/tmp/rails.pid", options[:pid] + end + end + def test_caching_without_option args = [] options = parse_arguments(args) @@ -234,6 +241,12 @@ class Rails::Command::ServerCommandTest < ActiveSupport::TestCase options = parse_arguments(args) assert_equal "127.0.0.1", options[:Host] end + + switch_env "PIDFILE", "/tmp/rails.pid" do + args = ["-P", "/somewhere/else.pid"] + options = parse_arguments(args) + assert_equal "/somewhere/else.pid", options[:pid] + end end def test_records_user_supplied_options @@ -253,6 +266,16 @@ class Rails::Command::ServerCommandTest < ActiveSupport::TestCase server_options = parse_arguments assert_equal [:Host], server_options[:user_supplied_options] end + + switch_env "PORT", "3001" do + server_options = parse_arguments + assert_equal [:Port], server_options[:user_supplied_options] + end + + switch_env "PIDFILE", "/tmp/server.pid" do + server_options = parse_arguments + assert_equal [:pid], server_options[:user_supplied_options] + end end def test_default_options diff --git a/railties/test/configuration/middleware_stack_proxy_test.rb b/railties/test/configuration/middleware_stack_proxy_test.rb index bc72b7f0c9..b67142f4c2 100644 --- a/railties/test/configuration/middleware_stack_proxy_test.rb +++ b/railties/test/configuration/middleware_stack_proxy_test.rb @@ -51,7 +51,6 @@ module Rails end private - def assert_playback(msg_name, args) mock = Minitest::Mock.new mock.expect :send, nil, [msg_name, args] diff --git a/railties/test/env_helpers.rb b/railties/test/env_helpers.rb index 336832b867..e3157e0c77 100644 --- a/railties/test/env_helpers.rb +++ b/railties/test/env_helpers.rb @@ -4,7 +4,6 @@ require "rails" module EnvHelpers private - def with_rails_env(env) Rails.instance_variable_set :@_env, nil switch_env "RAILS_ENV", env do diff --git a/railties/test/generators/actions_test.rb b/railties/test/generators/actions_test.rb index d913bb5438..5d6d7f1595 100644 --- a/railties/test/generators/actions_test.rb +++ b/railties/test/generators/actions_test.rb @@ -43,7 +43,7 @@ class ActionsTest < Rails::Generators::TestCase def test_add_source_adds_source_to_gemfile run_generator action :add_source, "http://gems.github.com" - assert_file "Gemfile", /source 'http:\/\/gems\.github\.com'/ + assert_file "Gemfile", /source 'http:\/\/gems\.github\.com'\n/ end def test_add_source_with_block_adds_source_to_gemfile_with_gem @@ -51,7 +51,7 @@ class ActionsTest < Rails::Generators::TestCase action :add_source, "http://gems.github.com" do gem "rspec-rails" end - assert_file "Gemfile", /source 'http:\/\/gems\.github\.com' do\n gem 'rspec-rails'\nend/ + assert_file "Gemfile", /\n\nsource 'http:\/\/gems\.github\.com' do\n gem 'rspec-rails'\nend\n\z/ end def test_add_source_with_block_adds_source_to_gemfile_after_gem @@ -60,13 +60,25 @@ class ActionsTest < Rails::Generators::TestCase action :add_source, "http://gems.github.com" do gem "rspec-rails" end - assert_file "Gemfile", /gem 'will-paginate'\nsource 'http:\/\/gems\.github\.com' do\n gem 'rspec-rails'\nend/ + assert_file "Gemfile", /\ngem 'will-paginate'\n\nsource 'http:\/\/gems\.github\.com' do\n gem 'rspec-rails'\nend\n\z/ + end + + def test_add_source_should_create_newline_between_blocks + run_generator + action :add_source, "http://gems.github.com" do + gem "rspec-rails" + end + + action :add_source, "http://gems2.github.com" do + gem "fakeweb" + end + assert_file "Gemfile", /\n\nsource 'http:\/\/gems\.github\.com' do\n gem 'rspec-rails'\nend\n\nsource 'http:\/\/gems2\.github\.com' do\n gem 'fakeweb'\nend\n\z/ end def test_gem_should_put_gem_dependency_in_gemfile run_generator action :gem, "will-paginate" - assert_file "Gemfile", /gem 'will\-paginate'/ + assert_file "Gemfile", /gem 'will\-paginate'\n\z/ end def test_gem_with_version_should_include_version_in_gemfile @@ -141,7 +153,7 @@ class ActionsTest < Rails::Generators::TestCase gem "fakeweb" end - assert_file "Gemfile", /\ngroup :development, :test do\n gem 'rspec-rails'\nend\n\ngroup :test do\n gem 'fakeweb'\nend/ + assert_file "Gemfile", /\n\ngroup :development, :test do\n gem 'rspec-rails'\nend\n\ngroup :test do\n gem 'fakeweb'\nend\n\z/ end def test_github_should_create_an_indented_block @@ -153,7 +165,7 @@ class ActionsTest < Rails::Generators::TestCase gem "baz" end - assert_file "Gemfile", /\ngithub 'user\/repo' do\n gem 'foo'\n gem 'bar'\n gem 'baz'\nend/ + assert_file "Gemfile", /\n\ngithub 'user\/repo' do\n gem 'foo'\n gem 'bar'\n gem 'baz'\nend\n\z/ end def test_github_should_create_an_indented_block_with_options @@ -165,7 +177,7 @@ class ActionsTest < Rails::Generators::TestCase gem "baz" end - assert_file "Gemfile", /\ngithub 'user\/repo', a: 'correct', other: true do\n gem 'foo'\n gem 'bar'\n gem 'baz'\nend/ + assert_file "Gemfile", /\n\ngithub 'user\/repo', a: 'correct', other: true do\n gem 'foo'\n gem 'bar'\n gem 'baz'\nend\n\z/ end def test_github_should_create_an_indented_block_within_a_group @@ -177,9 +189,73 @@ class ActionsTest < Rails::Generators::TestCase gem "bar" gem "baz" end + github "user/repo2", a: "correct", other: true do + gem "foo" + gem "bar" + gem "baz" + end + end + + assert_file "Gemfile", /\n\ngroup :magic do\n github 'user\/repo', a: 'correct', other: true do\n gem 'foo'\n gem 'bar'\n gem 'baz'\n end\n github 'user\/repo2', a: 'correct', other: true do\n gem 'foo'\n gem 'bar'\n gem 'baz'\n end\nend\n\z/ + end + + def test_github_should_create_newline_between_blocks + run_generator + + action :github, "user/repo", a: "correct", other: true do + gem "foo" + gem "bar" + gem "baz" + end + + action :github, "user/repo2", a: "correct", other: true do + gem "foo" + gem "bar" + gem "baz" + end + + assert_file "Gemfile", /\n\ngithub 'user\/repo', a: 'correct', other: true do\n gem 'foo'\n gem 'bar'\n gem 'baz'\nend\n\ngithub 'user\/repo2', a: 'correct', other: true do\n gem 'foo'\n gem 'bar'\n gem 'baz'\nend\n\z/ + end + + def test_gem_with_gemfile_without_newline_at_the_end + run_generator + File.open("Gemfile", "a") { |f| f.write("gem 'rspec-rails'") } + + action :gem, "will-paginate" + assert_file "Gemfile", /gem 'rspec-rails'\ngem 'will-paginate'\n\z/ + end + + def test_gem_group_with_gemfile_without_newline_at_the_end + run_generator + File.open("Gemfile", "a") { |f| f.write("gem 'rspec-rails'") } + + action :gem_group, :test do + gem "fakeweb" end - assert_file "Gemfile", /\ngroup :magic do\n github 'user\/repo', a: 'correct', other: true do\n gem 'foo'\n gem 'bar'\n gem 'baz'\n end\nend\n/ + assert_file "Gemfile", /gem 'rspec-rails'\n\ngroup :test do\n gem 'fakeweb'\nend\n\z/ + end + + def test_add_source_with_gemfile_without_newline_at_the_end + run_generator + File.open("Gemfile", "a") { |f| f.write("gem 'rspec-rails'") } + + action :add_source, "http://gems.github.com" do + gem "fakeweb" + end + + assert_file "Gemfile", /gem 'rspec-rails'\n\nsource 'http:\/\/gems\.github\.com' do\n gem 'fakeweb'\nend\n\z/ + end + + def test_github_with_gemfile_without_newline_at_the_end + run_generator + File.open("Gemfile", "a") { |f| f.write("gem 'rspec-rails'") } + + action :github, "user/repo" do + gem "fakeweb" + end + + assert_file "Gemfile", /gem 'rspec-rails'\n\ngithub 'user\/repo' do\n gem 'fakeweb'\nend\n\z/ end def test_environment_should_include_data_in_environment_initializer_block @@ -505,7 +581,6 @@ F end private - def action(*args, &block) capture(:stdout) { generator.send(*args, &block) } end diff --git a/railties/test/generators/api_app_generator_test.rb b/railties/test/generators/api_app_generator_test.rb index d03178da66..099bad8fb9 100644 --- a/railties/test/generators/api_app_generator_test.rb +++ b/railties/test/generators/api_app_generator_test.rb @@ -109,7 +109,6 @@ class ApiAppGeneratorTest < Rails::Generators::TestCase end private - def default_files %w(.gitignore .ruby-version diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb index 65cde91436..080e54a1ca 100644 --- a/railties/test/generators/migration_generator_test.rb +++ b/railties/test/generators/migration_generator_test.rb @@ -445,7 +445,6 @@ class MigrationGeneratorTest < Rails::Generators::TestCase end private - def with_singular_table_name old_state = ActiveRecord::Base.pluralize_table_names ActiveRecord::Base.pluralize_table_names = false diff --git a/railties/test/generators/named_base_test.rb b/railties/test/generators/named_base_test.rb index 4e61b660d7..1b45c58b0e 100644 --- a/railties/test/generators/named_base_test.rb +++ b/railties/test/generators/named_base_test.rb @@ -169,7 +169,6 @@ class NamedBaseTest < Rails::Generators::TestCase end private - def assert_name(generator, value, method) assert_equal value, generator.send(method) end diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb index f45464f8d0..db774f6ac1 100644 --- a/railties/test/generators/plugin_generator_test.rb +++ b/railties/test/generators/plugin_generator_test.rb @@ -713,7 +713,6 @@ class PluginGeneratorTest < Rails::Generators::TestCase end private - def action(*args, &block) silence(:stdout) { generator.send(*args, &block) } end diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index fab704944b..0fe62df8ba 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -448,18 +448,36 @@ module TestHelpers $:.reject! { |path| path =~ %r'/(#{to_remove.join('|')})/' } end - def use_postgresql - File.open("#{app_path}/config/database.yml", "w") do |f| - f.puts <<-YAML - default: &default - adapter: postgresql - pool: 5 - database: railties_test - development: - <<: *default - test: - <<: *default - YAML + def use_postgresql(multi_db: false) + if multi_db + File.open("#{app_path}/config/database.yml", "w") do |f| + f.puts <<-YAML + default: &default + adapter: postgresql + pool: 5 + development: + primary: + <<: *default + database: railties_test + animals: + <<: *default + database: railties_animals_test + migrations_paths: db/animals_migrate + YAML + end + else + File.open("#{app_path}/config/database.yml", "w") do |f| + f.puts <<-YAML + default: &default + adapter: postgresql + pool: 5 + database: railties_test + development: + <<: *default + test: + <<: *default + YAML + end end end end diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb index 8ce68dbcfa..7f05b9d9cf 100644 --- a/railties/test/railties/engine_test.rb +++ b/railties/test/railties/engine_test.rb @@ -34,7 +34,7 @@ module RailtiesTest def migrations migration_root = File.expand_path(ActiveRecord::Migrator.migrations_paths.first, app_path) - ActiveRecord::MigrationContext.new(migration_root).migrations + ActiveRecord::MigrationContext.new(migration_root, ActiveRecord::SchemaMigration).migrations end test "serving sprocket's assets" do diff --git a/tools/profile b/tools/profile index 6fb571f43b..d38ba1dd84 100755 --- a/tools/profile +++ b/tools/profile @@ -68,7 +68,6 @@ module CodeTools end private - def assert_ruby_file_exists(path) fail Error.new("No such file") unless File.exist?(path) fail Error.new("#{path} is a directory") if File.directory?(path) |