diff options
456 files changed, 4918 insertions, 1860 deletions
diff --git a/.travis.yml b/.travis.yml index 520c434f06..2823a5456f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,13 +3,6 @@ script: 'ci/travis.rb' before_install: - travis_retry gem install bundler - "rvm current | grep 'jruby' && export AR_JDBC=true || echo" -rvm: - - 1.9.3 - - 2.0.0 - - 2.1 - - ruby-head - - rbx-2 - - jruby env: global: - JRUBY_OPTS='-J-Xmx1024M' @@ -22,6 +15,13 @@ env: - "GEM=ar:sqlite3" - "GEM=ar:postgresql" - "GEM=aj:integration" +rvm: + - 1.9.3 + - 2.0.0 + - 2.1 + - ruby-head + - rbx-2 + - jruby matrix: allow_failures: - rvm: 1.9.3 @@ -2,8 +2,6 @@ source 'https://rubygems.org' gemspec -gem 'rails-dom-testing', github: 'rails/rails-dom-testing' - # We need a newish Rake since Active Job sets its test tasks' descriptions. gem 'rake', '>= 10.3' @@ -13,9 +11,9 @@ gem 'rake', '>= 10.3' gem 'mocha', '~> 0.14', require: false gem 'rack-cache', '~> 1.2' -gem 'jquery-rails', '~> 4.0.0.beta2' -gem 'coffee-rails', '~> 4.0.0' -gem 'turbolinks', '~> 2.2.3' +gem 'jquery-rails', '~> 4.0' +gem 'coffee-rails', '~> 4.1.0' +gem 'turbolinks' # require: false so bcrypt is loaded only when has_secure_password is used. # This is to avoid ActiveModel (and by extension the entire framework) @@ -65,6 +63,10 @@ group :test do gem 'ruby-prof', '~> 0.11.2' end + platforms :mri_21 do + gem 'stackprof' + end + # platforms :mri_19, :mri_20 do # gem 'debugger' # end @@ -82,7 +84,7 @@ platforms :ruby do gem 'sqlite3', '~> 1.3.6' group :db do - gem 'pg', '>= 0.11.0' + gem 'pg', '>= 0.15.0' gem 'mysql', '>= 2.9.0' gem 'mysql2', '>= 0.3.13' end diff --git a/RAILS_VERSION b/RAILS_VERSION index a771777d25..b86dc8c0c6 100644 --- a/RAILS_VERSION +++ b/RAILS_VERSION @@ -1 +1 @@ -4.2.0.beta2 +4.2.0.beta4 @@ -13,10 +13,10 @@ Person, Post, etc.) and encapsulates the business logic that is specific to your application. In Rails, database-backed model classes are derived from `ActiveRecord::Base`. Active Record allows you to present the data from database rows as objects and embellish these data objects with business logic -methods. Although most Rails models are backed by a database, models can also -be ordinary Ruby classes, or Ruby classes that implement a set of interfaces -as provided by the Active Model module. You can read more about Active Record -in its [README](activerecord/README.rdoc). +methods. You can read more about Active Record in its [README](activerecord/README.rdoc). +Although most Rails models are backed by a database, models can also be ordinary +Ruby classes, or Ruby classes that implement a set of interfaces as provided by +the Active Model module. You can read more about Active Model in its [README](activemodel/README.rdoc). The _Controller layer_ is responsible for handling incoming HTTP requests and providing a suitable response. Usually this means returning HTML, but Rails controllers @@ -36,9 +36,11 @@ You can read more about Action View in its [README](actionview/README.rdoc). Active Record, Action Pack, and Action View can each be used independently outside Rails. In addition to them, Rails also comes with Action Mailer ([README](actionmailer/README.rdoc)), a library -to generate and send emails; and Active Support ([README](activesupport/README.rdoc)), a collection of -utility classes and standard library extensions that are useful for Rails, and may also be used -independently outside Rails. +to generate and send emails; Active Job ([README](activejob/README.md)), a +framework for declaring jobs and making them run on a variety of queueing +backends; and Active Support ([README](activesupport/README.rdoc)), a collection +of utility classes and standard library extensions that are useful for Rails, +and may also be used independently outside Rails. ## Getting Started diff --git a/RELEASING_RAILS.rdoc b/RELEASING_RAILS.rdoc index f8c40f0b02..c80a5816a7 100644 --- a/RELEASING_RAILS.rdoc +++ b/RELEASING_RAILS.rdoc @@ -28,7 +28,7 @@ Do not release with Red AWDwR tests. === Are the supported plugins working? If not, make it work. Some Rails plugins are important and need to be supported until Rails 5. -As these plugins are outside the Rails repository it is easy to break then without knowing +As these plugins are outside the Rails repository it is easy to break them without knowing after some refactoring or bug fix, so it is important to check if the following plugins are working with the versions that will be released: @@ -54,7 +54,7 @@ addressed, and that can impact your release date. Ruby implementors have high stakes in making sure Rails works. Be kind and give them a heads up that Rails will be released soonish. -This only needs done for major and minor releases, bugfix releases aren't a +This only need to be done for major and minor releases, bugfix releases aren't a big enough deal, and are supposed to be backwards compatible. Send an email just giving a heads up about the upcoming release to these diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md index e2900c2d10..9fdda52f77 100644 --- a/actionmailer/CHANGELOG.md +++ b/actionmailer/CHANGELOG.md @@ -1,3 +1,17 @@ +* MailerGenerator now generates layouts by default. HTML mailer layout will + include `<html>` and `<body>` tags which will help to reduce spam score in + some spam detection engines. Mailers will now inherit from `ApplicationMailer` + which sets the default layout. + + *Andy Jeffries* + +* `link_to` and `url_for` generate URLs by default in templates, it is no + longer needed to pass `only_path: false`. + + Fixes #16497 and #16589. + + *Xavier Noria*, *Richard Schneeman* + * Attachments can be added while rendering the mail template. Fixes #16974. @@ -10,7 +24,7 @@ using the new Active Job framework in Rails, and will use whatever queue is configured for Rails. - *DHH/Abdelkader Boudih/Cristian Bica* + *DHH*, *Abdelkader Boudih*, *Cristian Bica* * Make `ActionMailer::Previews` methods class methods. Previously they were instance methods and `ActionMailer` tries to render a message when they diff --git a/actionmailer/README.rdoc b/actionmailer/README.rdoc index 3b8e3ed749..a4e660d621 100644 --- a/actionmailer/README.rdoc +++ b/actionmailer/README.rdoc @@ -61,7 +61,7 @@ generated would look like this: Thank you for signing up! -In order to send mails, you simply call the method and then call +deliver+ on the return value. +In order to send mails, you simply call the method and then call +deliver_now+ on the return value. Calling the method returns a Mail Message object: @@ -74,9 +74,17 @@ Or you can just chain the methods together like: == Setting defaults -It is possible to set default values that will be used in every method in your Action Mailer class. To implement this functionality, you just call the public class method <tt>default</tt> which you get for free from <tt>ActionMailer::Base</tt>. This method accepts a Hash as the parameter. You can use any of the headers email messages have, like <tt>:from</tt> as the key. You can also pass in a string as the key, like "Content-Type", but Action Mailer does this out of the box for you, so you won't need to worry about that. Finally, it is also possible to pass in a Proc that will get evaluated when it is needed. +It is possible to set default values that will be used in every method in your +Action Mailer class. To implement this functionality, you just call the public +class method +default+ which you get for free from <tt>ActionMailer::Base</tt>. +This method accepts a Hash as the parameter. You can use any of the headers, +email messages have, like +:from+ as the key. You can also pass in a string as +the key, like "Content-Type", but Action Mailer does this out of the box for you, +so you won't need to worry about that. Finally, it is also possible to pass in a +Proc that will get evaluated when it is needed. -Note that every value you set with this method will get overwritten if you use the same key in your mailer method. +Note that every value you set with this method will get overwritten if you use the +same key in your mailer method. Example: @@ -87,10 +95,11 @@ Example: == Receiving emails -To receive emails, you need to implement a public instance method called <tt>receive</tt> that takes an -email object as its single parameter. The Action Mailer framework has a corresponding class method, -which is also called <tt>receive</tt>, that accepts a raw, unprocessed email as a string, which it then turns -into the email object and calls the receive instance method. +To receive emails, you need to implement a public instance method called ++receive+ that takes an email object as its single parameter. The Action Mailer +framework has a corresponding class method, which is also called +receive+, that +accepts a raw, unprocessed email as a string, which it then turns into the email +object and calls the receive instance method. Example: @@ -111,13 +120,14 @@ Example: end end -This Mailman can be the target for Postfix or other MTAs. In Rails, you would use the runner in the -trivial case like this: +This Mailman can be the target for Postfix or other MTAs. In Rails, you would use +the runner in the trivial case like this: rails runner 'Mailman.receive(STDIN.read)' -However, invoking Rails in the runner for each mail to be received is very resource intensive. A single -instance of Rails should be run within a daemon, if it is going to process more than just a limited amount of email. +However, invoking Rails in the runner for each mail to be received is very +resource intensive. A single instance of Rails should be run within a daemon, if +it is going to process more than just a limited amount of email. == Configuration diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec index fbf6c5e9f9..b63f4e5c08 100644 --- a/actionmailer/actionmailer.gemspec +++ b/actionmailer/actionmailer.gemspec @@ -24,5 +24,5 @@ Gem::Specification.new do |s| s.add_dependency 'activejob', version s.add_dependency 'mail', ['~> 2.5', '>= 2.5.4'] - s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.3' + s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.5' end diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 1ab68d2953..23139bcbe8 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -15,11 +15,17 @@ module ActionMailer # # $ rails generate mailer Notifier # - # The generated model inherits from <tt>ActionMailer::Base</tt>. A mailer model defines methods + # The generated model inherits from <tt>ApplicationMailer</tt> which in turn + # inherits from <tt>ActionMailer::Base</tt>. A mailer model defines methods # used to generate an email message. In these methods, you can setup variables to be used in # the mailer views, options on the mail itself such as the <tt>:from</tt> address, and attachments. # - # class Notifier < ActionMailer::Base + # class ApplicationMailer < ActionMailer::Base + # default from: 'from@exmaple.com' + # layout 'mailer' + # end + # + # class Notifier < ApplicationMailer # default from: 'no-reply@example.com', # return_path: 'system@example.com' # @@ -39,11 +45,8 @@ module ActionMailer # in the same manner as <tt>attachments[]=</tt> # # * <tt>headers[]=</tt> - Allows you to specify any header field in your email such - # as <tt>headers['X-No-Spam'] = 'True'</tt>. Note, while most fields like <tt>To:</tt> - # <tt>From:</tt> can only appear once in an email header, other fields like <tt>X-Anything</tt> - # can appear multiple times. If you want to change a field that can appear multiple times, - # you need to set it to nil first so that Mail knows you are replacing it and not adding - # another field of the same name. + # as <tt>headers['X-No-Spam'] = 'True'</tt>. Note that declaring a header multiple times + # will add many fields of the same name. Read #headers doc for more information. # # * <tt>headers(hash)</tt> - Allows you to specify multiple headers in your email such # as <tt>headers({'X-No-Spam' => 'True', 'In-Reply-To' => '1234@message.id'})</tt> @@ -87,7 +90,8 @@ module ActionMailer # name as the method in your mailer model. For example, in the mailer defined above, the template at # <tt>app/views/notifier/welcome.text.erb</tt> would be used to generate the email. # - # Variables defined in the model are accessible as instance variables in the view. + # Variables defined in the methods of your mailer model are accessible as instance variables in their + # corresponding view. # # Emails by default are sent in plain text, so a sample view for our model example might look like this: # @@ -180,7 +184,7 @@ module ActionMailer # # Sending attachment in emails is easy: # - # class ApplicationMailer < ActionMailer::Base + # class Notifier < ApplicationMailer # def welcome(recipient) # attachments['free_book.pdf'] = File.read('path/to/file.pdf') # mail(to: recipient, subject: "New account information") @@ -196,7 +200,7 @@ module ActionMailer # If you need to send attachments with no content, you need to create an empty view for it, # or add an empty body parameter like this: # - # class ApplicationMailer < ActionMailer::Base + # class Notifier < ApplicationMailer # def welcome(recipient) # attachments['free_book.pdf'] = File.read('path/to/file.pdf') # mail(to: recipient, subject: "New account information", body: "") @@ -208,7 +212,7 @@ module ActionMailer # You can also specify that a file should be displayed inline with other HTML. This is useful # if you want to display a corporate logo or a photo. # - # class ApplicationMailer < ActionMailer::Base + # class Notifier < ApplicationMailer # def welcome(recipient) # attachments.inline['photo.png'] = File.read('path/to/photo.png') # mail(to: recipient, subject: "Here is what we look like") @@ -247,7 +251,7 @@ module ActionMailer # Action Mailer provides some intelligent defaults for your emails, these are usually specified in a # default method inside the class definition: # - # class Notifier < ActionMailer::Base + # class Notifier < ApplicationMailer # default sender: 'system@example.com' # end # @@ -265,7 +269,7 @@ module ActionMailer # As you can pass in any header, you need to either quote the header as a string, or pass it in as # an underscored symbol, so the following will work: # - # class Notifier < ActionMailer::Base + # class Notifier < ApplicationMailer # default 'Content-Transfer-Encoding' => '7bit', # content_description: 'This is a description' # end @@ -273,7 +277,7 @@ module ActionMailer # Finally, Action Mailer also supports passing <tt>Proc</tt> objects into the default hash, so you # can define methods that evaluate as the message is being generated: # - # class Notifier < ActionMailer::Base + # class Notifier < ApplicationMailer # default 'X-Special-Header' => Proc.new { my_method } # # private @@ -298,7 +302,7 @@ module ActionMailer # This may be useful, for example, when you want to add default inline attachments for all # messages sent out by a certain mailer class: # - # class Notifier < ActionMailer::Base + # class Notifier < ApplicationMailer # before_action :add_inline_attachment! # # def welcome @@ -625,6 +629,26 @@ module ActionMailer # The resulting <tt>Mail::Message</tt> will have the following in its header: # # X-Special-Domain-Specific-Header: SecretValue + # + # Note about replacing already defined headers: + # + # * +subject+ + # * +sender+ + # * +from+ + # * +to+ + # * +cc+ + # * +bcc+ + # * +reply-to+ + # * +orig-date+ + # * +message-id+ + # * +references+ + # + # Fields can only appear once in email headers while other fields such as + # <tt>X-Anything</tt> can appear multiple times. + # + # If you want to replace any header which already exists, first set it to + # +nil+ in order to reset the value otherwise another field will be added + # for the same header. def headers(args = nil) if args @_message.headers(args) @@ -685,8 +709,8 @@ module ActionMailer # The main method that creates the message and renders the email templates. There are # two ways to call this method, with a block, or without a block. # - # Both methods accept a headers hash. This hash allows you to specify the most used headers - # in an email message, these are: + # It accepts a headers hash. This hash allows you to specify + # the most used headers in an email message, these are: # # * +:subject+ - The subject of the message, if this is omitted, Action Mailer will # ask the Rails I18n class for a translated +:subject+ in the scope of diff --git a/actionmailer/lib/action_mailer/delivery_job.rb b/actionmailer/lib/action_mailer/delivery_job.rb index 622f202695..95231411fb 100644 --- a/actionmailer/lib/action_mailer/delivery_job.rb +++ b/actionmailer/lib/action_mailer/delivery_job.rb @@ -1,6 +1,8 @@ require 'active_job' module ActionMailer + # The <tt>ActionMailer::DeliveryJob</tt> class is used when you + # want to send emails outside of the request-response cycle. class DeliveryJob < ActiveJob::Base #:nodoc: queue_as :mailers diff --git a/actionmailer/lib/action_mailer/gem_version.rb b/actionmailer/lib/action_mailer/gem_version.rb index 0c5c55be84..e568b8f6f2 100644 --- a/actionmailer/lib/action_mailer/gem_version.rb +++ b/actionmailer/lib/action_mailer/gem_version.rb @@ -8,7 +8,7 @@ module ActionMailer MAJOR = 4 MINOR = 2 TINY = 0 - PRE = "beta2" + PRE = "beta4" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/actionmailer/lib/action_mailer/message_delivery.rb b/actionmailer/lib/action_mailer/message_delivery.rb index 7118f9b02c..b5dc2d7497 100644 --- a/actionmailer/lib/action_mailer/message_delivery.rb +++ b/actionmailer/lib/action_mailer/message_delivery.rb @@ -1,4 +1,5 @@ require 'delegate' +require 'active_support/core_ext/string/filters' module ActionMailer @@ -46,6 +47,7 @@ module ActionMailer # # * <tt>:wait</tt> - Enqueue the email to be delivered with a delay # * <tt>:wait_until</tt> - Enqueue the email to be delivered at (after) a specific date / time + # * <tt>:queue</tt> - Enqueue the email on the specified queue def deliver_later!(options={}) enqueue_delivery :deliver_now!, options end @@ -61,6 +63,7 @@ module ActionMailer # # * <tt>:wait</tt> - Enqueue the email to be delivered with a delay # * <tt>:wait_until</tt> - Enqueue the email to be delivered at (after) a specific date / time + # * <tt>:queue</tt> - Enqueue the email on the specified queue def deliver_later(options={}) enqueue_delivery :deliver_now, options end @@ -83,14 +86,22 @@ module ActionMailer end def deliver! #:nodoc: - ActiveSupport::Deprecation.warn "#deliver! is deprecated and will be removed in Rails 5. " \ - "Use #deliver_now! to deliver immediately or #deliver_later! to deliver through Active Job." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + `#deliver!` is deprecated and will be removed in Rails 5. Use + `#deliver_now!` to deliver immediately or `#deliver_later!` to + deliver through Active Job. + MSG + deliver_now! end def deliver #:nodoc: - ActiveSupport::Deprecation.warn "#deliver is deprecated and will be removed in Rails 5. " \ - "Use #deliver_now to deliver immediately or #deliver_later to deliver through Active Job." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + `#deliver` is deprecated and will be removed in Rails 5. Use + `#deliver_now` to deliver immediately or `#deliver_later` to + deliver through Active Job. + MSG + deliver_now end diff --git a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb index d5bf864595..094ec85114 100644 --- a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb +++ b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb @@ -8,6 +8,7 @@ module Rails def create_mailer_file template "mailer.rb", File.join('app/mailers', class_path, "#{file_name}.rb") + template "application_mailer.rb", 'app/mailers/application_mailer.rb' end hook_for :template_engine, :test_framework diff --git a/actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb b/actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb new file mode 100644 index 0000000000..d25d8892dd --- /dev/null +++ b/actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout 'mailer' +end diff --git a/actionmailer/lib/rails/generators/mailer/templates/mailer.rb b/actionmailer/lib/rails/generators/mailer/templates/mailer.rb index edcfb4233d..bce64a5e6e 100644 --- a/actionmailer/lib/rails/generators/mailer/templates/mailer.rb +++ b/actionmailer/lib/rails/generators/mailer/templates/mailer.rb @@ -1,6 +1,5 @@ <% module_namespacing do -%> -class <%= class_name %> < ActionMailer::Base - default from: "from@example.com" +class <%= class_name %> < ApplicationMailer <% actions.each do |action| -%> # Subject can be set in your I18n file at config/locales/en.yml diff --git a/actionmailer/test/fixtures/url_test_mailer/exercise_url_for.erb b/actionmailer/test/fixtures/url_test_mailer/exercise_url_for.erb new file mode 100644 index 0000000000..0322c1191e --- /dev/null +++ b/actionmailer/test/fixtures/url_test_mailer/exercise_url_for.erb @@ -0,0 +1 @@ +<%= url_for(@options) %> <%= @url %> diff --git a/actionmailer/test/url_test.rb b/actionmailer/test/url_test.rb index be7532d42f..7928fe9542 100644 --- a/actionmailer/test/url_test.rb +++ b/actionmailer/test/url_test.rb @@ -23,9 +23,32 @@ class UrlTestMailer < ActionMailer::Base mail(to: recipient, subject: "[Signed up] Welcome #{recipient}", from: "system@loudthinking.com", date: Time.local(2004, 12, 12)) end + + def exercise_url_for(options) + @options = options + @url = url_for(@options) + mail(from: 'from@example.com', to: 'to@example.com', subject: 'subject') + end end class ActionMailerUrlTest < ActionMailer::TestCase + class DummyModel + def self.model_name + OpenStruct.new(route_key: 'dummy_model') + end + + def persisted? + false + end + + def model_name + self.class.model_name + end + + def to_model + self + end + end def encode( text, charset="UTF-8" ) quoted_printable( text, charset ) @@ -40,10 +63,47 @@ class ActionMailerUrlTest < ActionMailer::TestCase mail end + def assert_url_for(expected, options, relative = false) + expected = "http://www.basecamphq.com#{expected}" if expected.start_with?('/') && !relative + urls = UrlTestMailer.exercise_url_for(options).body.to_s.chomp.split + + assert_equal expected, urls.first + assert_equal expected, urls.second + end + def setup @recipient = 'test@localhost' end + def test_url_for + UrlTestMailer.delivery_method = :test + + AppRoutes.draw do + get ':controller(/:action(/:id))' + get '/welcome' => 'foo#bar', as: 'welcome' + get '/dummy_model' => 'foo#baz', as: 'dummy_model' + end + + # string + assert_url_for 'http://foo/', 'http://foo/' + + # symbol + assert_url_for '/welcome', :welcome + + # hash + assert_url_for '/a/b/c', controller: 'a', action: 'b', id: 'c' + assert_url_for '/a/b/c', {controller: 'a', action: 'b', id: 'c', only_path: true}, true + + # model + assert_url_for '/dummy_model', DummyModel.new + + # class + assert_url_for '/dummy_model', DummyModel + + # array + assert_url_for '/dummy_model' , [DummyModel] + end + def test_signed_up_with_url UrlTestMailer.delivery_method = :test diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index de9722c392..07063c953a 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -1,3 +1,37 @@ +* Restore handling of a bare `Authorization` header, without `token=` + prefix. + + Fixes #17108. + + *Guo Xiang Tan* + +* Deprecate use of string keys in URL helpers. + + Use symbols instead. + Fixes #16958. + + *Byron Bischoff*, *Melanie Gilman* + +* Deprecate the `only_path` option on `*_path` helpers. + + In cases where this option is set to `true`, the option is redundant and can + be safely removed; otherwise, the corresponding `*_url` helper should be + used instead. + + Fixes #17294. + + *Dan Olson*, *Godfrey Chan* + +* Improve Journey compliance to RFC 3986. + + The scanner in Journey failed to recognize routes that use literals + from the sub-delims section of RFC 3986. It's now able to parse those + authorized delimiters and route as expected. + + Fixes #17212. + + *Nicolas Cavigneaux* + * Deprecate implicit Array conversion for Response objects. It was added (using `#to_ary`) so we could conveniently use implicit splatting: diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index 69a160fdc8..1e68d1870d 100644 --- a/actionpack/actionpack.gemspec +++ b/actionpack/actionpack.gemspec @@ -24,7 +24,7 @@ Gem::Specification.new do |s| s.add_dependency 'rack', '~> 1.6.0.beta' s.add_dependency 'rack-test', '~> 0.6.2' s.add_dependency 'rails-html-sanitizer', '~> 1.0', '>= 1.0.1' - s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.3' + s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.5' s.add_dependency 'actionview', version s.add_development_dependency 'activemodel', version diff --git a/actionpack/lib/abstract_controller/helpers.rb b/actionpack/lib/abstract_controller/helpers.rb index 95c67d482b..df7382f02d 100644 --- a/actionpack/lib/abstract_controller/helpers.rb +++ b/actionpack/lib/abstract_controller/helpers.rb @@ -150,7 +150,17 @@ module AbstractController rescue LoadError => e raise AbstractController::Helpers::MissingHelperError.new(e, file_name) end - file_name.camelize.constantize + + mod_name = file_name.camelize + begin + mod_name.constantize + rescue LoadError + # dependencies.rb gives a similar error message but its wording is + # not as clear because it mentions autoloading. To the user all it + # matters is that a helper module couldn't be loaded, autoloading + # is an internal mechanism that should not leak. + raise NameError, "Couldn't find #{mod_name}, expected it to be defined in helpers/#{file_name}.rb" + end when Module arg else diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 7bbf938987..5cb11bc479 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -44,7 +44,7 @@ module ActionController # The full request object is available via the request accessor and is primarily used to query for HTTP headers: # # def server_ip - # location = request.env["SERVER_ADDR"] + # location = request.env["REMOTE_ADDR"] # render plain: "This server hosted at #{location}" # end # diff --git a/actionpack/lib/action_controller/log_subscriber.rb b/actionpack/lib/action_controller/log_subscriber.rb index 89fa75f025..d3f93a5352 100644 --- a/actionpack/lib/action_controller/log_subscriber.rb +++ b/actionpack/lib/action_controller/log_subscriber.rb @@ -1,4 +1,3 @@ - module ActionController class LogSubscriber < ActiveSupport::LogSubscriber INTERNAL_PARAMS = %w(controller action format _method only_path) diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb index bfbc15a901..6dd213b2f7 100644 --- a/actionpack/lib/action_controller/metal.rb +++ b/actionpack/lib/action_controller/metal.rb @@ -165,7 +165,7 @@ module ActionController headers["Location"] = url end - # basic url_for that can be overridden for more robust functionality + # Basic url_for that can be overridden for more robust functionality def url_for(string) string end @@ -182,7 +182,7 @@ module ActionController body = [body] unless body.nil? || body.respond_to?(:each) super end - + # Tests if render or redirect has already happened. def performed? response_body || (response && response.committed?) @@ -237,7 +237,7 @@ module ActionController end end - def _status_code + def _status_code #:nodoc: @_status end end diff --git a/actionpack/lib/action_controller/metal/etag_with_template_digest.rb b/actionpack/lib/action_controller/metal/etag_with_template_digest.rb index 3ca0c6837a..f9303efe6c 100644 --- a/actionpack/lib/action_controller/metal/etag_with_template_digest.rb +++ b/actionpack/lib/action_controller/metal/etag_with_template_digest.rb @@ -7,8 +7,8 @@ module ActionController # # config.action_controller.etag_with_template_digest = false # - # Override the template to digest by passing `:template` to `fresh_when` - # and `stale?` calls. For example: + # Override the template to digest by passing +:template+ to +fresh_when+ + # and +stale?+ calls. For example: # # # We're going to render widgets/show, not posts/show # fresh_when @post, template: 'widgets/show' diff --git a/actionpack/lib/action_controller/metal/exceptions.rb b/actionpack/lib/action_controller/metal/exceptions.rb index 3844dbf2a6..18e003741d 100644 --- a/actionpack/lib/action_controller/metal/exceptions.rb +++ b/actionpack/lib/action_controller/metal/exceptions.rb @@ -25,7 +25,7 @@ module ActionController end end - class ActionController::UrlGenerationError < RoutingError #:nodoc: + class ActionController::UrlGenerationError < ActionControllerError #:nodoc: end class MethodNotAllowed < ActionControllerError #:nodoc: diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb index 167df2f935..fd578d60ca 100644 --- a/actionpack/lib/action_controller/metal/http_authentication.rb +++ b/actionpack/lib/action_controller/metal/http_authentication.rb @@ -463,14 +463,14 @@ module ActionController raw_params.map { |param| param.split %r/=(.+)?/ } end - # This removes the `"` characters wrapping the value. + # This removes the <tt>"</tt> characters wrapping the value. def rewrite_param_values(array_params) array_params.each { |param| (param[1] || "").gsub! %r/^"|"$/, '' } end # This method takes an authorization body and splits up the key-value - # pairs by the standardized `:`, `;`, or `\t` delimiters defined in - # `AUTHN_PAIR_DELIMITERS`. + # pairs by the standardized <tt>:</tt>, <tt>;</tt>, or <tt>\t</tt> + # delimiters defined in +AUTHN_PAIR_DELIMITERS+. def raw_params(auth) _raw_params = auth.sub(TOKEN_REGEX, '').split(/\s*#{AUTHN_PAIR_DELIMITERS}\s*/) diff --git a/actionpack/lib/action_controller/metal/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb index b0e164bc57..bef7545e71 100644 --- a/actionpack/lib/action_controller/metal/instrumentation.rb +++ b/actionpack/lib/action_controller/metal/instrumentation.rb @@ -21,7 +21,7 @@ module ActionController :action => self.action_name, :params => request.filtered_parameters, :format => request.format.try(:ref), - :method => request.method, + :method => request.request_method, :path => (request.fullpath rescue "unknown") } diff --git a/actionpack/lib/action_controller/metal/live.rb b/actionpack/lib/action_controller/metal/live.rb index c9ef3a3dad..1e13b3761f 100644 --- a/actionpack/lib/action_controller/metal/live.rb +++ b/actionpack/lib/action_controller/metal/live.rb @@ -102,7 +102,7 @@ module ActionController end end - message = json.gsub("\n", "\ndata: ") + message = json.gsub(/\n/, "\ndata: ") @stream.write "data: #{message}\n\n" end end diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb index dc572f13d2..ac1f209232 100644 --- a/actionpack/lib/action_controller/metal/mime_responds.rb +++ b/actionpack/lib/action_controller/metal/mime_responds.rb @@ -135,18 +135,6 @@ module ActionController #:nodoc: # # render json: @people # - # Since this is a common pattern, you can use the class method respond_to - # with the respond_with method to have the same results: - # - # class PeopleController < ApplicationController - # respond_to :html, :xml, :json - # - # def index - # @people = Person.all - # respond_with(@people) - # end - # end - # # Formats can have different variants. # # The request variant is a specialization of the request format, like <tt>:tablet</tt>, @@ -214,13 +202,13 @@ module ActionController #:nodoc: # format.html.phone # this gets rendered # end # - # Be sure to check the documentation of +respond_with+ and - # <tt>ActionController::MimeResponds.respond_to</tt> for more examples. - def respond_to(*mimes, &block) + # Be sure to check the documentation of <tt>ActionController::MimeResponds.respond_to</tt> + # for more examples. + def respond_to(*mimes) raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given? collector = Collector.new(mimes, request.variant) - block.call(collector) if block_given? + yield collector if block_given? if format = collector.negotiate_format(request) _process_format(format) @@ -234,8 +222,8 @@ module ActionController #:nodoc: # A container for responses available from the current controller for # requests for different mime-types sent to a particular action. # - # The public controller methods +respond_with+ and +respond_to+ may be called - # with a block that is used to define responses to different mime-types, e.g. + # The public controller methods +respond_to+ may be called with a block + # that is used to define responses to different mime-types, e.g. # for +respond_to+ : # # respond_to do |format| diff --git a/actionpack/lib/action_controller/metal/rack_delegation.rb b/actionpack/lib/action_controller/metal/rack_delegation.rb index 6921834044..545d4a7e6e 100644 --- a/actionpack/lib/action_controller/metal/rack_delegation.rb +++ b/actionpack/lib/action_controller/metal/rack_delegation.rb @@ -6,7 +6,7 @@ module ActionController extend ActiveSupport::Concern delegate :headers, :status=, :location=, :content_type=, - :status, :location, :content_type, :_status_code, :to => "@_response" + :status, :location, :content_type, :response_code, :to => "@_response" def dispatch(action, request) set_response!(request) diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb index bc94536c8c..45d3962494 100644 --- a/actionpack/lib/action_controller/metal/renderers.rb +++ b/actionpack/lib/action_controller/metal/renderers.rb @@ -86,8 +86,7 @@ module ActionController # end # end # To use renderers and their mime types in more concise ways, see - # <tt>ActionController::MimeResponds::ClassMethods.respond_to</tt> and - # <tt>ActionController::MimeResponds#respond_with</tt> + # <tt>ActionController::MimeResponds::ClassMethods.respond_to</tt> def self.add(key, &block) define_method(_render_with_renderer_method_name(key), &block) RENDERERS << key.to_sym diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb index a4f376816f..fd20682f8f 100644 --- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb +++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb @@ -1,5 +1,6 @@ require 'rack/session/abstract/id' require 'action_controller/metal/exceptions' +require 'active_support/security_utils' module ActionController #:nodoc: class InvalidAuthenticityToken < ActionControllerError #:nodoc: @@ -305,8 +306,7 @@ module ActionController #:nodoc: end def compare_with_real_token(token, session) - # Borrow a constant-time comparison from Rack - Rack::Utils.secure_compare(token, real_csrf_token(session)) + ActiveSupport::SecurityUtils.secure_compare(token, real_csrf_token(session)) end def real_csrf_token(session) diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb index 7038f0997f..a5ee1e2159 100644 --- a/actionpack/lib/action_controller/metal/strong_parameters.rb +++ b/actionpack/lib/action_controller/metal/strong_parameters.rb @@ -1,5 +1,6 @@ require 'active_support/core_ext/hash/indifferent_access' require 'active_support/core_ext/array/wrap' +require 'active_support/core_ext/string/filters' require 'active_support/deprecation' require 'active_support/rescuable' require 'action_dispatch/http/upload' @@ -114,10 +115,12 @@ module ActionController def self.const_missing(const_name) super unless const_name == :NEVER_UNPERMITTED_PARAMS - ActiveSupport::Deprecation.warn "`ActionController::Parameters::NEVER_UNPERMITTED_PARAMS`"\ - " has been deprecated. Use "\ - "`ActionController::Parameters.always_permitted_parameters` instead." - self.always_permitted_parameters + ActiveSupport::Deprecation.warn(<<-MSG.squish) + `ActionController::Parameters::NEVER_UNPERMITTED_PARAMS` has been deprecated. + Use `ActionController::Parameters.always_permitted_parameters` instead. + MSG + + always_permitted_parameters end # Returns a new instance of <tt>ActionController::Parameters</tt>. diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 41d33d4396..cd92962dc3 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -2,6 +2,7 @@ require 'rack/session/abstract/id' require 'active_support/core_ext/object/to_query' require 'active_support/core_ext/module/anonymous' require 'active_support/core_ext/hash/keys' +require 'active_support/deprecation' require 'rails-dom-testing' @@ -689,7 +690,7 @@ module ActionController private def document_root_element - html_document + html_document.root end def check_required_ivars @@ -710,7 +711,28 @@ module ActionController :relative_url_root => nil, :_recall => @request.path_parameters) - url, query_string = @routes.path_for(options).split("?", 2) + if route_name = options.delete(:use_route) + ActiveSupport::Deprecation.warn <<-MSG.squish + Passing the `use_route` option in functional tests are deprecated. + Support for this option in the `process` method (and the related + `get`, `head`, `post`, `patch`, `put` and `delete` helpers) will + be removed in the next version without replacement. + + Functional tests are essentially unit tests for controllers and + they should not require knowledge to how the application's routes + are configured. Instead, you should explicitly pass the appropiate + params to the `process` method. + + Previously the engines guide also contained an incorrect example + that recommended using this option to test an engine's controllers + within the dummy application. That recommendation was incorrect + and has since been corrected. Instead, you should override the + `@routes` variable in the test case with `Foo::Engine.routes`. See + the updated engines guide for details. + MSG + end + + url, query_string = @routes.path_for(options, route_name).split("?", 2) @request.env["SCRIPT_NAME"] = @controller.config.relative_url_root @request.env["PATH_INFO"] = url diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb index 20ae48d458..a5cd26a3c1 100644 --- a/actionpack/lib/action_dispatch/http/parameters.rb +++ b/actionpack/lib/action_dispatch/http/parameters.rb @@ -27,7 +27,7 @@ module ActionDispatch def symbolized_path_parameters ActiveSupport::Deprecation.warn( - "`symbolized_path_parameters` is deprecated. Please use `path_parameters`" + '`symbolized_path_parameters` is deprecated. Please use `path_parameters`.' ) path_parameters end diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index a8785ee6bf..2a7bb374a5 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -328,7 +328,7 @@ module ActionDispatch # Extracted into ActionDispatch::Request::Utils.deep_munge, but kept here for backwards compatibility. def deep_munge(hash) ActiveSupport::Deprecation.warn( - "This method has been extracted into ActionDispatch::Request::Utils.deep_munge. Please start using that instead." + 'This method has been extracted into `ActionDispatch::Request::Utils.deep_munge`. Please start using that instead.' ) Utils.deep_munge(hash) diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index c5e18048da..33de2f8b5f 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -1,4 +1,5 @@ require 'active_support/core_ext/module/attribute_accessors' +require 'active_support/core_ext/string/filters' require 'active_support/deprecation' require 'action_dispatch/http/filter_redirect' require 'monitor' @@ -288,7 +289,12 @@ module ActionDispatch # :nodoc: # as arrays work, and "flattening" responses, cascading to the rack body! # Not sensible behavior. def to_ary - ActiveSupport::Deprecation.warn 'ActionDispatch::Response#to_ary no longer performs implicit conversion to an Array. Please use response.to_a instead, or a splat like `status, headers, body = *response`' + ActiveSupport::Deprecation.warn(<<-MSG.squish) + `ActionDispatch::Response#to_ary` no longer performs implicit conversion + to an array. Please use `response.to_a` instead, or a splat like `status, + headers, body = *response`. + MSG + to_a end @@ -309,9 +315,6 @@ module ActionDispatch # :nodoc: cookies end - def _status_code - @status - end private def before_committed diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 6b8dcaf497..22c0de2ac2 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -68,7 +68,9 @@ module ActionDispatch end def add_anchor(path, anchor) - path << "##{Journey::Router::Utils.escape_fragment(anchor.to_param.to_s)}" + if anchor + path << "##{Journey::Router::Utils.escape_fragment(anchor.to_param)}" + end end def extract_domain_from(host, tld_length) diff --git a/actionpack/lib/action_dispatch/journey/formatter.rb b/actionpack/lib/action_dispatch/journey/formatter.rb index 59b353b1b7..177f586c0e 100644 --- a/actionpack/lib/action_dispatch/journey/formatter.rb +++ b/actionpack/lib/action_dispatch/journey/formatter.rb @@ -1,4 +1,5 @@ require 'action_controller/metal/exceptions' +require 'active_support/deprecation' module ActionDispatch module Journey @@ -40,7 +41,7 @@ module ActionDispatch end message = "No route matches #{Hash[constraints.sort].inspect}" - message << " missing required keys: #{missing_keys.sort.inspect}" if name + message << " missing required keys: #{missing_keys.sort.inspect}" unless missing_keys.empty? raise ActionController::UrlGenerationError, message end @@ -80,6 +81,9 @@ module ActionDispatch if named_routes.key?(name) yield named_routes[name] else + # Make sure we don't show the deprecation warning more than once + warned = false + routes = non_recursive(cache, options) hash = routes.group_by { |_, r| r.score(options) } @@ -88,6 +92,17 @@ module ActionDispatch break if score < 0 hash[score].sort_by { |i, _| i }.each do |_, route| + if name && !warned + ActiveSupport::Deprecation.warn <<-MSG.squish + You are trying to generate the URL for a named route called + #{name.inspect} but no such route was found. In the future, + this will result in an `ActionController::UrlGenerationError` + exception. + MSG + + warned = true + end + yield route end end diff --git a/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb b/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb index 990d2127ee..1b914f0637 100644 --- a/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb +++ b/actionpack/lib/action_dispatch/journey/gtg/transition_table.rb @@ -88,13 +88,13 @@ module ActionDispatch erb = File.read File.join(viz_dir, 'index.html.erb') states = "function tt() { return #{to_json}; }" - fun_routes = paths.shuffle.first(3).map do |ast| + fun_routes = paths.sample(3).map do |ast| ast.map { |n| case n when Nodes::Symbol case n.left when ':id' then rand(100).to_s - when ':format' then %w{ xml json }.shuffle.first + when ':format' then %w{ xml json }.sample else 'omg' end diff --git a/actionpack/lib/action_dispatch/journey/scanner.rb b/actionpack/lib/action_dispatch/journey/scanner.rb index 633be11a2d..19e0bc03d6 100644 --- a/actionpack/lib/action_dispatch/journey/scanner.rb +++ b/actionpack/lib/action_dispatch/journey/scanner.rb @@ -39,18 +39,18 @@ module ActionDispatch [:SLASH, text] when text = @ss.scan(/\*\w+/) [:STAR, text] - when text = @ss.scan(/\(/) + when text = @ss.scan(/(?<!\\)\(/) [:LPAREN, text] - when text = @ss.scan(/\)/) + when text = @ss.scan(/(?<!\\)\)/) [:RPAREN, text] when text = @ss.scan(/\|/) [:OR, text] when text = @ss.scan(/\./) [:DOT, text] - when text = @ss.scan(/:\w+/) + when text = @ss.scan(/(?<!\\):\w+/) [:SYMBOL, text] - when text = @ss.scan(/[\w%\-~]+/) - [:LITERAL, text] + when text = @ss.scan(/(?:[\w%\-~!$&'*+,;=@]|\\:|\\\(|\\\))+/) + [:LITERAL, text.tr('\\', '')] # any char when text = @ss.scan(/./) [:LITERAL, text] diff --git a/actionpack/lib/action_dispatch/journey/visualizer/fsm.css b/actionpack/lib/action_dispatch/journey/visualizer/fsm.css index 50caebaa18..403e16a7bb 100644 --- a/actionpack/lib/action_dispatch/journey/visualizer/fsm.css +++ b/actionpack/lib/action_dispatch/journey/visualizer/fsm.css @@ -16,10 +16,6 @@ h2 { font-size: 0.5em; } -div#chart-2 { - height: 350px; -} - .clearfix {display: inline-block; } .input { overflow: show;} .instruction { color: #666; padding: 0 30px 20px; font-size: 0.9em} diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb index baf9d5779e..f80df78582 100644 --- a/actionpack/lib/action_dispatch/middleware/callbacks.rb +++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb @@ -1,6 +1,6 @@ module ActionDispatch - # Provide callbacks to be executed before and after the request dispatch. + # Provides callbacks to be executed before and after dispatching the request. class Callbacks include ActiveSupport::Callbacks diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index 83ac62a83d..9037bf0e0a 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -120,7 +120,7 @@ module ActionDispatch # the cookie again. This is useful for creating cookies with values that the user is not supposed to change. If a signed # cookie was tampered with by the user (or a 3rd party), nil will be returned. # - # If +secrets.secret_key_base+ and +config.secret_token+ (deprecated) are both set, + # If +secrets.secret_key_base+ and +secrets.secret_token+ (deprecated) are both set, # legacy cookies signed with the old key generator will be transparently upgraded. # # This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+. @@ -143,7 +143,7 @@ module ActionDispatch # Returns a jar that'll automatically encrypt cookie values before sending them to the client and will decrypt them for read. # If the cookie was tampered with by the user (or a 3rd party), nil will be returned. # - # If +secrets.secret_key_base+ and +config.secret_token+ (deprecated) are both set, + # If +secrets.secret_key_base+ and +secrets.secret_token+ (deprecated) are both set, # legacy cookies signed with the old key generator will be transparently upgraded. # # This jar requires that you set a suitable secret for the verification on your app's +secrets.secret_key_base+. @@ -479,7 +479,7 @@ module ActionDispatch end # UpgradeLegacySignedCookieJar is used instead of SignedCookieJar if - # config.secret_token and secrets.secret_key_base are both set. It reads + # secrets.secret_token and secrets.secret_key_base are both set. It reads # legacy cookies signed with the old dummy key generator and re-saves # them using the new key generator to provide a smooth upgrade path. class UpgradeLegacySignedCookieJar < SignedCookieJar #:nodoc: @@ -537,7 +537,7 @@ module ActionDispatch end # UpgradeLegacyEncryptedCookieJar is used by ActionDispatch::Session::CookieStore - # instead of EncryptedCookieJar if config.secret_token and secrets.secret_key_base + # instead of EncryptedCookieJar if secrets.secret_token and secrets.secret_key_base # are both set. It reads legacy cookies signed with the old dummy key generator and # encrypts and re-saves them using the new key generator to provide a smooth upgrade path. class UpgradeLegacyEncryptedCookieJar < EncryptedCookieJar #:nodoc: diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb index 274f6f2f22..c1562fcc0d 100644 --- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb @@ -35,12 +35,25 @@ module ActionDispatch if env['action_dispatch.show_detailed_exceptions'] request = Request.new(env) + traces = wrapper.traces + + trace_to_show = 'Application Trace' + if traces[trace_to_show].empty? && wrapper.rescue_template != 'routing_error' + trace_to_show = 'Full Trace' + end + + if source_to_show = traces[trace_to_show].first + source_to_show_id = source_to_show[:id] + end + template = ActionView::Base.new([RESCUES_TEMPLATE_PATH], request: request, exception: wrapper.exception, - traces: traces_from_wrapper(wrapper), + traces: traces, + show_source_idx: source_to_show_id, + trace_to_show: trace_to_show, routes_inspector: routes_inspector(exception), - source_extract: wrapper.source_extract, + source_extracts: wrapper.source_extracts, line_number: wrapper.line_number, file: wrapper.file ) @@ -93,36 +106,5 @@ module ActionDispatch ActionDispatch::Routing::RoutesInspector.new(@routes_app.routes.routes) end end - - # Augment the exception traces by providing ids for all unique stack frame - def traces_from_wrapper(wrapper) - application_trace = wrapper.application_trace - framework_trace = wrapper.framework_trace - full_trace = wrapper.full_trace - - if application_trace && framework_trace - id_counter = 0 - - application_trace = application_trace.map do |trace| - prev = id_counter - id_counter += 1 - { id: prev, trace: trace } - end - - framework_trace = framework_trace.map do |trace| - prev = id_counter - id_counter += 1 - { id: prev, trace: trace } - end - - full_trace = application_trace + framework_trace - end - - { - "Application Trace" => application_trace, - "Framework Trace" => framework_trace, - "Full Trace" => full_trace - } - end end end diff --git a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb index b98b553c38..a4862e33aa 100644 --- a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb +++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb @@ -6,16 +6,17 @@ module ActionDispatch cattr_accessor :rescue_responses @@rescue_responses = Hash.new(:internal_server_error) @@rescue_responses.merge!( - 'ActionController::RoutingError' => :not_found, - 'AbstractController::ActionNotFound' => :not_found, - 'ActionController::MethodNotAllowed' => :method_not_allowed, - 'ActionController::UnknownHttpMethod' => :method_not_allowed, - 'ActionController::NotImplemented' => :not_implemented, - 'ActionController::UnknownFormat' => :not_acceptable, - 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity, - 'ActionDispatch::ParamsParser::ParseError' => :bad_request, - 'ActionController::BadRequest' => :bad_request, - 'ActionController::ParameterMissing' => :bad_request + 'ActionController::RoutingError' => :not_found, + 'AbstractController::ActionNotFound' => :not_found, + 'ActionController::MethodNotAllowed' => :method_not_allowed, + 'ActionController::UnknownHttpMethod' => :method_not_allowed, + 'ActionController::NotImplemented' => :not_implemented, + 'ActionController::UnknownFormat' => :not_acceptable, + 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity, + 'ActionController::InvalidCrossOriginRequest' => :unprocessable_entity, + 'ActionDispatch::ParamsParser::ParseError' => :bad_request, + 'ActionController::BadRequest' => :bad_request, + 'ActionController::ParameterMissing' => :bad_request ) cattr_accessor :rescue_templates @@ -56,24 +57,52 @@ module ActionDispatch clean_backtrace(:all) end + def traces + appplication_trace_with_ids = [] + framework_trace_with_ids = [] + full_trace_with_ids = [] + + full_trace.each_with_index do |trace, idx| + trace_with_id = { id: idx, trace: trace } + + if application_trace.include?(trace) + appplication_trace_with_ids << trace_with_id + else + framework_trace_with_ids << trace_with_id + end + + full_trace_with_ids << trace_with_id + end + + { + "Application Trace" => appplication_trace_with_ids, + "Framework Trace" => framework_trace_with_ids, + "Full Trace" => full_trace_with_ids + } + end + def self.status_code_for_exception(class_name) Rack::Utils.status_code(@@rescue_responses[class_name]) end - def source_extract - exception.backtrace.map do |trace| + def source_extracts + backtrace.map do |trace| file, line = trace.split(":") line_number = line.to_i + { code: source_fragment(file, line_number), - file: file, line_number: line_number } - end if exception.backtrace + end end private + def backtrace + Array(@exception.backtrace) + end + def original_exception(exception) if registered_original_exception?(exception) exception.original_exception @@ -88,9 +117,9 @@ module ActionDispatch def clean_backtrace(*args) if backtrace_cleaner - backtrace_cleaner.clean(@exception.backtrace, *args) + backtrace_cleaner.clean(backtrace, *args) else - @exception.backtrace + backtrace end end diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb index e90f8b9ce6..a7f95150a4 100644 --- a/actionpack/lib/action_dispatch/middleware/flash.rb +++ b/actionpack/lib/action_dispatch/middleware/flash.rb @@ -79,7 +79,7 @@ module ActionDispatch class FlashHash include Enumerable - def self.from_session_value(value) + def self.from_session_value(value) #:nodoc: flash = case value when FlashHash # Rails 3.1, 3.2 new(value.instance_variable_get(:@flashes), value.instance_variable_get(:@used)) @@ -91,8 +91,11 @@ module ActionDispatch flash.tap(&:sweep) end - - def to_session_value + + # Builds a hash containing the discarded values and the hashes + # representing the flashes. + # If there are no values in @flashes, returns nil. + def to_session_value #:nodoc: return nil if empty? {'discard' => @discard.to_a, 'flashes' => @flashes} end @@ -132,7 +135,7 @@ module ActionDispatch end def key?(name) - @flashes.key? name + @flashes.key? name.to_s end def delete(key) diff --git a/actionpack/lib/action_dispatch/middleware/params_parser.rb b/actionpack/lib/action_dispatch/middleware/params_parser.rb index b426183488..29d43faeed 100644 --- a/actionpack/lib/action_dispatch/middleware/params_parser.rb +++ b/actionpack/lib/action_dispatch/middleware/params_parser.rb @@ -47,7 +47,7 @@ module ActionDispatch else false end - rescue Exception => e # JSON or Ruby code block errors + rescue => e # JSON or Ruby code block errors logger(env).debug "Error occurred while parsing request parameters.\nContents:\n\n#{request.raw_post}" raise ParseError.new(e.message, e) diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index e66c21ef85..002bf8b11a 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -24,9 +24,19 @@ module ActionDispatch path = URI.parser.unescape(path) return false unless path.valid_encoding? - paths = [path, "#{path}#{ext}", "#{path}/index#{ext}"] + paths = [path, "#{path}#{ext}", "#{path}/index#{ext}"].map { |v| + Rack::Utils.clean_path_info v + } - if match = paths.detect {|p| File.file?(File.join(@root, p)) } + if match = paths.detect { |p| + path = File.join(@root, p) + begin + File.file?(path) && File.readable?(path) + rescue SystemCallError + false + end + + } return ::Rack::Utils.escape(match) end end diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb index ba29e26930..e7b913bbe4 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb @@ -1,29 +1,27 @@ -<% if @source_extract %> - <% @source_extract.each_with_index do |extract_source, index| %> - <% if extract_source[:code] %> - <div class="source <%="hidden" if index != 0%>" id="frame-source-<%=index%>"> - <div class="info"> - Extracted source (around line <strong>#<%= extract_source[:line_number] %></strong>): - </div> - <div class="data"> - <table cellpadding="0" cellspacing="0" class="lines"> - <tr> - <td> - <pre class="line_numbers"> - <% extract_source[:code].each_key do |line_number| %> +<% @source_extracts.each_with_index do |source_extract, index| %> + <% if source_extract[:code] %> + <div class="source <%="hidden" if @show_source_idx != index%>" id="frame-source-<%=index%>"> + <div class="info"> + Extracted source (around line <strong>#<%= source_extract[:line_number] %></strong>): + </div> + <div class="data"> + <table cellpadding="0" cellspacing="0" class="lines"> + <tr> + <td> + <pre class="line_numbers"> + <% source_extract[:code].each_key do |line_number| %> <span><%= line_number -%></span> - <% end %> - </pre> - </td> + <% end %> + </pre> + </td> <td width="100%"> <pre> -<% extract_source[:code].each do |line, source| -%><div class="line<%= " active" if line == extract_source[:line_number] -%>"><%= source -%></div><% end -%> +<% source_extract[:code].each do |line, source| -%><div class="line<%= " active" if line == source_extract[:line_number] -%>"><%= source -%></div><% end -%> </pre> </td> - </tr> - </table> - </div> + </tr> + </table> </div> - <% end %> + </div> <% end %> <% end %> diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb index f62caf51d7..ab57b11c7d 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb @@ -12,7 +12,7 @@ <% end %> <% @traces.each do |name, trace| %> - <div id="<%= name.gsub(/\s/, '-') %>" style="display: <%= (name == "Application Trace") ? 'block' : 'none' %>;"> + <div id="<%= name.gsub(/\s/, '-') %>" style="display: <%= (name == @trace_to_show) ? 'block' : 'none' %>;"> <pre><code><% trace.each do |frame| %><a class="trace-frames" data-frame-id="<%= frame[:id] %>" href="#"><%= frame[:trace] %></a><br><% end %></code></pre> </div> <% end %> diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb index 5c016e544e..2a65fd06ad 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/missing_template.html.erb @@ -4,4 +4,8 @@ <div id="container"> <h2><%= h @exception.message %></h2> + + <%= render template: "rescues/_source" %> + <%= render template: "rescues/_trace" %> + <%= render template: "rescues/_request_and_response" %> </div> diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb index 7e9cedb95e..55dd5ddc7b 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb @@ -27,4 +27,6 @@ <%= @routes_inspector.format(ActionDispatch::Routing::HtmlTableFormatter.new(self)) %> <% end %> + + <%= render template: "rescues/_request_and_response" %> </div> diff --git a/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb b/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb index 6ffa242da4..5cee0b5932 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/routes/_table.html.erb @@ -1,6 +1,6 @@ <% content_for :style do %> #route_table { - margin: 0 auto 0; + margin: 0; border-collapse: collapse; } diff --git a/actionpack/lib/action_dispatch/routing/inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb index ea3b2f419d..cfe2237512 100644 --- a/actionpack/lib/action_dispatch/routing/inspector.rb +++ b/actionpack/lib/action_dispatch/routing/inspector.rb @@ -48,7 +48,7 @@ module ActionDispatch def reqs @reqs ||= begin reqs = endpoint - reqs += " #{constraints.to_s}" unless constraints.empty? + reqs += " #{constraints}" unless constraints.empty? reqs end end diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index fc28740828..a8be77f46d 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -4,6 +4,7 @@ require 'active_support/core_ext/hash/slice' require 'active_support/core_ext/enumerable' require 'active_support/core_ext/array/extract_options' require 'active_support/core_ext/module/remove_method' +require 'active_support/core_ext/string/filters' require 'active_support/inflector' require 'action_dispatch/routing/redirection' require 'action_dispatch/routing/endpoint' @@ -243,12 +244,10 @@ module ActionDispatch def app(blocks) if to.respond_to?(:call) Constraints.new(to, blocks, false) + elsif blocks.any? + Constraints.new(dispatcher(defaults), blocks, true) else - if blocks.any? - Constraints.new(dispatcher(defaults), blocks, true) - else - dispatcher(defaults) - end + dispatcher(defaults) end end @@ -282,11 +281,19 @@ module ActionDispatch def split_to(to) case to when Symbol - ActiveSupport::Deprecation.warn "defining a route where `to` is a symbol is deprecated. Please change \"to: :#{to}\" to \"action: :#{to}\"" + ActiveSupport::Deprecation.warn(<<-MSG.squish) + Defining a route where `to` is a symbol is deprecated. + Please change `to: :#{to}` to `action: :#{to}`. + MSG + [nil, to.to_s] when /#/ then to.split('#') when String - ActiveSupport::Deprecation.warn "defining a route where `to` is a controller without an action is deprecated. Please change \"to: :#{to}\" to \"controller: :#{to}\"" + ActiveSupport::Deprecation.warn(<<-MSG.squish) + Defining a route where `to` is a controller without an action is deprecated. + Please change `to: :#{to}` to `controller: :#{to}`. + MSG + [to, nil] else [] @@ -382,7 +389,7 @@ module ActionDispatch # Matches a url pattern to one or more routes. # - # You should not use the `match` method in your router + # You should not use the +match+ method in your router # without specifying an HTTP method. # # If you want to expose your action to both GET and POST, use: @@ -393,7 +400,7 @@ module ActionDispatch # Note that +:controller+, +:action+ and +:id+ are interpreted as url # query parameters and thus available through +params+ in an action. # - # If you want to expose your action to GET, use `get` in the router: + # If you want to expose your action to GET, use +get+ in the router: # # Instead of: # @@ -434,7 +441,7 @@ module ActionDispatch # # Because requesting various HTTP verbs with a single action has security # implications, you must either specify the actions in - # the via options or use one of the HtttpHelpers[rdoc-ref:HttpHelpers] + # the via options or use one of the HttpHelpers[rdoc-ref:HttpHelpers] # instead +match+ # # === Options @@ -448,7 +455,7 @@ module ActionDispatch # The route's action. # # [:param] - # Overrides the default resource identifier `:id` (name of the + # Overrides the default resource identifier +:id+ (name of the # dynamic segment used to generate the routes). # You can access that segment from your controller using # <tt>params[<:param>]</tt>. diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index f51bee3b31..6e3ae36a7f 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -6,6 +6,7 @@ require 'active_support/core_ext/object/to_query' require 'active_support/core_ext/hash/slice' require 'active_support/core_ext/module/remove_method' require 'active_support/core_ext/array/extract_options' +require 'active_support/core_ext/string/filters' require 'action_controller/metal/exceptions' require 'action_dispatch/http/request' require 'action_dispatch/routing/endpoint' @@ -102,7 +103,10 @@ module ActionDispatch end def helpers - ActiveSupport::Deprecation.warn("`named_routes.helpers` is deprecated, please use `route_defined?(route_name)` to see if a named route was defined.") + ActiveSupport::Deprecation.warn(<<-MSG.squish) + `named_routes.helpers` is deprecated, please use `route_defined?(route_name)` + to see if a named route was defined. + MSG @path_helpers + @url_helpers end @@ -134,8 +138,8 @@ module ActionDispatch @url_helpers_module.send :undef_method, url_name end routes[key] = route - define_url_helper @path_helpers_module, route, path_name, route.defaults, name, PATH - define_url_helper @url_helpers_module, route, url_name, route.defaults, name, FULL + define_url_helper @path_helpers_module, route, path_name, route.defaults, name, LEGACY + define_url_helper @url_helpers_module, route, url_name, route.defaults, name, UNKNOWN @path_helpers << path_name @url_helpers << url_name @@ -267,7 +271,7 @@ module ActionDispatch controller_options = t.url_options options = controller_options.merge @options hash = handle_positional_args(controller_options, - inner_options || {}, + deprecate_string_options(inner_options) || {}, args, options, @segment_keys) @@ -289,6 +293,22 @@ module ActionDispatch result.merge!(inner_options) end + + DEPRECATED_STRING_OPTIONS = %w[controller action] + + def deprecate_string_options(options) + options ||= {} + deprecated_string_options = options.keys & DEPRECATED_STRING_OPTIONS + if deprecated_string_options.any? + msg = "Calling URL helpers with string keys #{deprecated_string_options.join(", ")} is deprecated. Use symbols instead." + ActiveSupport::Deprecation.warn(msg) + deprecated_string_options.each do |option| + value = options.delete(option) + options[option.to_sym] = value + end + end + options + end end private @@ -322,6 +342,32 @@ module ActionDispatch PATH = ->(options) { ActionDispatch::Http::URL.path_for(options) } FULL = ->(options) { ActionDispatch::Http::URL.full_url_for(options) } UNKNOWN = ->(options) { ActionDispatch::Http::URL.url_for(options) } + LEGACY = ->(options) { + if options.key?(:only_path) + if options[:only_path] + ActiveSupport::Deprecation.warn(<<-MSG.squish) + You are calling a `*_path` helper with the `only_path` option + explicitly set to `true`. This option will stop working on + path helpers in Rails 5. Simply remove the `only_path: true` + argument from your call as it is redundant when applied to a + path helper. + MSG + + PATH.call(options) + else + ActiveSupport::Deprecation.warn(<<-MSG.squish) + You are calling a `*_path` helper with the `only_path` option + explicitly set to `false`. This option will stop working on + path helpers in Rails 5. Use the corresponding `*_url` helper + instead. + MSG + + FULL.call(options) + end + else + PATH.call(options) + end + } # :startdoc: attr_accessor :formatter, :set, :named_routes, :default_scope, :router @@ -427,7 +473,7 @@ module ActionDispatch RUBY end - def url_helpers(include_path_helpers = true) + def url_helpers(supports_path = true) routes = self Module.new do @@ -454,7 +500,7 @@ module ActionDispatch # named routes... include url_helpers - if include_path_helpers + if supports_path path_helpers = routes.named_routes.path_helpers_module else path_helpers = routes.named_routes.path_helpers_module(true) @@ -472,6 +518,10 @@ module ActionDispatch # UrlFor (included in this module) add extra # conveniences for working with @_routes. define_method(:_routes) { @_routes || routes } + + define_method(:_generate_paths_by_default) do + supports_path + end end end @@ -699,7 +749,7 @@ module ActionDispatch end def find_script_name(options) - options.delete(:script_name) { '' } + options.delete(:script_name) || '' end def path_for(options, route_name = nil) # :nodoc: diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index eb554ec383..dca86858cc 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -184,6 +184,12 @@ module ActionDispatch def _routes_context self end + + private + + def _generate_paths_by_default + true + end end end end diff --git a/actionpack/lib/action_dispatch/testing/assertions.rb b/actionpack/lib/action_dispatch/testing/assertions.rb index 41d00b5e2b..f325c35b57 100644 --- a/actionpack/lib/action_dispatch/testing/assertions.rb +++ b/actionpack/lib/action_dispatch/testing/assertions.rb @@ -15,7 +15,7 @@ module ActionDispatch @html_document ||= if @response.content_type =~ /xml$/ Nokogiri::XML::Document.parse(@response.body) else - Nokogiri::HTML::DocumentFragment.parse(@response.body) + Nokogiri::HTML::Document.parse(@response.body) end end end diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index e06f7037c6..28dc88d317 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -144,12 +144,6 @@ module ActionDispatch old_controller, @controller = @controller, @controller.clone _routes = @routes - # Unfortunately, there is currently an abstraction leak between AC::Base - # and AV::Base which requires having the URL helpers in both AC and AV. - # To do this safely at runtime for tests, we need to bump up the helper serial - # to that the old AV subclass isn't cached. - # - # TODO: Make this unnecessary @controller.singleton_class.send(:include, _routes.url_helpers) @controller.view_context_class = Class.new(@controller.view_context_class) do include _routes.url_helpers diff --git a/actionpack/lib/action_dispatch/testing/assertions/tag.rb b/actionpack/lib/action_dispatch/testing/assertions/tag.rb index 5c2905d1ac..da98b1d6ce 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/tag.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/tag.rb @@ -1,3 +1,3 @@ require 'active_support/deprecation' -ActiveSupport::Deprecation.warn("ActionDispatch::Assertions::TagAssertions has been extracted to the rails-dom-testing gem.") +ActiveSupport::Deprecation.warn('`ActionDispatch::Assertions::TagAssertions` has been extracted to the rails-dom-testing gem.') diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index c300a4ea0d..a9a1576fed 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -326,13 +326,21 @@ module ActionDispatch @integration_session = Integration::Session.new(app) end + def remove! # :nodoc: + @integration_session = nil + end + %w(get post patch put head delete cookies assigns xml_http_request xhr get_via_redirect post_via_redirect).each do |method| define_method(method) do |*args| reset! unless integration_session - reset_template_assertion - # reset the html_document variable, but only for new get/post calls - @html_document = nil unless method == 'cookies' || method == 'assigns' + + # reset the html_document variable, except for cookies/assigns calls + unless method == 'cookies' || method == 'assigns' + @html_document = nil + reset_template_assertion + end + integration_session.__send__(method, *args).tap do copy_session_variables! end @@ -497,7 +505,7 @@ module ActionDispatch end def document_root_element - html_document + html_document.root end end end diff --git a/actionpack/lib/action_pack/gem_version.rb b/actionpack/lib/action_pack/gem_version.rb index 6834845d4f..9b3ea30f69 100644 --- a/actionpack/lib/action_pack/gem_version.rb +++ b/actionpack/lib/action_pack/gem_version.rb @@ -8,7 +8,7 @@ module ActionPack MAJOR = 4 MINOR = 2 TINY = 0 - PRE = "beta2" + PRE = "beta4" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 69312e4c22..63c9ab04c9 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -194,6 +194,7 @@ class ActionDispatch::IntegrationTest < ActiveSupport::TestCase yield temporary_routes ensure self.class.app = old_app + self.remove! silence_warnings { Object.const_set(:SharedTestRoutes, old_routes) } end diff --git a/actionpack/test/controller/flash_hash_test.rb b/actionpack/test/controller/flash_hash_test.rb index 50b36a0567..d979b561f2 100644 --- a/actionpack/test/controller/flash_hash_test.rb +++ b/actionpack/test/controller/flash_hash_test.rb @@ -29,6 +29,15 @@ module ActionDispatch assert_equal 'world', @hash['hello'] end + def test_key + @hash['foo'] = 'bar' + + assert @hash.key?('foo') + assert @hash.key?(:foo) + assert_not @hash.key?('bar') + assert_not @hash.key?(:bar) + end + def test_delete @hash['foo'] = 'bar' @hash.delete 'foo' diff --git a/actionpack/test/controller/helper_test.rb b/actionpack/test/controller/helper_test.rb index 20f99f19ee..936b8c2450 100644 --- a/actionpack/test/controller/helper_test.rb +++ b/actionpack/test/controller/helper_test.rb @@ -60,6 +60,12 @@ class HelpersPathsController < ActionController::Base end end +class HelpersTypoController < ActionController::Base + path = File.expand_path('../../fixtures/helpers_typo', __FILE__) + $:.unshift(path) + self.helpers_path = path +end + module LocalAbcHelper def a() end def b() end @@ -82,6 +88,22 @@ class HelperPathsTest < ActiveSupport::TestCase end end +class HelpersTypoControllerTest < ActiveSupport::TestCase + def setup + @autoload_paths = ActiveSupport::Dependencies.autoload_paths + ActiveSupport::Dependencies.autoload_paths = Array(HelpersTypoController.helpers_path) + end + + def test_helper_typo_error_message + e = assert_raise(NameError) { HelpersTypoController.helper 'admin/users' } + assert_equal "Couldn't find Admin::UsersHelper, expected it to be defined in helpers/admin/users_helper.rb", e.message + end + + def teardown + ActiveSupport::Dependencies.autoload_paths = @autoload_paths + end +end + class HelperTest < ActiveSupport::TestCase class TestController < ActionController::Base attr_accessor :delegate_attr diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index c6380c7ffd..d6219b7626 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -292,7 +292,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest assert_equal({}, cookies.to_hash) assert_equal "OK", body assert_equal "OK", response.body - assert_kind_of Nokogiri::HTML::DocumentFragment, html_document + assert_kind_of Nokogiri::HTML::Document, html_document assert_equal 1, request_count end end @@ -308,7 +308,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest assert_equal({}, cookies.to_hash) assert_equal "Created", body assert_equal "Created", response.body - assert_kind_of Nokogiri::HTML::DocumentFragment, html_document + assert_kind_of Nokogiri::HTML::Document, html_document assert_equal 1, request_count end end @@ -368,7 +368,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest assert_response :redirect assert_response :found assert_equal "<html><body>You are being <a href=\"http://www.example.com/get\">redirected</a>.</body></html>", response.body - assert_kind_of Nokogiri::HTML::DocumentFragment, html_document + assert_kind_of Nokogiri::HTML::Document, html_document assert_equal 1, request_count follow_redirect! @@ -615,6 +615,8 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest get 'bar', :to => 'application_integration_test/test#index', :as => :bar mount MountedApp => '/mounted', :as => "mounted" + get 'fooz' => proc { |env| [ 200, {'X-Cascade' => 'pass'}, [ "omg" ] ] }, :anchor => false + get 'fooz', :to => 'application_integration_test/test#index' end def app @@ -631,6 +633,12 @@ class ApplicationIntegrationTest < ActionDispatch::IntegrationTest assert_equal '/mounted/baz', mounted.baz_path end + test "path after cascade pass" do + get '/fooz' + assert_equal 'index', response.body + assert_equal '/fooz', path + end + test "route helpers after controller access" do get '/' assert_equal '/', empty_string_path @@ -806,3 +814,39 @@ class HeadWithStatusActionIntegrationTest < ActionDispatch::IntegrationTest assert_response :ok end end + +class IntegrationWithRoutingTest < ActionDispatch::IntegrationTest + class FooController < ActionController::Base + def index + render plain: 'ok' + end + end + + def test_with_routing_resets_session + klass_namespace = self.class.name.underscore + + with_routing do |routes| + routes.draw do + namespace klass_namespace do + resources :foo, path: '/with' + end + end + + get '/integration_with_routing_test/with' + assert_response 200 + assert_equal 'ok', response.body + end + + with_routing do |routes| + routes.draw do + namespace klass_namespace do + resources :foo, path: '/routing' + end + end + + get '/integration_with_routing_test/routing' + assert_response 200 + assert_equal 'ok', response.body + end + end +end diff --git a/actionpack/test/controller/mime/respond_to_test.rb b/actionpack/test/controller/mime/respond_to_test.rb index 1bc7ad3015..66d2fd7716 100644 --- a/actionpack/test/controller/mime/respond_to_test.rb +++ b/actionpack/test/controller/mime/respond_to_test.rb @@ -579,10 +579,10 @@ class RespondToControllerTest < ActionController::TestCase end get :using_defaults - assert_equal "using_defaults - #{[:html].to_s}", @response.body + assert_equal "using_defaults - #{[:html]}", @response.body get :using_defaults, :format => "xml" - assert_equal "using_defaults - #{[:xml].to_s}", @response.body + assert_equal "using_defaults - #{[:xml]}", @response.body end def test_format_with_custom_response_type diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index c18914cc8e..f46b32e019 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -1001,6 +1001,9 @@ class RouteSetTest < ActiveSupport::TestCase assert_equal "http://test.host/people?baz=bar#location", controller.send(:index_url, :baz => "bar", :anchor => 'location') + + assert_equal "http://test.host/people", controller.send(:index_url, anchor: nil) + assert_equal "http://test.host/people", controller.send(:index_url, anchor: false) end def test_named_route_url_method_with_port @@ -1383,7 +1386,7 @@ class RouteSetTest < ActiveSupport::TestCase url = controller.url_for({ :controller => "connection", :only_path => true }) assert_equal "/connection/connection", url - url = controller.url_for({ :use_route => :family_connection, + url = controller.url_for({ :use_route => "family_connection", :controller => "connection", :only_path => true }) assert_equal "/connection", url end diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb index 9d7abd5e94..ba2ff7d12c 100644 --- a/actionpack/test/controller/test_case_test.rb +++ b/actionpack/test/controller/test_case_test.rb @@ -1,6 +1,7 @@ require 'abstract_unit' require 'controller/fake_controllers' require 'active_support/json/decoding' +require 'rails/engine' class TestCaseTest < ActionController::TestCase class TestController < ActionController::Base @@ -132,6 +133,14 @@ XML render :nothing => true end + def test_without_body + render html: '<div class="foo"></div>'.html_safe + end + + def test_with_body + render html: '<body class="foo"></body>'.html_safe + end + private def generate_url(opts) @@ -179,6 +188,19 @@ XML end end + def test_assert_select_without_body + get :test_without_body + + assert_select 'body', 0 + assert_select 'div.foo' + end + + def test_assert_select_with_body + get :test_with_body + + assert_select 'body.foo' + end + def test_url_options_reset @controller = DefaultUrlOptionsCachingController.new get :test_url_options_reset @@ -499,6 +521,18 @@ XML end end + def test_use_route + with_routing do |set| + set.draw do + get 'via_unnamed_route', to: 'test_case_test/test#test_uri' + get 'via_named_route', as: :a_named_route, to: 'test_case_test/test#test_uri' + end + + assert_deprecated { get :test_uri, use_route: :a_named_route } + assert_equal '/via_named_route', @response.body + end + end + def test_assert_realistic_path_parameters get :test_params, :id => 20, :foo => Object.new @@ -720,6 +754,57 @@ XML end end +module EngineControllerTests + class Engine < ::Rails::Engine + isolate_namespace EngineControllerTests + + routes.draw do + get '/' => 'bar#index' + end + end + + class BarController < ActionController::Base + def index + render :text => 'bar' + end + end + + class BarControllerTest < ActionController::TestCase + tests BarController + + def test_engine_controller_route + get :index + assert_equal @response.body, 'bar' + end + end + + class BarControllerTestWithExplicitRouteSet < ActionController::TestCase + tests BarController + + def setup + @routes = Engine.routes + end + + def test_engine_controller_route + get :index + assert_equal @response.body, 'bar' + end + end + + class BarControllerTestWithHostApplicationRouteSet < ActionController::TestCase + tests BarController + + def test_use_route + with_routing do |set| + set.draw { mount Engine => '/foo' } + + assert_deprecated { get :index, use_route: :foo } + assert_equal @response.body, 'bar' + end + end + end +end + class InferringClassNameTest < ActionController::TestCase def test_determine_controller_class assert_equal ContentController, determine_class("ContentControllerTest") diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index 969129d9ba..0ffa2d2a03 100644 --- a/actionpack/test/controller/url_for_test.rb +++ b/actionpack/test/controller/url_for_test.rb @@ -25,8 +25,7 @@ module AbstractController path = klass.new.fun_path({:controller => :articles, :baz => "baz", - :zot => "zot", - :only_path => true }) + :zot => "zot"}) # :bar key isn't provided assert_equal '/foo/zot', path end @@ -55,6 +54,20 @@ module AbstractController ) end + def test_nil_anchor + assert_equal( + '/c/a', + W.new.url_for(only_path: true, controller: 'c', action: 'a', anchor: nil) + ) + end + + def test_false_anchor + assert_equal( + '/c/a', + W.new.url_for(only_path: true, controller: 'c', action: 'a', anchor: false) + ) + end + def test_anchor_should_call_to_param assert_equal('/c/a#anchor', W.new.url_for(:only_path => true, :controller => 'c', :action => 'a', :anchor => Struct.new(:to_param).new('anchor')) @@ -277,6 +290,13 @@ module AbstractController end end + def test_using_nil_script_name_properly_concats_with_original_script_name + add_host! + assert_equal('https://www.basecamphq.com/subdir/c/a/i', + W.new.url_for(:controller => 'c', :action => 'a', :id => 'i', :protocol => 'https', :script_name => nil, :original_script_name => '/subdir') + ) + end + def test_only_path with_routing do |set| set.draw do @@ -291,7 +311,7 @@ module AbstractController assert_equal '/brave/new/world', controller.url_for(:controller => 'brave', :action => 'new', :id => 'world', :only_path => true) - assert_equal("/home/sweet/home/alabama", controller.home_path(:user => 'alabama', :host => 'unused', :only_path => true)) + assert_equal("/home/sweet/home/alabama", controller.home_path(:user => 'alabama', :host => 'unused')) assert_equal("/home/sweet/home/alabama", controller.home_path('alabama')) end end diff --git a/actionpack/test/controller/webservice_test.rb b/actionpack/test/controller/webservice_test.rb index d80b0e2da0..2b109ff19e 100644 --- a/actionpack/test/controller/webservice_test.rb +++ b/actionpack/test/controller/webservice_test.rb @@ -83,6 +83,16 @@ class WebServiceTest < ActionDispatch::IntegrationTest end end + def test_parsing_json_doesnot_rescue_exception + with_test_route_set do + with_params_parsers Mime::JSON => Proc.new { |data| raise Interrupt } do + assert_raises(Interrupt) do + post "/", '{"title":"JSON"}}', 'CONTENT_TYPE' => 'application/json' + end + end + end + end + private def with_params_parsers(parsers = {}) old_session = @integration_session diff --git a/actionpack/test/dispatch/debug_exceptions_test.rb b/actionpack/test/dispatch/debug_exceptions_test.rb index 0add9fa3b0..5e87744f6b 100644 --- a/actionpack/test/dispatch/debug_exceptions_test.rb +++ b/actionpack/test/dispatch/debug_exceptions_test.rb @@ -19,6 +19,10 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest @closed = true end + def method_that_raises + raise StandardError.new 'error in framework' + end + def call(env) env['action_dispatch.show_detailed_exceptions'] = @detailed req = ActionDispatch::Request.new(env) @@ -39,6 +43,8 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest raise ActionController::InvalidAuthenticityToken when "/not_found_original_exception" raise ActionView::Template::Error.new('template', AbstractController::ActionNotFound.new) + when "/missing_template" + raise ActionView::MissingTemplate.new(%w(foo), 'foo/index', %w(foo), false, 'mailer') when "/bad_request" raise ActionController::BadRequest when "/missing_keys" @@ -57,7 +63,8 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest {}) raise ActionView::Template::Error.new(template, e) end - + when "/framework_raises" + method_that_raises else raise "puke!" end @@ -115,6 +122,15 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest assert_no_match '<|>', routing_table, "there should not be escaped html in the output" end + test 'displays request and response info when a RoutingError occurs' do + @app = DevelopmentApp + + get "/pass", {}, {'action_dispatch.show_exceptions' => true} + + assert_select 'h2', /Request/ + assert_select 'h2', /Response/ + end + test "rescue with diagnostics message" do @app = DevelopmentApp @@ -270,6 +286,22 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest end end + test 'display backtrace on template missing errors' do + @app = DevelopmentApp + + get "/missing_template", nil, {} + + assert_select "header h1", /Template is missing/ + + assert_select "#container h2", /^Missing template/ + + assert_select '#Application-Trace' + assert_select '#Framework-Trace' + assert_select '#Full-Trace' + + assert_select 'h2', /Request/ + end + test 'display backtrace when error type is SyntaxError wrapped by ActionView::Template::Error' do @app = DevelopmentApp @@ -280,4 +312,39 @@ class DebugExceptionsTest < ActionDispatch::IntegrationTest assert_select 'pre code', /\(eval\):1: syntax error, unexpected/ end end + + test 'debug exceptions app shows user code that caused the error in source view' do + @app = DevelopmentApp + Rails.stubs(:root).returns(Pathname.new('.')) + cleaner = ActiveSupport::BacktraceCleaner.new.tap do |bc| + bc.add_silencer { |line| line =~ /method_that_raises/ } + bc.add_silencer { |line| line !~ %r{test/dispatch/debug_exceptions_test.rb} } + end + + get '/framework_raises', {}, {'action_dispatch.backtrace_cleaner' => cleaner} + + # Assert correct error + assert_response 500 + assert_select 'h2', /error in framework/ + + # assert source view line is the call to method_that_raises + assert_select 'div.source:not(.hidden)' do + assert_select 'pre .line.active', /method_that_raises/ + end + + # assert first source view (hidden) that throws the error + assert_select 'div.source:first' do + assert_select 'pre .line.active', /raise StandardError\.new/ + end + + # assert application trace refers to line that calls method_that_raises is first + assert_select '#Application-Trace' do + assert_select 'pre code a:first', %r{test/dispatch/debug_exceptions_test\.rb:\d+:in `call} + end + + # assert framework trace that that threw the error is first + assert_select '#Framework-Trace' do + assert_select 'pre code a:first', /method_that_raises/ + end + end end diff --git a/actionpack/test/dispatch/exception_wrapper_test.rb b/actionpack/test/dispatch/exception_wrapper_test.rb new file mode 100644 index 0000000000..d7408164ba --- /dev/null +++ b/actionpack/test/dispatch/exception_wrapper_test.rb @@ -0,0 +1,97 @@ +require 'abstract_unit' + +module ActionDispatch + class ExceptionWrapperTest < ActionDispatch::IntegrationTest + class TestError < StandardError + attr_reader :backtrace + + def initialize(*backtrace) + @backtrace = backtrace.flatten + end + end + + class BadlyDefinedError < StandardError + def backtrace + nil + end + end + + setup do + Rails.stubs(:root).returns(Pathname.new('.')) + + cleaner = ActiveSupport::BacktraceCleaner.new + cleaner.add_silencer { |line| line !~ /^lib/ } + + @environment = { 'action_dispatch.backtrace_cleaner' => cleaner } + end + + test '#source_extracts fetches source fragments for every backtrace entry' do + exception = TestError.new("lib/file.rb:42:in `index'") + wrapper = ExceptionWrapper.new({}, exception) + + wrapper.expects(:source_fragment).with('lib/file.rb', 42).returns('foo') + + assert_equal [ code: 'foo', line_number: 42 ], wrapper.source_extracts + end + + + test '#application_trace returns traces only from the application' do + exception = TestError.new(caller.prepend("lib/file.rb:42:in `index'")) + wrapper = ExceptionWrapper.new(@environment, exception) + + assert_equal [ "lib/file.rb:42:in `index'" ], wrapper.application_trace + end + + test '#application_trace cannot be nil' do + nil_backtrace_wrapper = ExceptionWrapper.new(@environment, BadlyDefinedError.new) + nil_cleaner_wrapper = ExceptionWrapper.new({}, BadlyDefinedError.new) + + assert_equal [], nil_backtrace_wrapper.application_trace + assert_equal [], nil_cleaner_wrapper.application_trace + end + + test '#framework_trace returns traces outside the application' do + exception = TestError.new(caller.prepend("lib/file.rb:42:in `index'")) + wrapper = ExceptionWrapper.new(@environment, exception) + + assert_equal caller, wrapper.framework_trace + end + + test '#framework_trace cannot be nil' do + nil_backtrace_wrapper = ExceptionWrapper.new(@environment, BadlyDefinedError.new) + nil_cleaner_wrapper = ExceptionWrapper.new({}, BadlyDefinedError.new) + + assert_equal [], nil_backtrace_wrapper.framework_trace + assert_equal [], nil_cleaner_wrapper.framework_trace + end + + test '#full_trace returns application and framework traces' do + exception = TestError.new(caller.prepend("lib/file.rb:42:in `index'")) + wrapper = ExceptionWrapper.new(@environment, exception) + + assert_equal exception.backtrace, wrapper.full_trace + end + + test '#full_trace cannot be nil' do + nil_backtrace_wrapper = ExceptionWrapper.new(@environment, BadlyDefinedError.new) + nil_cleaner_wrapper = ExceptionWrapper.new({}, BadlyDefinedError.new) + + assert_equal [], nil_backtrace_wrapper.full_trace + assert_equal [], nil_cleaner_wrapper.full_trace + end + + test '#traces returns every trace by category enumerated with an index' do + exception = TestError.new("lib/file.rb:42:in `index'", "/gems/rack.rb:43:in `index'") + wrapper = ExceptionWrapper.new(@environment, exception) + + assert_equal({ + 'Application Trace' => [ id: 0, trace: "lib/file.rb:42:in `index'" ], + 'Framework Trace' => [ id: 1, trace: "/gems/rack.rb:43:in `index'" ], + 'Full Trace' => [ + { id: 0, trace: "lib/file.rb:42:in `index'" }, + { id: 1, trace: "/gems/rack.rb:43:in `index'" } + ] + }, wrapper.traces) + end + end +end diff --git a/actionpack/test/dispatch/routing/route_set_test.rb b/actionpack/test/dispatch/routing/route_set_test.rb index c465d56bde..5a39119446 100644 --- a/actionpack/test/dispatch/routing/route_set_test.rb +++ b/actionpack/test/dispatch/routing/route_set_test.rb @@ -69,6 +69,86 @@ module ActionDispatch end end + test "only_path: true with *_url and no :host option" do + draw do + get 'foo', to: SimpleApp.new('foo#index') + end + + assert_equal '/foo', url_helpers.foo_url(only_path: true) + end + + test "only_path: false with *_url and no :host option" do + draw do + get 'foo', to: SimpleApp.new('foo#index') + end + + assert_raises ArgumentError do + assert_equal 'http://example.com/foo', url_helpers.foo_url(only_path: false) + end + end + + test "only_path: false with *_url and local :host option" do + draw do + get 'foo', to: SimpleApp.new('foo#index') + end + + assert_equal 'http://example.com/foo', url_helpers.foo_url(only_path: false, host: 'example.com') + end + + test "only_path: false with *_url and global :host option" do + @set.default_url_options = { host: 'example.com' } + + draw do + get 'foo', to: SimpleApp.new('foo#index') + end + + assert_equal 'http://example.com/foo', url_helpers.foo_url(only_path: false) + end + + test "only_path: true with *_path" do + draw do + get 'foo', to: SimpleApp.new('foo#index') + end + + assert_deprecated do + assert_equal '/foo', url_helpers.foo_path(only_path: true) + end + end + + test "only_path: false with *_path with global :host option" do + @set.default_url_options = { host: 'example.com' } + + draw do + get 'foo', to: SimpleApp.new('foo#index') + end + + assert_deprecated do + assert_equal 'http://example.com/foo', url_helpers.foo_path(only_path: false) + end + end + + test "only_path: false with *_path with local :host option" do + draw do + get 'foo', to: SimpleApp.new('foo#index') + end + + assert_deprecated do + assert_equal 'http://example.com/foo', url_helpers.foo_path(only_path: false, host: 'example.com') + end + end + + test "only_path: false with *_path with no :host option" do + draw do + get 'foo', to: SimpleApp.new('foo#index') + end + + assert_deprecated do + assert_raises ArgumentError do + assert_equal 'http://example.com/foo', url_helpers.foo_path(only_path: false) + end + end + end + test "explicit keys win over implicit keys" do draw do resources :foo do @@ -80,6 +160,26 @@ module ActionDispatch assert_equal '/foo/1/bar/2', url_helpers.foo_bar_path(2, foo_id: 1) end + test "stringified controller and action keys are properly symbolized" do + draw do + root 'foo#bar' + end + + assert_deprecated do + assert_equal '/', url_helpers.root_path('controller' => 'foo', 'action' => 'bar') + end + end + + test "mix of string and symbol keys are properly symbolized" do + draw do + root 'foo#bar' + end + + assert_deprecated do + assert_equal '/', url_helpers.root_path('controller' => 'foo', :action => 'bar') + end + end + private def draw(&block) @set.draw(&block) diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index d141210ad9..d0a624784a 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -4420,7 +4420,7 @@ class TestUrlGenerationErrors < ActionDispatch::IntegrationTest include Routes.url_helpers - test "url helpers raise a helpful error message whem generation fails" do + test "url helpers raise a helpful error message when generation fails" do url, missing = { action: 'show', controller: 'products', id: nil }, [:id] message = "No route matches #{url.inspect} missing required keys: #{missing.inspect}" diff --git a/actionpack/test/dispatch/static_test.rb b/actionpack/test/dispatch/static_test.rb index 6f7373201c..7f1207eaed 100644 --- a/actionpack/test/dispatch/static_test.rb +++ b/actionpack/test/dispatch/static_test.rb @@ -200,7 +200,8 @@ class StaticTest < ActiveSupport::TestCase } def setup - @app = ActionDispatch::Static.new(DummyApp, "#{FIXTURE_LOAD_PATH}/public", "public, max-age=60") + @root = "#{FIXTURE_LOAD_PATH}/public" + @app = ActionDispatch::Static.new(DummyApp, @root, "public, max-age=60") end def public_path @@ -208,11 +209,28 @@ class StaticTest < ActiveSupport::TestCase end include StaticTests + + def test_custom_handler_called_when_file_is_outside_root + filename = 'shared.html.erb' + assert File.exist?(File.join(@root, '..', filename)) + env = { + "REQUEST_METHOD"=>"GET", + "REQUEST_PATH"=>"/..%2F#{filename}", + "PATH_INFO"=>"/..%2F#{filename}", + "REQUEST_URI"=>"/..%2F#{filename}", + "HTTP_VERSION"=>"HTTP/1.1", + "SERVER_NAME"=>"localhost", + "SERVER_PORT"=>"8080", + "QUERY_STRING"=>"" + } + assert_equal(DummyApp.call(nil), @app.call(env)) + end end class StaticEncodingTest < StaticTest def setup - @app = ActionDispatch::Static.new(DummyApp, "#{FIXTURE_LOAD_PATH}/公共", "public, max-age=60") + @root = "#{FIXTURE_LOAD_PATH}/公共" + @app = ActionDispatch::Static.new(DummyApp, @root, "public, max-age=60") end def public_path diff --git a/actionpack/test/dispatch/template_assertions_test.rb b/actionpack/test/dispatch/template_assertions_test.rb index 3c393f937b..7278754b49 100644 --- a/actionpack/test/dispatch/template_assertions_test.rb +++ b/actionpack/test/dispatch/template_assertions_test.rb @@ -10,7 +10,7 @@ class AssertTemplateController < ActionController::Base end def render_with_layout - @variable_for_layout = nil + @variable_for_layout = 'hello' render 'test/hello_world', layout: "layouts/standard" end @@ -95,4 +95,16 @@ class AssertTemplateControllerTest < ActionDispatch::IntegrationTest session.assert_template file: nil end end + + def test_assigns_do_not_reset_template_assertion + get '/assert_template/render_with_layout' + assert_equal 'hello', assigns(:variable_for_layout) + assert_template layout: 'layouts/standard' + end + + def test_cookies_do_not_reset_template_assertion + get '/assert_template/render_with_layout' + cookies + assert_template layout: 'layouts/standard' + end end diff --git a/actionpack/test/fixtures/helpers_typo/admin/users_helper.rb b/actionpack/test/fixtures/helpers_typo/admin/users_helper.rb new file mode 100644 index 0000000000..7d2326e04d --- /dev/null +++ b/actionpack/test/fixtures/helpers_typo/admin/users_helper.rb @@ -0,0 +1,5 @@ +module Admin + module UsersHelpeR + end +end + diff --git a/actionpack/test/journey/route/definition/scanner_test.rb b/actionpack/test/journey/route/definition/scanner_test.rb index 624e6df51a..7a510f1e07 100644 --- a/actionpack/test/journey/route/definition/scanner_test.rb +++ b/actionpack/test/journey/route/definition/scanner_test.rb @@ -11,12 +11,25 @@ module ActionDispatch # /page/:id(/:action)(.:format) def test_tokens [ - ['/', [[:SLASH, '/']]], - ['*omg', [[:STAR, '*omg']]], - ['/page', [[:SLASH, '/'], [:LITERAL, 'page']]], - ['/~page', [[:SLASH, '/'], [:LITERAL, '~page']]], - ['/pa-ge', [[:SLASH, '/'], [:LITERAL, 'pa-ge']]], - ['/:page', [[:SLASH, '/'], [:SYMBOL, ':page']]], + ['/', [[:SLASH, '/']]], + ['*omg', [[:STAR, '*omg']]], + ['/page', [[:SLASH, '/'], [:LITERAL, 'page']]], + ['/page!', [[:SLASH, '/'], [:LITERAL, 'page!']]], + ['/page$', [[:SLASH, '/'], [:LITERAL, 'page$']]], + ['/page&', [[:SLASH, '/'], [:LITERAL, 'page&']]], + ["/page'", [[:SLASH, '/'], [:LITERAL, "page'"]]], + ['/page*', [[:SLASH, '/'], [:LITERAL, 'page*']]], + ['/page+', [[:SLASH, '/'], [:LITERAL, 'page+']]], + ['/page,', [[:SLASH, '/'], [:LITERAL, 'page,']]], + ['/page;', [[:SLASH, '/'], [:LITERAL, 'page;']]], + ['/page=', [[:SLASH, '/'], [:LITERAL, 'page=']]], + ['/page@', [[:SLASH, '/'], [:LITERAL, 'page@']]], + ['/page\:', [[:SLASH, '/'], [:LITERAL, 'page:']]], + ['/page\(', [[:SLASH, '/'], [:LITERAL, 'page(']]], + ['/page\)', [[:SLASH, '/'], [:LITERAL, 'page)']]], + ['/~page', [[:SLASH, '/'], [:LITERAL, '~page']]], + ['/pa-ge', [[:SLASH, '/'], [:LITERAL, 'pa-ge']]], + ['/:page', [[:SLASH, '/'], [:SYMBOL, ':page']]], ['/(:page)', [ [:SLASH, '/'], [:LPAREN, '('], diff --git a/actionpack/test/journey/router_test.rb b/actionpack/test/journey/router_test.rb index 8e90d4100f..19c61b5914 100644 --- a/actionpack/test/journey/router_test.rb +++ b/actionpack/test/journey/router_test.rb @@ -201,6 +201,16 @@ module ActionDispatch assert_match(/missing required keys: \[:id\]/, error.message) end + def test_does_not_include_missing_keys_message + route_name = "gorby_thunderhorse" + + error = assert_raises(ActionController::UrlGenerationError) do + @formatter.generate(route_name, { }, { }) + end + + assert_no_match(/missing required keys: \[\]/, error.message) + end + def test_X_Cascade add_routes @router, [ "/messages(.:format)" ] resp = @router.serve(rails_env({ 'REQUEST_METHOD' => 'GET', 'PATH_INFO' => '/lol' })) @@ -405,7 +415,7 @@ module ActionDispatch def test_generate_with_name path = Path::Pattern.from_string '/:controller(/:action)' - @router.routes.add_route @app, path, {}, {}, {} + @router.routes.add_route @app, path, {}, {}, "tasks" path, params = @formatter.generate( "tasks", diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md index 8ac74dc938..de65543137 100644 --- a/actionview/CHANGELOG.md +++ b/actionview/CHANGELOG.md @@ -1,3 +1,28 @@ +* Local variable in a partial is now available even if a falsy value is + passed to `:object` when rendering a partial. + + Fixes #17373. + + *Agis Anastasopoulos* + +* Add support for `:enforce_utf8` option in `form_for`. + + This is the same option that was added in 06388b0 to `form_tag` and allows + users to skip the insertion of the UTF8 enforcer tag in a form. + + * claudiob * + +* Fix a bug that <%= foo(){ %> and <%= foo()do %> in view templates were not regarded + as Ruby block calls. + + * Akira Matsuda * + +* Update `select_tag` to work correctly with `:include_blank` option passing a string. + + Fixes #16483. + + *Frank Groeneveld* + * Changed the meaning of `render "foo/bar"`. Previously, calling `render "foo/bar"` in a controller action is equivalent diff --git a/actionview/actionview.gemspec b/actionview/actionview.gemspec index e43c19b018..28407521cc 100644 --- a/actionview/actionview.gemspec +++ b/actionview/actionview.gemspec @@ -24,7 +24,7 @@ Gem::Specification.new do |s| s.add_dependency 'builder', '~> 3.1' s.add_dependency 'erubis', '~> 2.7.0' s.add_dependency 'rails-html-sanitizer', '~> 1.0', '>= 1.0.1' - s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.3' + s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.5' s.add_development_dependency 'actionpack', version s.add_development_dependency 'activemodel', version diff --git a/actionview/lib/action_view/gem_version.rb b/actionview/lib/action_view/gem_version.rb index 076b8ec30b..752eafee3c 100644 --- a/actionview/lib/action_view/gem_version.rb +++ b/actionview/lib/action_view/gem_version.rb @@ -8,7 +8,7 @@ module ActionView MAJOR = 4 MINOR = 2 TINY = 0 - PRE = "beta2" + PRE = "beta4" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/actionview/lib/action_view/helpers/date_helper.rb b/actionview/lib/action_view/helpers/date_helper.rb index 9272bb5c10..bd7b36c352 100644 --- a/actionview/lib/action_view/helpers/date_helper.rb +++ b/actionview/lib/action_view/helpers/date_helper.rb @@ -177,7 +177,7 @@ module ActionView # and +:name+ (string). A format string would be something like "%{name} (%<number>02d)" for example. # See <tt>Kernel.sprintf</tt> for documentation on format sequences. # * <tt>:date_separator</tt> - Specifies a string to separate the date fields. Default is "" (i.e. nothing). - # * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Date.today.year - 5</tt>if + # * <tt>:start_year</tt> - Set the start year for the year select. Default is <tt>Date.today.year - 5</tt> if # you are creating new record. While editing existing record, <tt>:start_year</tt> defaults to # the current selected year minus 5. # * <tt>:end_year</tt> - Set the end year for the year select. Default is <tt>Date.today.year + 5</tt> if @@ -1035,7 +1035,7 @@ module ActionView def build_selects_from_types(order) select = '' first_visible = order.find { |type| !@options[:"discard_#{type}"] } - order.reverse.each do |type| + order.reverse_each do |type| separator = separator(type) unless type == first_visible # don't add before first visible field select.insert(0, separator.to_s + send("select_#{type}").to_s) end diff --git a/actionview/lib/action_view/helpers/form_helper.rb b/actionview/lib/action_view/helpers/form_helper.rb index 038f9e384b..6d10b41bd5 100644 --- a/actionview/lib/action_view/helpers/form_helper.rb +++ b/actionview/lib/action_view/helpers/form_helper.rb @@ -164,6 +164,23 @@ module ActionView # * <tt>:namespace</tt> - A namespace for your form to ensure uniqueness of # id attributes on form elements. The namespace attribute will be prefixed # with underscore on the generated HTML id. + # * <tt>:method</tt> - The method to use when submitting the form, usually + # either "get" or "post". If "patch", "put", "delete", or another verb + # is used, a hidden input with name <tt>_method</tt> is added to + # simulate the verb over post. + # * <tt>:authenticity_token</tt> - Authenticity token to use in the form. + # Use only if you need to pass custom authenticity token string, or to + # not add authenticity_token field at all (by passing <tt>false</tt>). + # Remote forms may omit the embedded authenticity token by setting + # <tt>config.action_view.embed_authenticity_token_in_remote_forms = false</tt>. + # This is helpful when you're fragment-caching the form. Remote forms + # get the authenticity token from the <tt>meta</tt> tag, so embedding is + # unnecessary unless you support browsers without JavaScript. + # * <tt>:remote</tt> - If set to true, will allow the Unobtrusive + # JavaScript drivers to control the submit behavior. By default this + # behavior is an ajax submit. + # * <tt>:enforce_utf8</tt> - If set to false, a hidden input with name + # utf8 is not output. # * <tt>:html</tt> - Optional HTML attributes for the form tag. # # Also note that +form_for+ doesn't create an exclusive scope. It's still @@ -420,6 +437,7 @@ module ActionView html_options[:data] = options.delete(:data) if options.has_key?(:data) html_options[:remote] = options.delete(:remote) if options.has_key?(:remote) html_options[:method] = options.delete(:method) if options.has_key?(:method) + html_options[:enforce_utf8] = options.delete(:enforce_utf8) if options.has_key?(:enforce_utf8) html_options[:authenticity_token] = options.delete(:authenticity_token) builder = instantiate_builder(object_name, object, options) @@ -1231,8 +1249,8 @@ module ActionView # end # # The above code creates a new method +div_radio_button+ which wraps a div - # around the a new radio button. Note that when options are passed in, you - # must called +objectify_options+ in order for the model object to get + # around the new radio button. Note that when options are passed in, you + # must call +objectify_options+ in order for the model object to get # correctly passed to the method. If +objectify_options+ is not called, # then the newly created helper will not be linked back to the model. # diff --git a/actionview/lib/action_view/helpers/form_tag_helper.rb b/actionview/lib/action_view/helpers/form_tag_helper.rb index ff5d278b85..93c04fbec6 100644 --- a/actionview/lib/action_view/helpers/form_tag_helper.rb +++ b/actionview/lib/action_view/helpers/form_tag_helper.rb @@ -133,12 +133,20 @@ module ActionView option_tags ||= "" html_name = (options[:multiple] == true && !name.to_s.ends_with?("[]")) ? "#{name}[]" : name - if options.delete(:include_blank) - option_tags = content_tag(:option, '', :value => '').safe_concat(option_tags) + if options.include?(:include_blank) + include_blank = options.delete(:include_blank) + + if include_blank == true + include_blank = '' + end + + if include_blank + option_tags = content_tag(:option, include_blank, value: '').safe_concat(option_tags) + end end if prompt = options.delete(:prompt) - option_tags = content_tag(:option, prompt, :value => '').safe_concat(option_tags) + option_tags = content_tag(:option, prompt, value: '').safe_concat(option_tags) end content_tag :select, option_tags, { "name" => html_name, "id" => sanitize_to_id(name) }.update(options.stringify_keys) @@ -224,7 +232,7 @@ module ActionView # # => <input id="collected_input" name="collected_input" onchange="alert('Input collected!')" # # type="hidden" value="" /> def hidden_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.stringify_keys.update("type" => "hidden")) + text_field_tag(name, value, options.merge(type: :hidden)) end # Creates a file upload field. If you are using file uploads then you will also need @@ -263,7 +271,7 @@ module ActionView # file_field_tag 'file', accept: 'text/html', class: 'upload', value: 'index.html' # # => <input accept="text/html" class="upload" id="file" name="file" type="file" value="index.html" /> def file_field_tag(name, options = {}) - text_field_tag(name, nil, options.update("type" => "file")) + text_field_tag(name, nil, options.merge(type: :file)) end # Creates a password field, a masked text field that will hide the users input behind a mask character. @@ -296,7 +304,7 @@ module ActionView # password_field_tag 'pin', '1234', maxlength: 4, size: 6, class: "pin_input" # # => <input class="pin_input" id="pin" maxlength="4" name="pin" size="6" type="password" value="1234" /> def password_field_tag(name = "password", value = nil, options = {}) - text_field_tag(name, value, options.update("type" => "password")) + text_field_tag(name, value, options.merge(type: :password)) end # Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions. @@ -571,7 +579,7 @@ module ActionView # color_field_tag 'color', '#DEF726', class: 'special_input', disabled: true # # => <input disabled="disabled" class="special_input" id="color" name="color" type="color" value="#DEF726" /> def color_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.stringify_keys.update("type" => "color")) + text_field_tag(name, value, options.merge(type: :color)) end # Creates a text field of type "search". @@ -592,7 +600,7 @@ module ActionView # search_field_tag 'search', 'Enter your search query here', class: 'special_input', disabled: true # # => <input disabled="disabled" class="special_input" id="search" name="search" type="search" value="Enter your search query here" /> def search_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.stringify_keys.update("type" => "search")) + text_field_tag(name, value, options.merge(type: :search)) end # Creates a text field of type "tel". @@ -613,7 +621,7 @@ module ActionView # telephone_field_tag 'tel', '0123456789', class: 'special_input', disabled: true # # => <input disabled="disabled" class="special_input" id="tel" name="tel" type="tel" value="0123456789" /> def telephone_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.stringify_keys.update("type" => "tel")) + text_field_tag(name, value, options.merge(type: :tel)) end alias phone_field_tag telephone_field_tag @@ -635,7 +643,7 @@ module ActionView # date_field_tag 'date', '01/01/2014', class: 'special_input', disabled: true # # => <input disabled="disabled" class="special_input" id="date" name="date" type="date" value="01/01/2014" /> def date_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.stringify_keys.update("type" => "date")) + text_field_tag(name, value, options.merge(type: :date)) end # Creates a text field of type "time". @@ -646,7 +654,7 @@ module ActionView # * <tt>:step</tt> - The acceptable value granularity. # * Otherwise accepts the same options as text_field_tag. def time_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.stringify_keys.update("type" => "time")) + text_field_tag(name, value, options.merge(type: :time)) end # Creates a text field of type "datetime". @@ -657,7 +665,7 @@ module ActionView # * <tt>:step</tt> - The acceptable value granularity. # * Otherwise accepts the same options as text_field_tag. def datetime_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.stringify_keys.update("type" => "datetime")) + text_field_tag(name, value, options.merge(type: :datetime)) end # Creates a text field of type "datetime-local". @@ -668,7 +676,7 @@ module ActionView # * <tt>:step</tt> - The acceptable value granularity. # * Otherwise accepts the same options as text_field_tag. def datetime_local_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.stringify_keys.update("type" => "datetime-local")) + text_field_tag(name, value, options.merge(type: 'datetime-local')) end # Creates a text field of type "month". @@ -679,7 +687,7 @@ module ActionView # * <tt>:step</tt> - The acceptable value granularity. # * Otherwise accepts the same options as text_field_tag. def month_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.stringify_keys.update("type" => "month")) + text_field_tag(name, value, options.merge(type: :month)) end # Creates a text field of type "week". @@ -690,7 +698,7 @@ module ActionView # * <tt>:step</tt> - The acceptable value granularity. # * Otherwise accepts the same options as text_field_tag. def week_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.stringify_keys.update("type" => "week")) + text_field_tag(name, value, options.merge(type: :week)) end # Creates a text field of type "url". @@ -711,7 +719,7 @@ module ActionView # url_field_tag 'url', 'http://rubyonrails.org', class: 'special_input', disabled: true # # => <input disabled="disabled" class="special_input" id="url" name="url" type="url" value="http://rubyonrails.org" /> def url_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.stringify_keys.update("type" => "url")) + text_field_tag(name, value, options.merge(type: :url)) end # Creates a text field of type "email". @@ -732,7 +740,7 @@ module ActionView # email_field_tag 'email', 'email@example.com', class: 'special_input', disabled: true # # => <input disabled="disabled" class="special_input" id="email" name="email" type="email" value="email@example.com" /> def email_field_tag(name, value = nil, options = {}) - text_field_tag(name, value, options.stringify_keys.update("type" => "email")) + text_field_tag(name, value, options.merge(type: :email)) end # Creates a number field. @@ -790,7 +798,7 @@ module ActionView # ==== Options # * Accepts the same options as number_field_tag. def range_field_tag(name, value = nil, options = {}) - number_field_tag(name, value, options.stringify_keys.update("type" => "range")) + number_field_tag(name, value, options.merge(type: :range)) end # Creates the hidden UTF8 enforcer tag. Override this method in a helper diff --git a/actionview/lib/action_view/helpers/number_helper.rb b/actionview/lib/action_view/helpers/number_helper.rb index 7220bded3c..f66dbfe7d3 100644 --- a/actionview/lib/action_view/helpers/number_helper.rb +++ b/actionview/lib/action_view/helpers/number_helper.rb @@ -306,12 +306,12 @@ module ActionView # string containing an i18n scope where to find this hash. It # might have the following keys: # * *integers*: <tt>:unit</tt>, <tt>:ten</tt>, - # *<tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>, - # *<tt>:billion</tt>, <tt>:trillion</tt>, - # *<tt>:quadrillion</tt> + # <tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>, + # <tt>:billion</tt>, <tt>:trillion</tt>, + # <tt>:quadrillion</tt> # * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>, - # *<tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>, - # *<tt>:pico</tt>, <tt>:femto</tt> + # <tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>, + # <tt>:pico</tt>, <tt>:femto</tt> # * <tt>:format</tt> - Sets the format of the output string # (defaults to "%n %u"). The field types are: # * %u - The quantifier (ex.: 'thousand') diff --git a/actionview/lib/action_view/helpers/sanitize_helper.rb b/actionview/lib/action_view/helpers/sanitize_helper.rb index 4f2db0a0c4..7cb55cc214 100644 --- a/actionview/lib/action_view/helpers/sanitize_helper.rb +++ b/actionview/lib/action_view/helpers/sanitize_helper.rb @@ -57,7 +57,7 @@ module ActionView # Add table tags to the default allowed tags # # class Application < Rails::Application - # config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td' + # config.action_view.sanitized_allowed_tags = ['table', 'tr', 'td'] # end # # Remove tags to the default allowed tags @@ -176,7 +176,7 @@ module ActionView # Replaces the allowed tags for the +sanitize+ helper. # # class Application < Rails::Application - # config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td' + # config.action_view.sanitized_allowed_tags = ['table', 'tr', 'td'] # end # diff --git a/actionview/lib/action_view/helpers/tag_helper.rb b/actionview/lib/action_view/helpers/tag_helper.rb index 385d57a7a5..b2038576a2 100644 --- a/actionview/lib/action_view/helpers/tag_helper.rb +++ b/actionview/lib/action_view/helpers/tag_helper.rb @@ -123,7 +123,7 @@ module ActionView # cdata_section("hello]]>world") # # => <![CDATA[hello]]]]><![CDATA[>world]]> def cdata_section(content) - splitted = content.to_s.gsub(']]>', ']]]]><![CDATA[>') + splitted = content.to_s.gsub(/\]\]\>/, ']]]]><![CDATA[>') "<![CDATA[#{splitted}]]>".html_safe end diff --git a/actionview/lib/action_view/helpers/tags/base.rb b/actionview/lib/action_view/helpers/tags/base.rb index 8607da301c..f8abb19698 100644 --- a/actionview/lib/action_view/helpers/tags/base.rb +++ b/actionview/lib/action_view/helpers/tags/base.rb @@ -25,7 +25,7 @@ module ActionView private def value(object) - object.send @method_name if object + object.public_send @method_name if object end def value_before_type_cast(object) diff --git a/actionview/lib/action_view/renderer/partial_renderer.rb b/actionview/lib/action_view/renderer/partial_renderer.rb index 0407632435..f627d5d40c 100644 --- a/actionview/lib/action_view/renderer/partial_renderer.rb +++ b/actionview/lib/action_view/renderer/partial_renderer.rb @@ -366,10 +366,12 @@ module ActionView partial = options[:partial] if String === partial + @has_object = options.key?(:object) @object = options[:object] @collection = collection_from_options @path = partial else + @has_object = true @object = partial @collection = collection_from_object || collection_from_options @@ -506,7 +508,7 @@ module ActionView def retrieve_template_keys keys = @locals.keys - keys << @variable if @object || @collection + keys << @variable if @has_object || @collection if @collection keys << @variable_counter keys << @variable_iteration diff --git a/actionview/lib/action_view/renderer/template_renderer.rb b/actionview/lib/action_view/renderer/template_renderer.rb index f3a48ecfa0..cd21d7ab47 100644 --- a/actionview/lib/action_view/renderer/template_renderer.rb +++ b/actionview/lib/action_view/renderer/template_renderer.rb @@ -18,7 +18,7 @@ module ActionView # Determine the template to be rendered using the given options. def determine_template(options) - keys = options.fetch(:locals, {}).keys + keys = options.has_key?(:locals) ? options[:locals].keys : [] if options.key?(:body) Template::Text.new(options[:body]) diff --git a/actionview/lib/action_view/rendering.rb b/actionview/lib/action_view/rendering.rb index 5cbdfdf6c0..abd3b77c67 100644 --- a/actionview/lib/action_view/rendering.rb +++ b/actionview/lib/action_view/rendering.rb @@ -35,13 +35,13 @@ module ActionView module ClassMethods def view_context_class @view_context_class ||= begin - include_path_helpers = supports_path? + supports_path = supports_path? routes = respond_to?(:_routes) && _routes helpers = respond_to?(:_helpers) && _helpers Class.new(ActionView::Base) do if routes - include routes.url_helpers(include_path_helpers) + include routes.url_helpers(supports_path) include routes.mounted_helpers end diff --git a/actionview/lib/action_view/routing_url_for.rb b/actionview/lib/action_view/routing_url_for.rb index 75febb8652..f281333a41 100644 --- a/actionview/lib/action_view/routing_url_for.rb +++ b/actionview/lib/action_view/routing_url_for.rb @@ -80,21 +80,38 @@ module ActionView when String options when nil - super({:only_path => true}) + super(only_path: _generate_paths_by_default) when Hash options = options.symbolize_keys - options[:only_path] = options[:host].nil? unless options.key?(:only_path) + unless options.key?(:only_path) + if options[:host].nil? + options[:only_path] = _generate_paths_by_default + else + options[:only_path] = false + end + end + super(options) when :back _back_url - when Symbol - ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.path.handle_string_call self, options when Array - polymorphic_path(options, options.extract_options!) - when Class - ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.path.handle_class_call self, options + if _generate_paths_by_default + polymorphic_path(options, options.extract_options!) + else + polymorphic_url(options, options.extract_options!) + end else - ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.path.handle_model_call self, options + method = _generate_paths_by_default ? :path : :url + builder = ActionDispatch::Routing::PolymorphicRoutes::HelperMethodBuilder.send(method) + + case options + when Symbol + builder.handle_string_call(self, options) + when Class + builder.handle_class_call(self, options) + else + builder.handle_model_call(self, options) + end end end diff --git a/actionview/lib/action_view/template.rb b/actionview/lib/action_view/template.rb index 379f31bdaf..6b61378a1f 100644 --- a/actionview/lib/action_view/template.rb +++ b/actionview/lib/action_view/template.rb @@ -313,11 +313,15 @@ module ActionView def locals_code #:nodoc: # Double assign to suppress the dreaded 'assigned but unused variable' warning - @locals.map { |key| "#{key} = #{key} = local_assigns[:#{key}];" }.join + @locals.each_with_object('') { |key, code| code << "#{key} = #{key} = local_assigns[:#{key}];" } end def method_name #:nodoc: - @method_name ||= "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}".tr('-', "_") + @method_name ||= begin + m = "_#{identifier_method_name}__#{@identifier.hash}_#{__id__}" + m.tr!('-', '_') + m + end end def identifier_method_name #:nodoc: diff --git a/actionview/lib/action_view/template/handlers.rb b/actionview/lib/action_view/template/handlers.rb index 33bfcb458c..ff2feb5149 100644 --- a/actionview/lib/action_view/template/handlers.rb +++ b/actionview/lib/action_view/template/handlers.rb @@ -22,7 +22,7 @@ module ActionView #:nodoc: # Register an object that knows how to handle template files with the given # extensions. This can be used to implement new template types. - # The handler must respond to `:call`, which will be passed the template + # The handler must respond to +:call+, which will be passed the template # and should return the rendered template as a String. def register_template_handler(*extensions, handler) raise(ArgumentError, "Extension is required") if extensions.empty? diff --git a/actionview/lib/action_view/template/handlers/erb.rb b/actionview/lib/action_view/template/handlers/erb.rb index 3c2224fbf5..85a100ed4c 100644 --- a/actionview/lib/action_view/template/handlers/erb.rb +++ b/actionview/lib/action_view/template/handlers/erb.rb @@ -35,7 +35,7 @@ module ActionView end end - BLOCK_EXPR = /\s+(do|\{)(\s*\|[^|]*\|)?\s*\Z/ + BLOCK_EXPR = /\s*((\s+|\))do|\{)(\s*\|[^|]*\|)?\s*\Z/ def add_expr_literal(src, code) flush_newline_if_pending(src) diff --git a/actionview/lib/action_view/template/handlers/raw.rb b/actionview/lib/action_view/template/handlers/raw.rb index 0c0d1fffcb..397c86014a 100644 --- a/actionview/lib/action_view/template/handlers/raw.rb +++ b/actionview/lib/action_view/template/handlers/raw.rb @@ -2,7 +2,7 @@ module ActionView module Template::Handlers class Raw def call(template) - escaped = template.source.gsub(':', '\:') + escaped = template.source.gsub(/:/, '\:') '%q:' + escaped + ':;' end diff --git a/actionview/lib/action_view/template/resolver.rb b/actionview/lib/action_view/template/resolver.rb index d77421d5f5..b65507f4a2 100644 --- a/actionview/lib/action_view/template/resolver.rb +++ b/actionview/lib/action_view/template/resolver.rb @@ -1,6 +1,7 @@ require "pathname" require "active_support/core_ext/class" require "active_support/core_ext/module/attribute_accessors" +require 'active_support/core_ext/string/filters' require "action_view/template" require "thread" require "thread_safe" @@ -251,9 +252,10 @@ module ActionView extension = pieces.pop unless extension - message = "The file #{path} did not specify a template handler. The default is currently ERB, " \ - "but will change to RAW in the future." - ActiveSupport::Deprecation.warn message + ActiveSupport::Deprecation.warn(<<-MSG.squish) + The file #{path} did not specify a template handler. The default is + currently ERB, but will change to RAW in the future. + MSG end handler = Template.handler_for_extension(extension) diff --git a/actionview/lib/action_view/test_case.rb b/actionview/lib/action_view/test_case.rb index fec980462d..812b011bd7 100644 --- a/actionview/lib/action_view/test_case.rb +++ b/actionview/lib/action_view/test_case.rb @@ -125,6 +125,7 @@ module ActionView @_rendered_views ||= RenderedViewsCollection.new end + # Need to experiment if this priority is the best one: rendered => output_buffer class RenderedViewsCollection def initialize @rendered_views ||= Hash.new { |hash, key| hash[key] = [] } @@ -158,7 +159,7 @@ module ActionView # Need to experiment if this priority is the best one: rendered => output_buffer def document_root_element - Nokogiri::HTML::DocumentFragment.parse(@rendered.blank? ? @output_buffer : @rendered) + Nokogiri::HTML::Document.parse(@rendered.blank? ? @output_buffer : @rendered).root end def say_no_to_protect_against_forgery! diff --git a/actionview/lib/action_view/view_paths.rb b/actionview/lib/action_view/view_paths.rb index 80a41f2418..2e203a7590 100644 --- a/actionview/lib/action_view/view_paths.rb +++ b/actionview/lib/action_view/view_paths.rb @@ -38,7 +38,11 @@ module ActionView def handle_deprecated_parent_prefixes # TODO: remove in 4.3/5.0. return unless respond_to?(:parent_prefixes) - ActiveSupport::Deprecation.warn "Overriding ActionController::Base::parent_prefixes is deprecated, override .local_prefixes instead." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + Overriding `ActionController::Base::parent_prefixes` is deprecated, + override `.local_prefixes` instead. + MSG + local_prefixes + parent_prefixes end end diff --git a/actionview/test/template/debug_helper_test.rb b/actionview/test/activerecord/debug_helper_test.rb index 5609694cd5..5609694cd5 100644 --- a/actionview/test/template/debug_helper_test.rb +++ b/actionview/test/activerecord/debug_helper_test.rb diff --git a/actionview/test/fixtures/test/_label_with_block.erb b/actionview/test/fixtures/test/_label_with_block.erb index 40117e594e..94089ea93d 100644 --- a/actionview/test/fixtures/test/_label_with_block.erb +++ b/actionview/test/fixtures/test/_label_with_block.erb @@ -1,4 +1,4 @@ -<%= label 'post', 'message' do %> +<%= label('post', 'message')do %> Message <%= text_field 'post', 'message' %> <% end %> diff --git a/actionview/test/template/date_helper_test.rb b/actionview/test/template/date_helper_test.rb index 0cdb130710..a6962b5200 100644 --- a/actionview/test/template/date_helper_test.rb +++ b/actionview/test/template/date_helper_test.rb @@ -1504,7 +1504,7 @@ class DateHelperTest < ActionView::TestCase expected << %(<option value="">Choose seconds</option>\n<option value="00">00</option>\n<option value="01">01</option>\n<option value="02">02</option>\n<option value="03">03</option>\n<option value="04">04</option>\n<option value="05">05</option>\n<option value="06">06</option>\n<option value="07">07</option>\n<option value="08">08</option>\n<option value="09">09</option>\n<option value="10">10</option>\n<option value="11">11</option>\n<option value="12">12</option>\n<option value="13">13</option>\n<option value="14">14</option>\n<option value="15">15</option>\n<option value="16">16</option>\n<option value="17">17</option>\n<option value="18" selected="selected">18</option>\n<option value="19">19</option>\n<option value="20">20</option>\n<option value="21">21</option>\n<option value="22">22</option>\n<option value="23">23</option>\n<option value="24">24</option>\n<option value="25">25</option>\n<option value="26">26</option>\n<option value="27">27</option>\n<option value="28">28</option>\n<option value="29">29</option>\n<option value="30">30</option>\n<option value="31">31</option>\n<option value="32">32</option>\n<option value="33">33</option>\n<option value="34">34</option>\n<option value="35">35</option>\n<option value="36">36</option>\n<option value="37">37</option>\n<option value="38">38</option>\n<option value="39">39</option>\n<option value="40">40</option>\n<option value="41">41</option>\n<option value="42">42</option>\n<option value="43">43</option>\n<option value="44">44</option>\n<option value="45">45</option>\n<option value="46">46</option>\n<option value="47">47</option>\n<option value="48">48</option>\n<option value="49">49</option>\n<option value="50">50</option>\n<option value="51">51</option>\n<option value="52">52</option>\n<option value="53">53</option>\n<option value="54">54</option>\n<option value="55">55</option>\n<option value="56">56</option>\n<option value="57">57</option>\n<option value="58">58</option>\n<option value="59">59</option>\n) expected << "</select>\n" - assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :prompt => true, :include_seconds => true, + assert_dom_equal expected, select_time(Time.mktime(2003, 8, 16, 8, 4, 18), :include_seconds => true, :prompt => {:hour => 'Choose hour', :minute => 'Choose minute', :second => 'Choose seconds'}) end diff --git a/actionview/test/template/form_helper_test.rb b/actionview/test/template/form_helper_test.rb index f2238d1443..a131752b2a 100644 --- a/actionview/test/template/form_helper_test.rb +++ b/actionview/test/template/form_helper_test.rb @@ -1785,6 +1785,20 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + 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 + end.new + + form_for(obj, as: "other_name", url: '/', html: { id: "edit-other-name" }) do |f| + assert_raise(NoMethodError) { f.hidden_field(:private_property) } + end + end + def test_form_for_with_method_as_part_of_html_options form_for(@post, url: '/', html: { id: 'create-post', method: :delete }) do |f| concat f.text_field(:title) @@ -1850,6 +1864,30 @@ class FormHelperTest < ActionView::TestCase assert_dom_equal expected, output_buffer end + def test_form_for_enforce_utf8_true + form_for(:post, enforce_utf8: true) do |f| + concat f.text_field(:title) + end + + expected = whole_form("/", nil, nil, enforce_utf8: true) do + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + end + + assert_dom_equal expected, output_buffer + end + + def test_form_for_enforce_utf8_false + form_for(:post, enforce_utf8: false) do |f| + concat f.text_field(:title) + end + + expected = whole_form("/", nil, nil, enforce_utf8: false) do + "<input name='post[title]' type='text' id='post_title' value='Hello World' />" + end + + assert_dom_equal expected, output_buffer + end + def test_form_for_with_remote_in_html form_for(@post, url: '/', html: { remote: true, id: 'create-post', method: :patch }) do |f| concat f.text_field(:title) @@ -3299,8 +3337,14 @@ class FormHelperTest < ActionView::TestCase protected - def hidden_fields(method = nil) - txt = %{<input name="utf8" type="hidden" value="✓" />} + def hidden_fields(options = {}) + method = options[:method] + + if options.fetch(:enforce_utf8, true) + txt = %{<input name="utf8" type="hidden" value="✓" />} + else + txt = '' + end if method && !%w(get post).include?(method.to_s) txt << %{<input name="_method" type="hidden" value="#{method}" />} @@ -3324,7 +3368,7 @@ class FormHelperTest < ActionView::TestCase method, remote, multipart = options.values_at(:method, :remote, :multipart) - form_text(action, id, html_class, remote, multipart, method) + hidden_fields(method) + contents + "</form>" + form_text(action, id, html_class, remote, multipart, method) + hidden_fields(options.slice :method, :enforce_utf8) + contents + "</form>" end def protect_against_forgery? diff --git a/actionview/test/template/form_tag_helper_test.rb b/actionview/test/template/form_tag_helper_test.rb index 771e3fefc3..84a581b107 100644 --- a/actionview/test/template/form_tag_helper_test.rb +++ b/actionview/test/template/form_tag_helper_test.rb @@ -170,6 +170,13 @@ class FormTagHelperTest < ActionView::TestCase assert_dom_equal expected, actual end + def test_multiple_field_tags_with_same_options + options = {class: 'important'} + assert_dom_equal %(<input name="title" type="file" id="title" class="important"/>), file_field_tag("title", options) + assert_dom_equal %(<input type="password" name="title" id="title" value="Hello!" class="important" />), password_field_tag("title", "Hello!", options) + assert_dom_equal %(<input type="text" name="title" id="title" value="Hello!" class="important" />), text_field_tag("title", "Hello!", options) + end + def test_radio_button_tag actual = radio_button_tag "people", "david" expected = %(<input id="people_david" name="people" type="radio" value="david" />) @@ -225,6 +232,18 @@ class FormTagHelperTest < ActionView::TestCase assert_dom_equal expected, actual end + def test_select_tag_with_include_blank_false + actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, include_blank: false + expected = %(<select id="places" name="places"><option>Home</option><option>Work</option><option>Pub</option></select>) + assert_dom_equal expected, actual + end + + def test_select_tag_with_include_blank_string + actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, include_blank: 'Choose' + expected = %(<select id="places" name="places"><option value="">Choose</option><option>Home</option><option>Work</option><option>Pub</option></select>) + assert_dom_equal expected, actual + end + def test_select_tag_with_prompt actual = select_tag "places", "<option>Home</option><option>Work</option><option>Pub</option>".html_safe, :prompt => "string" expected = %(<select id="places" name="places"><option value="">string</option><option>Home</option><option>Work</option><option>Pub</option></select>) diff --git a/activejob/README.md b/activejob/README.md index b5d27272b1..8c83d3669a 100644 --- a/activejob/README.md +++ b/activejob/README.md @@ -5,7 +5,7 @@ of queueing backends. These jobs can be everything from regularly scheduled clean-ups, to billing charges, to mailings. Anything that can be chopped up into small units of work and run in parallel, really. -It also serves as the backend for ActionMailer's #deliver_later functionality +It also serves as the backend for Action Mailer's #deliver_later functionality that makes it easy to turn any mailing into a job for running later. That's one of the most common jobs in a modern web application: Sending emails outside of the request-response cycle, so the user doesn't have to wait on it. @@ -26,7 +26,8 @@ Set the queue adapter for Active Job: ActiveJob::Base.queue_adapter = :inline # default queue adapter ``` Note: To learn how to use your preferred queueing backend see its adapter -documentation at ActiveJob::QueueAdapters. +documentation at +[ActiveJob::QueueAdapters](http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html). Declare a job like so: @@ -110,7 +111,7 @@ Source code can be downloaded as part of the Rails project on GitHub ## License -ActiveJob is released under the MIT license: +Active Job is released under the MIT license: * http://www.opensource.org/licenses/MIT @@ -128,5 +129,3 @@ Bug reports can be filed for the Ruby on Rails project here: Feature requests should be discussed on the rails-core mailing list here: * https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core - - diff --git a/activejob/Rakefile b/activejob/Rakefile index a66df8939e..7e66860b36 100644 --- a/activejob/Rakefile +++ b/activejob/Rakefile @@ -35,6 +35,7 @@ namespace :test do t.libs << 'test' t.test_files = FileList['test/cases/**/*_test.rb'] t.verbose = true + t.warning = true t.ruby_opts = ["--dev"] if defined?(JRUBY_VERSION) end @@ -53,6 +54,7 @@ namespace :test do t.libs << 'test' t.test_files = FileList['test/integration/**/*_test.rb'] t.verbose = true + t.warning = true t.ruby_opts = ["--dev"] if defined?(JRUBY_VERSION) end end diff --git a/activejob/lib/active_job/base.rb b/activejob/lib/active_job/base.rb index 8f4b37222a..fd49b3fda5 100644 --- a/activejob/lib/active_job/base.rb +++ b/activejob/lib/active_job/base.rb @@ -9,14 +9,14 @@ require 'active_job/logging' module ActiveJob #:nodoc: # = Active Job # - # Active job objects can be configured to work with different backend + # Active Job objects can be configured to work with different backend # queuing frameworks. To specify a queue adapter to use: # # ActiveJob::Base.queue_adapter = :inline # # A list of supported adapters can be found in QueueAdapters. # - # Active job objects can be defined by creating a class that inherits + # Active Job objects can be defined by creating a class that inherits # from the ActiveJob::Base class. The only necessary method to # implement is the "perform" method. # @@ -32,18 +32,22 @@ module ActiveJob #:nodoc: # end # # Records that are passed in are serialized/deserialized using Global - # Id. More information can be found in Arguments. + # ID. More information can be found in Arguments. # - # To queue a job to be processed asynchronously immediately: + # To enqueue a job to be performed as soon the queueing system is free: # # ProcessPhotoJob.perform_later(photo) # - # To queue a job to be processed at some point in the future: + # To enqueue a job to be processed at some point in the future: # # ProcessPhotoJob.set(wait_until: Date.tomorrow.noon).perform_later(photo) # # More information can be found in ActiveJob::Core::ClassMethods#set # + # A job can also be processed immediately without sending to the queue: + # + # ProcessPhotoJob.perform_now(photo) + # # == Exceptions # # * DeserializationError - Error class for deserialization errors. diff --git a/activejob/lib/active_job/callbacks.rb b/activejob/lib/active_job/callbacks.rb index 29e2a878b4..c4ceb484cc 100644 --- a/activejob/lib/active_job/callbacks.rb +++ b/activejob/lib/active_job/callbacks.rb @@ -22,6 +22,8 @@ module ActiveJob define_callbacks :enqueue end + # These methods will be included into any Active Job object, adding + # callbacks for +perform+ and +enqueue+ methods. module ClassMethods # Defines a callback that will get called right before the # job's perform method is executed. diff --git a/activejob/lib/active_job/core.rb b/activejob/lib/active_job/core.rb index f55db5a588..a0e55a0028 100644 --- a/activejob/lib/active_job/core.rb +++ b/activejob/lib/active_job/core.rb @@ -17,6 +17,8 @@ module ActiveJob attr_writer :queue_name end + # These methods will be included into any Active Job object, adding + # helpers for de/serialization and creation of job instances. module ClassMethods # Creates a new job instance from a hash created with +serialize+ def deserialize(job_data) @@ -48,8 +50,8 @@ module ActiveJob end end - # Creates a new job instance. Takes as arguments the arguments that - # will be passed to the perform method. + # Creates a new job instance. Takes the arguments that will be + # passed to the perform method. def initialize(*arguments) @arguments = arguments @job_id = SecureRandom.uuid @@ -84,6 +86,3 @@ module ActiveJob end end end - - - diff --git a/activejob/lib/active_job/enqueuing.rb b/activejob/lib/active_job/enqueuing.rb index 74bcc1fa5d..430c17e1bf 100644 --- a/activejob/lib/active_job/enqueuing.rb +++ b/activejob/lib/active_job/enqueuing.rb @@ -4,13 +4,14 @@ module ActiveJob module Enqueuing extend ActiveSupport::Concern + # Includes the +perform_later+ method for job initialization. module ClassMethods # Push a job onto the queue. The arguments must be legal JSON types # (string, int, float, nil, true, false, hash or array) or # GlobalID::Identification instances. Arbitrary Ruby objects # are not supported. # - # Returns an instance of the job class queued with args available in + # Returns an instance of the job class queued with arguments available in # Job#arguments. def perform_later(*args) job_or_instantiate(*args).enqueue @@ -22,7 +23,7 @@ module ActiveJob end end - # Reschedule the job to be re-executed. This is useful in combination + # Reschedules the job to be re-executed. This is useful in combination # with the +rescue_from+ option. When you rescue an exception from your job # you can ask Active Job to retry performing your job. # @@ -37,6 +38,7 @@ module ActiveJob # rescue_from(ErrorLoadingSite) do # retry_job queue: :low_priority # end + # # def perform(*args) # # raise ErrorLoadingSite if cannot scrape # end diff --git a/activejob/lib/active_job/execution.rb b/activejob/lib/active_job/execution.rb index 7ff857206d..79d232da4a 100644 --- a/activejob/lib/active_job/execution.rb +++ b/activejob/lib/active_job/execution.rb @@ -6,6 +6,7 @@ module ActiveJob extend ActiveSupport::Concern include ActiveSupport::Rescuable + # Includes methods for executing and performing jobs instantly. module ClassMethods # Performs the job immediately. # diff --git a/activejob/lib/active_job/gem_version.rb b/activejob/lib/active_job/gem_version.rb index f80e6563b8..ac364f77d1 100644 --- a/activejob/lib/active_job/gem_version.rb +++ b/activejob/lib/active_job/gem_version.rb @@ -8,7 +8,7 @@ module ActiveJob MAJOR = 4 MINOR = 2 TINY = 0 - PRE = "beta2" + PRE = "beta4" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/activejob/lib/active_job/logging.rb b/activejob/lib/active_job/logging.rb index 6e703faaa7..21d2fda3ff 100644 --- a/activejob/lib/active_job/logging.rb +++ b/activejob/lib/active_job/logging.rb @@ -75,7 +75,7 @@ module ActiveJob def perform(event) info do job = event.payload[:job] - "Performed #{job.class.name} from #{queue_name(event)} in #{event.duration.round(2).to_s}ms" + "Performed #{job.class.name} from #{queue_name(event)} in #{event.duration.round(2)}ms" end end diff --git a/activejob/lib/active_job/queue_adapter.rb b/activejob/lib/active_job/queue_adapter.rb index 4bd28522ab..85d7c44bb8 100644 --- a/activejob/lib/active_job/queue_adapter.rb +++ b/activejob/lib/active_job/queue_adapter.rb @@ -2,9 +2,12 @@ require 'active_job/queue_adapters/inline_adapter' require 'active_support/core_ext/string/inflections' module ActiveJob + # The <tt>ActionJob::QueueAdapter</tt> module is used to load the + # correct adapter. The default queue adapter is the :inline queue. module QueueAdapter #:nodoc: extend ActiveSupport::Concern + # Includes the setter method for changing the active queue adapter. module ClassMethods mattr_reader(:queue_adapter) { ActiveJob::QueueAdapters::InlineAdapter } diff --git a/activejob/lib/active_job/queue_adapters.rb b/activejob/lib/active_job/queue_adapters.rb index efbcd3cb3a..4b91c93dbe 100644 --- a/activejob/lib/active_job/queue_adapters.rb +++ b/activejob/lib/active_job/queue_adapters.rb @@ -13,12 +13,13 @@ module ActiveJob # * {Sneakers}[https://github.com/jondot/sneakers] # * {Sucker Punch}[https://github.com/brandonhilkert/sucker_punch] # - # #### Backends Features + # === Backends Features # # | | Async | Queues | Delayed | Priorities | Timeout | Retries | # |-------------------|-------|--------|-----------|------------|---------|---------| # | Backburner | Yes | Yes | Yes | Yes | Job | Global | # | Delayed Job | Yes | Yes | Yes | Job | Global | Global | + # | Qu | Yes | Yes | No | No | No | Global | # | Que | Yes | Yes | Yes | Job | No | Job | # | queue_classic | Yes | Yes | No* | No | No | No | # | Resque | Yes | Yes | Yes (Gem) | Queue | Global | Yes | diff --git a/activejob/lib/active_job/queue_adapters/delayed_job_adapter.rb b/activejob/lib/active_job/queue_adapters/delayed_job_adapter.rb index 4d27c4fff8..69d9e70de3 100644 --- a/activejob/lib/active_job/queue_adapters/delayed_job_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/delayed_job_adapter.rb @@ -6,10 +6,10 @@ module ActiveJob # # Delayed::Job (or DJ) encapsulates the common pattern of asynchronously # executing longer tasks in the background. Although DJ can have many - # storage backends one of the most used is based on Active Record. + # storage backends, one of the most used is based on Active Record. # Read more about Delayed Job {here}[https://github.com/collectiveidea/delayed_job]. # - # To use Delayed Job set the queue_adapter config to +:delayed_job+. + # To use Delayed Job, set the queue_adapter config to +:delayed_job+. # # Rails.application.config.active_job.queue_adapter = :delayed_job class DelayedJobAdapter diff --git a/activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb b/activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb index 1a46f20420..34c11a68b2 100644 --- a/activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb +++ b/activejob/lib/active_job/queue_adapters/queue_classic_adapter.rb @@ -26,7 +26,7 @@ module ActiveJob queue = build_queue(job.queue_name) unless queue.respond_to?(:enqueue_at) raise NotImplementedError, 'To be able to schedule jobs with queue_classic ' \ - 'the QC::Queue needs to respond to `enqueue_at(timestamp, method, *args)`. ' + 'the QC::Queue needs to respond to `enqueue_at(timestamp, method, *args)`. ' \ 'You can implement this yourself or you can use the queue_classic-later gem.' end queue.enqueue_at(timestamp, "#{JobWrapper.name}.perform", job.serialize) diff --git a/activejob/lib/active_job/queue_name.rb b/activejob/lib/active_job/queue_name.rb index d6ac01a921..9ae0345120 100644 --- a/activejob/lib/active_job/queue_name.rb +++ b/activejob/lib/active_job/queue_name.rb @@ -2,6 +2,7 @@ module ActiveJob module QueueName extend ActiveSupport::Concern + # Includes the ability to override the default queue name and prefix. module ClassMethods mattr_accessor(:queue_name_prefix) mattr_accessor(:default_queue_name) { "default" } @@ -24,15 +25,18 @@ module ActiveJob end def queue_name_from_part(part_name) #:nodoc: - queue_name = part_name.to_s.presence || default_queue_name + queue_name = part_name || default_queue_name name_parts = [queue_name_prefix.presence, queue_name] - name_parts.compact.join('_') + name_parts.compact.join(queue_name_delimiter) end end included do class_attribute :queue_name, instance_accessor: false + class_attribute :queue_name_delimiter, instance_accessor: false + self.queue_name = default_queue_name + self.queue_name_delimiter = '_' # set default delimiter to '_' end # Returns the name of the queue the job will be run on diff --git a/activejob/lib/active_job/test_helper.rb b/activejob/lib/active_job/test_helper.rb index af62fae9b9..1720b140e5 100644 --- a/activejob/lib/active_job/test_helper.rb +++ b/activejob/lib/active_job/test_helper.rb @@ -53,7 +53,7 @@ module ActiveJob end end - # Assert that no job have been enqueued. + # Asserts that no jobs have been enqueued. # # def test_jobs # assert_no_enqueued_jobs @@ -71,19 +71,27 @@ module ActiveJob # # Note: This assertion is simply a shortcut for: # - # assert_enqueued_jobs 0 + # assert_enqueued_jobs 0, &block def assert_no_enqueued_jobs(&block) assert_enqueued_jobs 0, &block end # Asserts that the number of performed jobs matches the given number. + # If no block is passed, <tt>perform_enqueued_jobs</tt> + # must be called around the job call. # # def test_jobs # assert_performed_jobs 0 - # HelloJob.perform_later('xavier') + # + # perform_enqueued_jobs do + # HelloJob.perform_later('xavier') + # end # assert_performed_jobs 1 - # HelloJob.perform_later('yves') - # assert_performed_jobs 2 + # + # perform_enqueued_jobs do + # HelloJob.perform_later('yves') + # assert_performed_jobs 2 + # end # end # # If a block is passed, that block should cause the specified number of @@ -102,7 +110,7 @@ module ActiveJob def assert_performed_jobs(number) if block_given? original_count = performed_jobs.size - yield + perform_enqueued_jobs { yield } new_count = performed_jobs.size assert_equal original_count + number, new_count, "#{number} jobs expected, but #{new_count - original_count} were performed" @@ -116,8 +124,11 @@ module ActiveJob # # def test_jobs # assert_no_performed_jobs - # HelloJob.perform_later('matthew') - # assert_performed_jobs 1 + # + # perform_enqueued_jobs do + # HelloJob.perform_later('matthew') + # assert_performed_jobs 1 + # end # end # # If a block is passed, that block should not cause any job to be performed. @@ -130,14 +141,14 @@ module ActiveJob # # Note: This assertion is simply a shortcut for: # - # assert_performed_jobs 0 + # assert_performed_jobs 0, &block def assert_no_performed_jobs(&block) assert_performed_jobs 0, &block end # Asserts that the job passed in the block has been enqueued with the given arguments. # - # def assert_enqueued_job + # def test_assert_enqueued_with # assert_enqueued_with(job: MyJob, args: [1,2,3], queue: 'low') do # MyJob.perform_later(1,2,3) # end @@ -166,7 +177,7 @@ module ActiveJob original_performed_jobs = performed_jobs.dup clear_performed_jobs args.assert_valid_keys(:job, :args, :at, :queue) - yield + perform_enqueued_jobs { yield } matching_job = performed_jobs.any? do |job| args.all? { |key, value| value == job[key] } end @@ -175,6 +186,17 @@ module ActiveJob queue_adapter.performed_jobs = original_performed_jobs + performed_jobs end + def perform_enqueued_jobs + @old_perform_enqueued_jobs = queue_adapter.perform_enqueued_jobs + @old_perform_enqueued_at_jobs = queue_adapter.perform_enqueued_at_jobs + queue_adapter.perform_enqueued_jobs = true + queue_adapter.perform_enqueued_at_jobs = true + yield + ensure + queue_adapter.perform_enqueued_jobs = @old_perform_enqueued_jobs + queue_adapter.perform_enqueued_at_jobs = @old_perform_enqueued_at_jobs + end + def queue_adapter ActiveJob::Base.queue_adapter end diff --git a/activejob/test/cases/logging_test.rb b/activejob/test/cases/logging_test.rb index 9c56ee08b6..3d4e561117 100644 --- a/activejob/test/cases/logging_test.rb +++ b/activejob/test/cases/logging_test.rb @@ -33,7 +33,7 @@ class AdapterTest < ActiveSupport::TestCase def teardown super ActiveJob::Logging::LogSubscriber.log_subscribers.pop - ActiveJob::Base.logger = @old_logger + set_logger @old_logger end def set_logger(logger) diff --git a/activejob/test/cases/queue_naming_test.rb b/activejob/test/cases/queue_naming_test.rb index 4052477543..898016a704 100644 --- a/activejob/test/cases/queue_naming_test.rb +++ b/activejob/test/cases/queue_naming_test.rb @@ -9,8 +9,9 @@ class QueueNamingTest < ActiveSupport::TestCase end test 'uses given queue name job' do + original_queue_name = HelloJob.queue_name + begin - original_queue_name = HelloJob.queue_name HelloJob.queue_as :greetings assert_equal "greetings", HelloJob.new.queue_name ensure @@ -18,9 +19,32 @@ class QueueNamingTest < ActiveSupport::TestCase end end + test 'allows a blank queue name' do + original_queue_name = HelloJob.queue_name + + begin + HelloJob.queue_as "" + assert_equal "", HelloJob.new.queue_name + ensure + HelloJob.queue_name = original_queue_name + end + end + + test 'does not use a nil queue name' do + original_queue_name = HelloJob.queue_name + + begin + HelloJob.queue_as nil + assert_equal "default", HelloJob.new.queue_name + ensure + HelloJob.queue_name = original_queue_name + end + end + test 'evals block given to queue_as to determine queue' do + original_queue_name = HelloJob.queue_name + begin - original_queue_name = HelloJob.queue_name HelloJob.queue_as { :another } assert_equal "another", HelloJob.new.queue_name ensure @@ -29,8 +53,9 @@ class QueueNamingTest < ActiveSupport::TestCase end test 'can use arguments to determine queue_name in queue_as block' do + original_queue_name = HelloJob.queue_name + begin - original_queue_name = HelloJob.queue_name HelloJob.queue_as { self.arguments.first=='1' ? :one : :two } assert_equal "one", HelloJob.new('1').queue_name assert_equal "two", HelloJob.new('3').queue_name @@ -39,11 +64,11 @@ class QueueNamingTest < ActiveSupport::TestCase end end - test 'queu_name_prefix prepended to the queue name' do - begin - original_queue_name_prefix = ActiveJob::Base.queue_name_prefix - original_queue_name = HelloJob.queue_name + test 'queue_name_prefix prepended to the queue name with default delimiter' do + original_queue_name_prefix = ActiveJob::Base.queue_name_prefix + original_queue_name = HelloJob.queue_name + begin ActiveJob::Base.queue_name_prefix = 'aj' HelloJob.queue_as :low assert_equal 'aj_low', HelloJob.queue_name @@ -53,9 +78,25 @@ class QueueNamingTest < ActiveSupport::TestCase end end + test 'queue_name_prefix prepended to the queue name with custom delimiter' do + original_queue_name_prefix = ActiveJob::Base.queue_name_prefix + original_queue_name_delimiter = ActiveJob::Base.queue_name_delimiter + original_queue_name = HelloJob.queue_name + + begin + ActiveJob::Base.queue_name_delimiter = '.' + ActiveJob::Base.queue_name_prefix = 'aj' + HelloJob.queue_as :low + assert_equal 'aj.low', HelloJob.queue_name + ensure + ActiveJob::Base.queue_name_prefix = original_queue_name_prefix + ActiveJob::Base.queue_name_delimiter = original_queue_name_delimiter + HelloJob.queue_name = original_queue_name + end + end + test 'uses queue passed to #set' do job = HelloJob.set(queue: :some_queue).perform_later assert_equal "some_queue", job.queue_name end - end diff --git a/activejob/test/cases/rescue_test.rb b/activejob/test/cases/rescue_test.rb index 1b6c2e9fac..58c9ca8992 100644 --- a/activejob/test/cases/rescue_test.rb +++ b/activejob/test/cases/rescue_test.rb @@ -2,8 +2,6 @@ require 'helper' require 'jobs/rescue_job' require 'models/person' -require 'active_support/core_ext/object/inclusion' - class RescueTest < ActiveSupport::TestCase setup do JobBuffer.clear diff --git a/activejob/test/cases/test_helper_test.rb b/activejob/test/cases/test_helper_test.rb index 71c505a65f..784ede3674 100644 --- a/activejob/test/cases/test_helper_test.rb +++ b/activejob/test/cases/test_helper_test.rb @@ -6,8 +6,6 @@ require 'jobs/logging_job' require 'jobs/nested_job' class EnqueuedJobsTest < ActiveJob::TestCase - setup { queue_adapter.perform_enqueued_at_jobs = true } - def test_assert_enqueued_jobs assert_nothing_raised do assert_enqueued_jobs 1 do @@ -44,11 +42,16 @@ class EnqueuedJobsTest < ActiveJob::TestCase end end + def test_assert_no_enqueued_jobs_with_no_block + assert_nothing_raised do + assert_no_enqueued_jobs + end + end + def test_assert_no_enqueued_jobs assert_nothing_raised do assert_no_enqueued_jobs do - # Scheduled jobs are being performed in this context - HelloJob.set(wait_until: Date.tomorrow.noon).perform_later('godfrey') + HelloJob.perform_now end end end @@ -86,7 +89,7 @@ class EnqueuedJobsTest < ActiveJob::TestCase def test_assert_enqueued_job assert_enqueued_with(job: LoggingJob, queue: 'default') do - NestedJob.set(wait_until: Date.tomorrow.noon).perform_later + LoggingJob.set(wait_until: Date.tomorrow.noon).perform_later end end @@ -116,8 +119,6 @@ class EnqueuedJobsTest < ActiveJob::TestCase end class PerformedJobsTest < ActiveJob::TestCase - setup { queue_adapter.perform_enqueued_jobs = true } - def test_assert_performed_jobs assert_nothing_raised do assert_performed_jobs 1 do @@ -143,22 +144,31 @@ class PerformedJobsTest < ActiveJob::TestCase def test_assert_performed_jobs_with_no_block assert_nothing_raised do - HelloJob.perform_later('rafael') + perform_enqueued_jobs do + HelloJob.perform_later('rafael') + end assert_performed_jobs 1 end assert_nothing_raised do - HelloJob.perform_later('aaron') - HelloJob.perform_later('matthew') - assert_performed_jobs 3 + perform_enqueued_jobs do + HelloJob.perform_later('aaron') + HelloJob.perform_later('matthew') + assert_performed_jobs 3 + end + end + end + + def test_assert_no_performed_jobs_with_no_block + assert_nothing_raised do + assert_no_performed_jobs end end def test_assert_no_performed_jobs assert_nothing_raised do assert_no_performed_jobs do - # Scheduled jobs are being enqueued in this context - HelloJob.set(wait_until: Date.tomorrow.noon).perform_later('godfrey') + # empty block won't perform jobs end end end diff --git a/activejob/test/helper.rb b/activejob/test/helper.rb index ce22833b11..ec0c8a8ede 100644 --- a/activejob/test/helper.rb +++ b/activejob/test/helper.rb @@ -26,5 +26,4 @@ end require 'active_support/testing/autorun' -ActiveJob::Base.logger.level = Logger::DEBUG ActiveSupport::TestCase.test_order = :random diff --git a/activejob/test/integration/queuing_test.rb b/activejob/test/integration/queuing_test.rb index 779dedb53f..38874b51a8 100644 --- a/activejob/test/integration/queuing_test.rb +++ b/activejob/test/integration/queuing_test.rb @@ -3,16 +3,17 @@ require 'jobs/logging_job' require 'active_support/core_ext/numeric/time' class QueuingTest < ActiveSupport::TestCase - test 'should run jobs enqueued on a listenting queue' do + test 'should run jobs enqueued on a listening queue' do TestJob.perform_later @id wait_for_jobs_to_finish_for(5.seconds) assert job_executed end - test 'should not run jobs queued on a non-listenting queue' do + test 'should not run jobs queued on a non-listening queue' do + skip if adapter_is?(:inline) || adapter_is?(:sucker_punch) + old_queue = TestJob.queue_name + begin - skip if adapter_is?(:inline) || adapter_is?(:sucker_punch) - old_queue = TestJob.queue_name TestJob.queue_as :some_other_queue TestJob.perform_later @id wait_for_jobs_to_finish_for(2.seconds) diff --git a/activejob/test/jobs/callback_job.rb b/activejob/test/jobs/callback_job.rb index 056dd073e8..891ed9464e 100644 --- a/activejob/test/jobs/callback_job.rb +++ b/activejob/test/jobs/callback_job.rb @@ -1,12 +1,21 @@ class CallbackJob < ActiveJob::Base before_perform ->(job) { job.history << "CallbackJob ran before_perform" } - after_perform ->(job) { job.history << "CallbackJob ran after_perform" } + after_perform ->(job) { job.history << "CallbackJob ran after_perform" } before_enqueue ->(job) { job.history << "CallbackJob ran before_enqueue" } - after_enqueue ->(job) { job.history << "CallbackJob ran after_enqueue" } + after_enqueue ->(job) { job.history << "CallbackJob ran after_enqueue" } - around_perform :around_perform - around_enqueue :around_enqueue + around_perform do |job, block| + job.history << "CallbackJob ran around_perform_start" + block.call + job.history << "CallbackJob ran around_perform_stop" + end + + around_enqueue do |job, block| + job.history << "CallbackJob ran around_enqueue_start" + block.call + job.history << "CallbackJob ran around_enqueue_stop" + end def perform(person = "david") @@ -17,16 +26,4 @@ class CallbackJob < ActiveJob::Base @history ||= [] end - # FIXME: Not sure why these can't be declared inline like before/after - def around_perform - history << "CallbackJob ran around_perform_start" - yield - history << "CallbackJob ran around_perform_stop" - end - - def around_enqueue - history << "CallbackJob ran around_enqueue_start" - yield - history << "CallbackJob ran around_enqueue_stop" - end end diff --git a/activejob/test/support/integration/adapters/backburner.rb b/activejob/test/support/integration/adapters/backburner.rb index 0cda36a273..2e82562948 100644 --- a/activejob/test/support/integration/adapters/backburner.rb +++ b/activejob/test/support/integration/adapters/backburner.rb @@ -29,7 +29,7 @@ module BackburnerJobsManager def can_run? begin Backburner::Worker.connection.send :connect! - rescue => e + rescue return false end true diff --git a/activejob/test/support/integration/adapters/qu.rb b/activejob/test/support/integration/adapters/qu.rb index e913f04a24..3a5b66a057 100644 --- a/activejob/test/support/integration/adapters/qu.rb +++ b/activejob/test/support/integration/adapters/qu.rb @@ -30,7 +30,7 @@ module QuJobsManager def can_run? begin Qu.backend.connection.client.connect - rescue => e + rescue return false end true diff --git a/activejob/test/support/integration/adapters/resque.rb b/activejob/test/support/integration/adapters/resque.rb index 9de3e7c879..82acb17b2b 100644 --- a/activejob/test/support/integration/adapters/resque.rb +++ b/activejob/test/support/integration/adapters/resque.rb @@ -41,7 +41,7 @@ module ResqueJobsManager def can_run? begin Resque.redis.client.connect - rescue => e + rescue return false end true diff --git a/activejob/test/support/integration/adapters/sidekiq.rb b/activejob/test/support/integration/adapters/sidekiq.rb index 0a0a549c9e..3cc9a34993 100644 --- a/activejob/test/support/integration/adapters/sidekiq.rb +++ b/activejob/test/support/integration/adapters/sidekiq.rb @@ -49,7 +49,7 @@ module SidekiqJobsManager def can_run? begin Sidekiq.redis { |conn| conn.connect } - rescue => e + rescue return false end true diff --git a/activejob/test/support/integration/adapters/sneakers.rb b/activejob/test/support/integration/adapters/sneakers.rb index f21bb38a32..875803a2d8 100644 --- a/activejob/test/support/integration/adapters/sneakers.rb +++ b/activejob/test/support/integration/adapters/sneakers.rb @@ -68,7 +68,7 @@ module SneakersJobsManager def can_run? begin bunny_publisher - rescue => e + rescue return false end true diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb index ca04f48c1c..4e389c8692 100644 --- a/activemodel/lib/active_model/dirty.rb +++ b/activemodel/lib/active_model/dirty.rb @@ -1,5 +1,6 @@ require 'active_support/hash_with_indifferent_access' require 'active_support/core_ext/object/duplicable' +require 'active_support/core_ext/string/filters' module ActiveModel # == Active \Model \Dirty @@ -200,7 +201,11 @@ module ActiveModel end def reset_changes - ActiveSupport::Deprecation.warn "#reset_changes is deprecated and will be removed on Rails 5. Please use #clear_changes_information instead." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + `#reset_changes` is deprecated and will be removed on Rails 5. + Please use `#clear_changes_information` instead. + MSG + clear_changes_information end @@ -224,7 +229,10 @@ module ActiveModel # Handle <tt>reset_*!</tt> for +method_missing+. def reset_attribute!(attr) - ActiveSupport::Deprecation.warn "#reset_#{attr}! is deprecated and will be removed on Rails 5. Please use #restore_#{attr}! instead." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + `#reset_#{attr}!` is deprecated and will be removed on Rails 5. + Please use `#restore_#{attr}!` instead. + MSG restore_attribute!(attr) end @@ -247,7 +255,7 @@ module ActiveModel end # Remove changes information for the provided attributes. - def clear_attribute_changes(attributes) + def clear_attribute_changes(attributes) # :doc: attributes_changed_by_setter.except!(*attributes) end end diff --git a/activemodel/lib/active_model/errors.rb b/activemodel/lib/active_model/errors.rb index 1b46727351..9105ef5dd6 100644 --- a/activemodel/lib/active_model/errors.rb +++ b/activemodel/lib/active_model/errors.rb @@ -98,6 +98,8 @@ module ActiveModel end # aliases include? alias :has_key? :include? + # aliases include? + alias :key? :include? # Get messages for +key+. # diff --git a/activemodel/lib/active_model/gem_version.rb b/activemodel/lib/active_model/gem_version.rb index e37edcf581..932fe3e5a9 100644 --- a/activemodel/lib/active_model/gem_version.rb +++ b/activemodel/lib/active_model/gem_version.rb @@ -8,7 +8,7 @@ module ActiveModel MAJOR = 4 MINOR = 2 TINY = 0 - PRE = "beta2" + PRE = "beta4" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/activemodel/lib/active_model/validations.rb b/activemodel/lib/active_model/validations.rb index 1116f6b8ee..c1e344b215 100644 --- a/activemodel/lib/active_model/validations.rb +++ b/activemodel/lib/active_model/validations.rb @@ -392,7 +392,7 @@ module ActiveModel protected def run_validations! #:nodoc: - run_validate_callbacks + _run_validate_callbacks errors.empty? end end diff --git a/activemodel/lib/active_model/validations/callbacks.rb b/activemodel/lib/active_model/validations/callbacks.rb index 1a5192b0ff..25ccabd66b 100644 --- a/activemodel/lib/active_model/validations/callbacks.rb +++ b/activemodel/lib/active_model/validations/callbacks.rb @@ -110,7 +110,7 @@ module ActiveModel # Overwrite run validations to include callbacks. def run_validations! #:nodoc: - run_validation_callbacks { super } + _run_validation_callbacks { super } end end end diff --git a/activemodel/lib/active_model/validations/format.rb b/activemodel/lib/active_model/validations/format.rb index ff3e95da34..02478dd5b6 100644 --- a/activemodel/lib/active_model/validations/format.rb +++ b/activemodel/lib/active_model/validations/format.rb @@ -54,7 +54,7 @@ module ActiveModel module HelperMethods # Validates whether the value of the specified attribute is of the correct - # form, going by the regular expression provided.You can require that the + # form, going by the regular expression provided. You can require that the # attribute matches the regular expression: # # class Person < ActiveRecord::Base diff --git a/activemodel/test/cases/errors_test.rb b/activemodel/test/cases/errors_test.rb index 42d0365521..efedd9055f 100644 --- a/activemodel/test/cases/errors_test.rb +++ b/activemodel/test/cases/errors_test.rb @@ -59,6 +59,17 @@ class ErrorsTest < ActiveModel::TestCase assert_equal false, errors.has_key?(:name), 'errors should not have key :name' end + def test_key? + errors = ActiveModel::Errors.new(self) + errors[:foo] = 'omg' + assert_equal true, errors.key?(:foo), 'errors should have key :foo' + end + + def test_no_key + errors = ActiveModel::Errors.new(self) + assert_equal false, errors.key?(:name), 'errors should not have key :name' + end + test "clear errors" do person = Person.new person.validate! diff --git a/activemodel/test/cases/validations/validates_test.rb b/activemodel/test/cases/validations/validates_test.rb index 699a872e42..8d4b74ee49 100644 --- a/activemodel/test/cases/validations/validates_test.rb +++ b/activemodel/test/cases/validations/validates_test.rb @@ -3,7 +3,6 @@ require 'cases/helper' require 'models/person' require 'models/topic' require 'models/person_with_validator' -require 'validators/email_validator' require 'validators/namespace/email_validator' class ValidatesTest < ActiveModel::TestCase diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 6bdb53ac5a..a6ed8cdb06 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,106 @@ +* Bring back `db:test:prepare` to synchronize the test database schema. + + Manual synchronization using `bin/rake db:test:prepare` is required + when a migration is rolled-back, edited and reapplied. + + `ActiveRecord::Base.maintain_test_schema` now uses `db:test:prepare` + to synchronize the schema. Plugins can use this task as a hook to + provide custom behavior after the schema has been loaded. + + NOTE: `test:prepare` runs before the schema is synchronized. + + Fixes #17171, #15787. + + *Yves Senn* + +* Change `reflections` public api to return the keys as String objects. + + Fixes #16928. + + *arthurnn* + +* Renaming a table in pg also renames the primary key index. + + Fixes #12856 + + *Sean Griffin* + +* Make it possible to access fixtures excluded by a `default_scope`. + + *Yves Senn* + +* Fix preloading of associations with a scope containing joins along with + conditions on the joined association. + + *Siddharth Sharma* + +* Add `Table#name` to match `TableDefinition#name`. + + *Cody Cutrer* + +* Cache `CollectionAssociation#reader` proxies separately before and after + the owner has been saved so that the proxy is not cached without the + owner's id. + + *Ben Woosley* + +* `ActiveRecord::ReadOnlyRecord` now has a descriptive message. + + *Franky W.* + +* Fix preloading of associations which unscope a default scope. + + Fixes #11036. + + *Byron Bischoff* + +* Added SchemaDumper support for tables with jsonb columns. + + *Ted O'Meara* + +* Deprecate `sanitize_sql_hash_for_conditions` without replacement. Using a + `Relation` for performing queries and updates is the prefered API. + + *Sean Griffin* + +* Queries now properly type cast values that are part of a join statement, + even when using type decorators such as `serialize`. + + *Melanie Gilman & Sean Griffin* + +* MySQL enum type lookups, with values matching another type, no longer result + in an endless loop. + + Fixes #17402. + + *Yves Senn* + +* Raise `ArgumentError` when the body of a scope is not callable. + + *Mauro George* + +* Use type column first in multi-column indexes created with `add-reference`. + + *Derek Prior* + +* Fix `Relation.rewhere` to work with Range values. + + *Dan Olson* + +* `AR::UnknownAttributeError` now includes the class name of a record. + + User.new(name: "Yuki Nishijima", project_attributes: {name: "kaminari"}) + # => ActiveRecord::UnknownAttributeError: unknown attribute 'name' for User. + + *Yuki Nishijima* + +* Fix a regression causing `after_create` callbacks to run before associated + records are autosaved. + + Fixes #17209. + + *Agis Anastasopoulos* + * Honor overridden `rack.test` in Rack environment for the connection management middleware. @@ -88,7 +191,7 @@ *Yves Senn* -* Fixed a regression where whitespaces were stripped from DISTINCT queries in +* Fix a regression where whitespaces were stripped from DISTINCT queries in PostgreSQL. *Agis Anastasopoulos* @@ -102,7 +205,7 @@ *Agis Anastasopoulos* -* Fixed `Relation#exists?` to work with polymorphic associations. +* Fix `Relation#exists?` to work with polymorphic associations. Fixes #15821. @@ -124,7 +227,7 @@ *arthurnn* -* Fixed an issue where custom accessor methods (such as those generated by +* Fix an issue where custom accessor methods (such as those generated by `enum`) with the same name as a global method are incorrectly overridden when subclassing. @@ -188,7 +291,7 @@ *Yves Senn* -* Fixed automatic maintaining test schema to properly handle sql structure +* Fix automatic maintaining test schema to properly handle sql structure schema format. Fixes #15394. @@ -351,8 +454,8 @@ *Sean Griffin* -* Fixed error in `reset_counters` when associations have `select` scope. - (Call to `count` generates invalid SQL.) +* Fix an error in `reset_counters` when associations have `select` scope. + (Call to `count` generated invalid SQL.) *Cade Truitt* @@ -577,7 +680,7 @@ *Yves Senn* -* Fixed `columns_for_distinct` of postgresql adapter to work correctly +* Fix `columns_for_distinct` of PostgreSQL adapter to work correctly with orders without sort direction modifiers. *Nikolay Kondratyev* @@ -613,7 +716,7 @@ *arthurnn* -* Fixed serialization for records with an attribute named `format`. +* Fix serialization for records with an attribute named `format`. Fixes #15188. @@ -624,12 +727,12 @@ *Kuldeep Aggarwal* -* Fixed serialized fields returning serialized data after being updated with +* Fix serialized fields returning serialized data after being updated with `update_column`. *Simon Hørup Eskildsen* -* Fixed polymorphic eager loading when using a String as foreign key. +* Fix polymorphic eager loading when using a String as foreign key. Fixes #14734. @@ -643,7 +746,7 @@ *Brock Trappitt* -* Fixed the inferred table name of a `has_and_belongs_to_many` auxiliar +* Fix the inferred table name of a `has_and_belongs_to_many` auxiliary table inside a schema. Fixes #14824. @@ -755,7 +858,7 @@ *Yves Senn* -* Fixed has_and_belongs_to_many's CollectionAssociation size calculation. +* Fix `has_and_belongs_to_many` CollectionAssociation size calculations. `has_and_belongs_to_many` should fall back to using the normal CollectionAssociation's size calculation if the collection is not cached or loaded. @@ -860,10 +963,12 @@ *Earl St Sauver* -* Fixed unexpected behavior for `has_many :through` associations going through a scoped `has_many`. +* Fix unexpected behavior for `has_many :through` associations going through + a scoped `has_many`. - If a `has_many` association is adjusted using a scope, and another `has_many :through` - uses this association, then the scope adjustment is unexpectedly neglected. + If a `has_many` association is adjusted using a scope, and another + `has_many :through` uses this association, then the scope adjustment is + unexpectedly neglected. Fixes #14537. @@ -873,13 +978,13 @@ *Kuldeep Aggarwal* -* Fixed `has_many` association to make it support irregular inflections. +* Enable `has_many` associations to support irregular inflections. Fixes #8928. *arthurnn*, *Javier Goizueta* -* Fixed a problem where count used with a grouping was not returning a Hash. +* Fix `count` used with a grouping not returning a Hash. Fixes #14721. @@ -934,8 +1039,8 @@ *Eileen M. Uchitelle*, *Aaron Patterson* -* Fixed error for aggregate methods (`empty?`, `any?`, `count`) with `select` - which created invalid SQL. +* Fix invalid SQL when aggregate methods (`empty?`, `any?`, `count`) used + with `select`. Fixes #13648. @@ -966,8 +1071,8 @@ *Roderick van Domburg* -* Fixed a problem where an enum would overwrite values of another enum - with the same name in an unrelated class. +* Fix a problem where an enum would overwrite values of another enum with the + same name in an unrelated class. Fixes #14607. @@ -1002,7 +1107,7 @@ *arthurnn* -* Fixed error when using `with_options` with lambda. +* Fix error when using `with_options` with lambda. Fixes #9805. @@ -1040,14 +1145,15 @@ *Yves Senn* -* Fixed error when specifying a non-empty default value on a PostgreSQL array column. +* Fix error when specifying a non-empty default value on a PostgreSQL array + column. Fixes #10613. *Luke Steensen* -* Fixed error where .persisted? throws SystemStackError for an unsaved model with a - custom primary key that didn't save due to validation error. +* Fix error where `.persisted?` throws SystemStackError for an unsaved model with a + custom primary key that did not save due to validation error. Fixes #14393. @@ -1140,7 +1246,8 @@ *Aaron Patterson* -* Only use BINARY for MySQL case sensitive uniqueness check when column has a case insensitive collation. +* Only use BINARY for MySQL case sensitive uniqueness check when column + has a case insensitive collation. *Ryuta Kamizono* @@ -1148,8 +1255,8 @@ *arthurnn*, *Tatsuhiko Miyagawa* -* Support for Postgres `citext` data type enabling case-insensitive where - values without needing to wrap in UPPER/LOWER sql functions. +* Support for PostgreSQL `citext` data type enabling case-insensitive + `where` values without needing to wrap in UPPER/LOWER sql functions. *Troy Kruthoff*, *Lachlan Sylvester* @@ -1179,9 +1286,8 @@ *Aaron Patterson*, *Yves Senn* -* Fixed error with validation with enum fields for records where the - value for any enum attribute is always evaluated as 0 during - uniqueness validation. +* Fix error with validation with enum fields for records where the value for + any enum attribute is always evaluated as 0 during uniqueness validation. Fixes #14172. @@ -1195,8 +1301,8 @@ Fixes #14144. -* Fixed STI classes not defining an attribute method if there is a - conflicting private method defined on its ancestors. +* Fix STI classes not defining an attribute method if there is a conflicting + private method defined on its ancestors. Fixes #11569. diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec index 6231851be5..834fffeb18 100644 --- a/activerecord/activerecord.gemspec +++ b/activerecord/activerecord.gemspec @@ -24,5 +24,5 @@ Gem::Specification.new do |s| s.add_dependency 'activesupport', version s.add_dependency 'activemodel', version - s.add_dependency 'arel', '>= 6.0.0.beta1', '< 6.1' + s.add_dependency 'arel', '~> 6.0' end diff --git a/activerecord/lib/active_record/aggregations.rb b/activerecord/lib/active_record/aggregations.rb index e576ec4d40..1040e6e3bb 100644 --- a/activerecord/lib/active_record/aggregations.rb +++ b/activerecord/lib/active_record/aggregations.rb @@ -230,8 +230,8 @@ module ActiveRecord private def reader_method(name, class_name, mapping, allow_nil, constructor) define_method(name) do - if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|key, _| !read_attribute(key).nil? }) - attrs = mapping.collect {|key, _| read_attribute(key)} + if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? {|key, _| !_read_attribute(key).nil? }) + attrs = mapping.collect {|key, _| _read_attribute(key)} object = constructor.respond_to?(:call) ? constructor.call(*attrs) : class_name.constantize.send(constructor, *attrs) diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 12ca3a48a9..d2bcdc55bf 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -46,6 +46,12 @@ module ActiveRecord end end + class HasOneAssociationPolymorphicThroughError < ActiveRecordError #:nodoc: + def initialize(owner_class_name, reflection) + super("Cannot have a has_one :through association '#{owner_class_name}##{reflection.name}' which goes through the polymorphic association '#{owner_class_name}##{reflection.through_reflection.name}'.") + end + end + class HasManyThroughSourceAssociationNotFoundError < ActiveRecordError #:nodoc: def initialize(reflection) through_reflection = reflection.through_reflection @@ -1694,7 +1700,7 @@ module ActiveRecord hm_options[:through] = middle_reflection.name hm_options[:source] = join_model.right_reflection.name - [:before_add, :after_add, :before_remove, :after_remove, :autosave, :validate, :join_table].each do |k| + [:before_add, :after_add, :before_remove, :after_remove, :autosave, :validate, :join_table, :class_name].each do |k| hm_options[k] = options[k] if options.key? k end diff --git a/activerecord/lib/active_record/associations/alias_tracker.rb b/activerecord/lib/active_record/associations/alias_tracker.rb index a6a1947148..0c3234ed24 100644 --- a/activerecord/lib/active_record/associations/alias_tracker.rb +++ b/activerecord/lib/active_record/associations/alias_tracker.rb @@ -57,20 +57,10 @@ module ActiveRecord end def aliased_table_for(table_name, aliased_name) - table_alias = aliased_name_for(table_name, aliased_name) - - if table_alias == table_name - Arel::Table.new(table_name) - else - Arel::Table.new(table_name).alias(table_alias) - end - end - - def aliased_name_for(table_name, aliased_name) if aliases[table_name].zero? # If it's zero, we can have our table_name aliases[table_name] = 1 - table_name + Arel::Table.new(table_name) else # Otherwise, we need to use an alias aliased_name = connection.table_alias_for(aliased_name) @@ -78,11 +68,12 @@ module ActiveRecord # Update the count aliases[aliased_name] += 1 - if aliases[aliased_name] > 1 + table_alias = if aliases[aliased_name] > 1 "#{truncate(aliased_name)}_#{aliases[aliased_name]}" else aliased_name end + Arel::Table.new(table_name).alias(table_alias) end end diff --git a/activerecord/lib/active_record/associations/association_scope.rb b/activerecord/lib/active_record/associations/association_scope.rb index b965230e60..dcbd57e61d 100644 --- a/activerecord/lib/active_record/associations/association_scope.rb +++ b/activerecord/lib/active_record/associations/association_scope.rb @@ -11,8 +11,7 @@ module ActiveRecord end def bind_value(scope, column, value, alias_tracker) - substitute = alias_tracker.connection.substitute_at( - column, scope.bind_values.length) + substitute = alias_tracker.connection.substitute_at(column) scope.bind_values += [[column, @block.call(value)]] substitute 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 815e8eb97f..092b4ebd2f 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 @@ -98,7 +98,7 @@ module ActiveRecord::Associations::Builder def middle_options(join_model) middle_options = {} - middle_options[:class] = join_model + middle_options[:class_name] = "#{lhs_model.name}::#{join_model.name}" middle_options[:source] = join_model.left_reflection.name if options.key? :foreign_key middle_options[:foreign_key] = options[:foreign_key] @@ -110,7 +110,7 @@ module ActiveRecord::Associations::Builder rhs_options = {} if options.key? :class_name - rhs_options[:foreign_key] = options[:class_name].foreign_key + rhs_options[:foreign_key] = options[:class_name].to_s.foreign_key rhs_options[:class_name] = options[:class_name] end diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 1836ff0910..2b7d39893d 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -33,7 +33,13 @@ module ActiveRecord reload end - @proxy ||= CollectionProxy.create(klass, self) + if owner.new_record? + # Cache the proxy separately before the owner has an id + # or else a post-save proxy will still lack the id + @new_record_proxy ||= CollectionProxy.create(klass, self) + else + @proxy ||= CollectionProxy.create(klass, self) + end end # Implements the writer method, e.g. foo.items= for Foo.has_many :items @@ -169,8 +175,8 @@ module ActiveRecord end # Removes all records from the association without calling callbacks - # on the associated records. It honors the `:dependent` option. However - # if the `:dependent` value is `:destroy` then in that case the `:delete_all` + # on the associated records. It honors the +:dependent+ option. However + # if the +:dependent+ value is +:destroy+ then in that case the +:delete_all+ # deletion strategy for the association is applied. # # You can force a particular deletion strategy by passing a parameter. @@ -352,6 +358,7 @@ module ActiveRecord if owner.new_record? replace_records(other_array, original_target) else + replace_common_records_in_memory(other_array, original_target) if other_array != original_target transaction { replace_records(other_array, original_target) } end @@ -379,11 +386,18 @@ module ActiveRecord target end - def add_to_target(record, skip_callbacks = false) + def add_to_target(record, skip_callbacks = false, &block) + if association_scope.distinct_value + index = @target.index(record) + end + replace_on_target(record, index, skip_callbacks, &block) + end + + def replace_on_target(record, index, skip_callbacks) callback(:before_add, record) unless skip_callbacks yield(record) if block_given? - if association_scope.distinct_value && index = @target.index(record) + if index @target[index] = record else @target << record @@ -407,7 +421,13 @@ module ActiveRecord private def get_records - return scope.to_a if reflection.scope_chain.any?(&:any?) || scope.eager_loading? + if reflection.scope_chain.any?(&:any?) || + scope.eager_loading? || + klass.current_scope || + klass.default_scopes.any? + + return scope.to_a + end conn = klass.connection sc = reflection.association_scope_cache(conn, owner) do @@ -522,6 +542,14 @@ module ActiveRecord target end + def replace_common_records_in_memory(new_target, original_target) + common_records = new_target & original_target + common_records.each do |record| + skip_callbacks = true + replace_on_target(record, @target.index(record), skip_callbacks) + end + end + def concat_records(records, should_raise = false) result = true diff --git a/activerecord/lib/active_record/associations/has_many_association.rb b/activerecord/lib/active_record/associations/has_many_association.rb index 1413efaf7f..93084e0dcf 100644 --- a/activerecord/lib/active_record/associations/has_many_association.rb +++ b/activerecord/lib/active_record/associations/has_many_association.rb @@ -66,7 +66,7 @@ module ActiveRecord # the loaded flag is set to true as well. def count_records count = if has_cached_counter? - owner.read_attribute cached_counter_attribute_name + owner._read_attribute cached_counter_attribute_name else scope.count end diff --git a/activerecord/lib/active_record/associations/has_many_through_association.rb b/activerecord/lib/active_record/associations/has_many_through_association.rb index 455a540bdb..6329fdfe95 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/string/filters' + module ActiveRecord # = Active Record Has Many Through Association module Associations @@ -18,7 +20,7 @@ module ActiveRecord # SELECT query will be generated by using #length instead. def size if has_cached_counter? - owner.read_attribute cached_counter_attribute_name(reflection) + owner._read_attribute cached_counter_attribute_name(reflection) elsif loaded? target.size else @@ -63,11 +65,12 @@ module ActiveRecord save_through_record(record) if has_cached_counter? && !through_reflection_updates_counter_cache? - ActiveSupport::Deprecation.warn \ - "Automatic updating of counter caches on through associations has been " \ - "deprecated, and will be removed in Rails 5.0. Instead, please set the " \ - "appropriate counter_cache options on the has_many and belongs_to for " \ - "your associations to #{through_reflection.name}." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + Automatic updating of counter caches on through associations has been + deprecated, and will be removed in Rails 5. Instead, please set the + appropriate `counter_cache` options on the `has_many` and `belongs_to` + for your associations to #{through_reflection.name}. + MSG update_counter_in_database(1) end @@ -158,8 +161,8 @@ module ActiveRecord if scope.klass.primary_key count = scope.destroy_all.length else - scope.to_a.each do |record| - record.run_destroy_callbacks + scope.each do |record| + record._run_destroy_callbacks end arel = scope.arel diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb index ec5c189cd3..285d0ec9af 100644 --- a/activerecord/lib/active_record/associations/join_dependency.rb +++ b/activerecord/lib/active_record/associations/join_dependency.rb @@ -94,7 +94,7 @@ module ActiveRecord # def initialize(base, associations, joins) @alias_tracker = AliasTracker.create(base.connection, joins) - @alias_tracker.aliased_name_for(base.table_name, base.table_name) # Updates the count for base.table_name to 1 + @alias_tracker.aliased_table_for(base.table_name, base.table_name) # Updates the count for base.table_name to 1 tree = self.class.make_tree associations @join_root = JoinBase.new base, build(tree, base) @join_root.children.each { |child| construct_tables! @join_root, child } @@ -142,11 +142,20 @@ module ActiveRecord parents = model_cache[join_root] column_aliases = aliases.column_aliases join_root - result_set.each { |row_hash| - parent = parents[row_hash[primary_key]] ||= join_root.instantiate(row_hash, column_aliases) - construct(parent, join_root, row_hash, result_set, seen, model_cache, aliases) + message_bus = ActiveSupport::Notifications.instrumenter + + payload = { + record_count: result_set.length, + class_name: join_root.base_klass.name } + message_bus.instrument('instantiation.active_record', payload) do + result_set.each { |row_hash| + parent = parents[row_hash[primary_key]] ||= join_root.instantiate(row_hash, column_aliases) + construct(parent, join_root, row_hash, result_set, seen, model_cache, aliases) + } + end + parents.values end diff --git a/activerecord/lib/active_record/associations/join_dependency/join_association.rb b/activerecord/lib/active_record/associations/join_dependency/join_association.rb index e7d3c9ba40..5dede5527d 100644 --- a/activerecord/lib/active_record/associations/join_dependency/join_association.rb +++ b/activerecord/lib/active_record/associations/join_dependency/join_association.rb @@ -67,7 +67,7 @@ module ActiveRecord value = foreign_klass.base_class.name column = klass.columns_hash[reflection.type.to_s] - substitute = klass.connection.substitute_at(column, bind_values.length) + substitute = klass.connection.substitute_at(column) bind_values.push [column, value] constraint = constraint.and table[reflection.type].eq substitute end diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index c0639742be..7d6523dbc4 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -142,14 +142,8 @@ module ActiveRecord scope._select! preload_values[:select] || values[:select] || table[Arel.star] scope.includes! preload_values[:includes] || values[:includes] - - if preload_values.key? :order - scope.order! preload_values[:order] - else - if values.key? :order - scope.order! values[:order] - end - end + scope.joins! preload_values[:joins] || values[:joins] + scope.order! preload_values[:order] || values[:order] if preload_values[:readonly] || values[:readonly] scope.readonly! @@ -159,6 +153,7 @@ module ActiveRecord scope.where!(klass.table_name => { reflection.type => model.base_class.sti_name }) end + scope.unscope_values = Array(values[:unscope]) klass.default_scoped.merge(scope) end end diff --git a/activerecord/lib/active_record/associations/preloader/through_association.rb b/activerecord/lib/active_record/associations/preloader/through_association.rb index d57da366bd..12bf3ef138 100644 --- a/activerecord/lib/active_record/associations/preloader/through_association.rb +++ b/activerecord/lib/active_record/associations/preloader/through_association.rb @@ -81,6 +81,7 @@ module ActiveRecord unless reflection_scope.where_values.empty? scope.includes_values = Array(reflection_scope.values[:includes] || options[:source]) scope.where_values = reflection_scope.values[:where] + scope.bind_values = reflection_scope.bind_values end scope.references! reflection_scope.values[:references] diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb index b9326b9683..c44242a0f0 100644 --- a/activerecord/lib/active_record/associations/singular_association.rb +++ b/activerecord/lib/active_record/associations/singular_association.rb @@ -39,7 +39,13 @@ module ActiveRecord end def get_records - return scope.limit(1).to_a if reflection.scope_chain.any?(&:any?) || scope.eager_loading? + if reflection.scope_chain.any?(&:any?) || + scope.eager_loading? || + klass.current_scope || + klass.default_scopes.any? + + return scope.limit(1).to_a + end conn = klass.connection sc = reflection.association_scope_cache(conn, owner) do diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index f4a4e3f605..d766996d37 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -1,4 +1,5 @@ require 'active_support/core_ext/enumerable' +require 'active_support/core_ext/string/filters' require 'mutex_m' require 'thread_safe' @@ -90,7 +91,7 @@ module ActiveRecord def undefine_attribute_methods # :nodoc: generated_attribute_methods.synchronize do - super if @attribute_methods_generated + super if defined?(@attribute_methods_generated) && @attribute_methods_generated @attribute_methods_generated = false end end @@ -205,9 +206,11 @@ module ActiveRecord def column_for_attribute(name) column = columns_hash[name.to_s] if column.nil? - ActiveSupport::Deprecation.warn \ - "`column_for_attribute` will return a null object for non-existent columns " \ - "in Rails 5.0. Use `has_attribute?` if you need to check for an attribute's existence." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + `#column_for_attribute` will return a null object for non-existent + columns in Rails 5. Use `#has_attribute?` if you need to check for + an attribute's existence. + MSG end column end @@ -329,7 +332,7 @@ module ActiveRecord # task.attribute_present?(:title) # => true # task.attribute_present?(:is_done) # => true def attribute_present?(attribute) - value = read_attribute(attribute) + value = _read_attribute(attribute) !value.nil? && !(value.respond_to?(:empty?) && value.empty?) end @@ -430,7 +433,7 @@ module ActiveRecord end def typecasted_attribute_value(name) - read_attribute(name) + _read_attribute(name) end end end diff --git a/activerecord/lib/active_record/attribute_methods/dirty.rb b/activerecord/lib/active_record/attribute_methods/dirty.rb index 2f02738f6d..9ba46ec4c7 100644 --- a/activerecord/lib/active_record/attribute_methods/dirty.rb +++ b/activerecord/lib/active_record/attribute_methods/dirty.rb @@ -110,7 +110,7 @@ module ActiveRecord if attribute_changed?(attr) changed_attributes[attr] else - clone_attribute_value(:read_attribute, attr) + clone_attribute_value(:_read_attribute, attr) end end diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb index 9bd333bbac..c28374e4ab 100644 --- a/activerecord/lib/active_record/attribute_methods/primary_key.rb +++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb @@ -17,7 +17,7 @@ module ActiveRecord def id if pk = self.class.primary_key sync_with_transaction_state - read_attribute(pk) + _read_attribute(pk) end end @@ -120,6 +120,7 @@ module ActiveRecord def primary_key=(value) @primary_key = value && value.to_s @quoted_primary_key = nil + @attributes_builder = nil end end end diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb index bf2a084a00..20f0936e52 100644 --- a/activerecord/lib/active_record/attribute_methods/read.rb +++ b/activerecord/lib/active_record/attribute_methods/read.rb @@ -27,7 +27,7 @@ module ActiveRecord <<-EOMETHOD def #{method_name} name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{const_name} - read_attribute(name) { |n| missing_attribute(n, caller) } + _read_attribute(name) { |n| missing_attribute(n, caller) } end EOMETHOD end @@ -64,7 +64,7 @@ module ActiveRecord generated_attribute_methods.module_eval <<-STR, __FILE__, __LINE__ + 1 def #{temp_method} name = ::ActiveRecord::AttributeMethods::AttrNames::ATTR_#{safe_name} - read_attribute(name) { |n| missing_attribute(n, caller) } + _read_attribute(name) { |n| missing_attribute(n, caller) } end STR @@ -76,19 +76,27 @@ module ActiveRecord end end + ID = 'id'.freeze + # Returns the value of the attribute identified by <tt>attr_name</tt> after # it has been typecast (for example, "2004-12-12" in a date column is cast # to a date object, like Date.new(2004, 12, 12)). def read_attribute(attr_name, &block) name = attr_name.to_s - name = self.class.primary_key if name == 'id' - @attributes.fetch_value(name, &block) + name = self.class.primary_key if name == ID + _read_attribute(name, &block) + end + + # This method exists to avoid the expensive primary_key check internally, without + # breaking compatibility with the read_attribute API + def _read_attribute(attr_name) # :nodoc: + @attributes.fetch_value(attr_name.to_s) { |n| yield n if block_given? } end private def attribute(attribute_name) - read_attribute(attribute_name) + _read_attribute(attribute_name) end end end diff --git a/activerecord/lib/active_record/attribute_methods/serialization.rb b/activerecord/lib/active_record/attribute_methods/serialization.rb index 100d6d4229..e5ec5ddca5 100644 --- a/activerecord/lib/active_record/attribute_methods/serialization.rb +++ b/activerecord/lib/active_record/attribute_methods/serialization.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/string/filters' + module ActiveRecord module AttributeMethods module Serialization @@ -8,11 +10,8 @@ module ActiveRecord # object, and retrieved as the same object, then specify the name of that # attribute using this method and it will be handled automatically. The # serialization is done through YAML. If +class_name+ is specified, the - # serialized object must be of that class on retrieval or - # <tt>SerializationTypeMismatch</tt> will be raised. - # - # A notable side effect of serialized attributes is that the model will - # be updated on every save, even if it is not dirty. + # serialized object must be of that class on assignment and retrieval. + # Otherwise <tt>SerializationTypeMismatch</tt> will be raised. # # ==== Parameters # @@ -54,8 +53,10 @@ module ActiveRecord end def serialized_attributes - ActiveSupport::Deprecation.warn "`serialized_attributes` is deprecated " \ - "without replacement, and will be removed in Rails 5.0." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + `serialized_attributes` is deprecated without replacement, and will + be removed in Rails 5.0. + MSG @serialized_attributes ||= Hash[ columns.select { |t| t.cast_type.is_a?(Type::Serialized) }.map { |c| 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 b7fe079ef5..33d9d2002c 100644 --- a/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb +++ b/activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb @@ -1,7 +1,7 @@ module ActiveRecord module AttributeMethods module TimeZoneConversion - class TimeZoneConverter < SimpleDelegator # :nodoc: + class TimeZoneConverter < DelegateClass(Type::Value) # :nodoc: include Type::Decorator def type_cast_from_database(value) diff --git a/activerecord/lib/active_record/attribute_set.rb b/activerecord/lib/active_record/attribute_set.rb index 98ac63c7e1..6b1d7ea79e 100644 --- a/activerecord/lib/active_record/attribute_set.rb +++ b/activerecord/lib/active_record/attribute_set.rb @@ -2,8 +2,6 @@ require 'active_record/attribute_set/builder' module ActiveRecord class AttributeSet # :nodoc: - delegate :keys, to: :initialized_attributes - def initialize(attributes) @attributes = attributes end @@ -25,8 +23,12 @@ module ActiveRecord attributes.key?(name) && self[name].initialized? end - def fetch_value(name, &block) - self[name].value(&block) + def keys + attributes.initialized_keys + end + + def fetch_value(name) + self[name].value { |n| yield n if block_given? } end def write_from_database(name, value) @@ -43,7 +45,7 @@ module ActiveRecord end def initialize_dup(_) - @attributes = attributes.transform_values(&:dup) + @attributes = attributes.dup super end @@ -58,12 +60,6 @@ module ActiveRecord end end - def ensure_initialized(key) - unless self[key].initialized? - write_from_database(key, nil) - end - end - protected attr_reader :attributes diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb index d4a787f2fe..05138ae36d 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -1,35 +1,84 @@ module ActiveRecord class AttributeSet # :nodoc: class Builder # :nodoc: - attr_reader :types + attr_reader :types, :always_initialized - def initialize(types) + def initialize(types, always_initialized = nil) @types = types + @always_initialized = always_initialized end def build_from_database(values = {}, additional_types = {}) - attributes = build_attributes_from_values(values, additional_types) - add_uninitialized_attributes(attributes) + if always_initialized && !values.key?(always_initialized) + values[always_initialized] = nil + end + + attributes = LazyAttributeHash.new(types, values, additional_types) AttributeSet.new(attributes) end + end + end - private + class LazyAttributeHash # :nodoc: + delegate :select, :transform_values, to: :materialize - def build_attributes_from_values(values, additional_types) - values.each_with_object({}) do |(name, value), hash| - type = additional_types.fetch(name, types[name]) - hash[name] = Attribute.from_database(name, value, type) - end + def initialize(types, values, additional_types) + @types = types + @values = values + @additional_types = additional_types + @materialized = false + @delegate_hash = {} + end + + def key?(key) + delegate_hash.key?(key) || values.key?(key) || types.key?(key) + end + + def [](key) + delegate_hash[key] || assign_default_value(key) + end + + def []=(key, value) + if frozen? + raise RuntimeError, "Can't modify frozen hash" + end + delegate_hash[key] = value + end + + def initialized_keys + delegate_hash.keys | values.keys + end + + def initialize_dup(_) + @delegate_hash = delegate_hash.transform_values(&:dup) + super + end + + protected + + attr_reader :types, :values, :additional_types, :delegate_hash + + private + + def assign_default_value(name) + type = additional_types.fetch(name, types[name]) + value_present = true + value = values.fetch(name) { value_present = false } + + if value_present + delegate_hash[name] = Attribute.from_database(name, value, type) + elsif types.key?(name) + delegate_hash[name] = Attribute.uninitialized(name, type) end + end - def add_uninitialized_attributes(attributes) - types.each_key do |name| - next if attributes.key? name - type = types[name] - attributes[name] = - Attribute.uninitialized(name, type) - end + def materialize + unless @materialized + values.each_key { |key| self[key] } + types.each_key { |key| self[key] } + @materialized = true end + delegate_hash end end end diff --git a/activerecord/lib/active_record/attributes.rb b/activerecord/lib/active_record/attributes.rb index 890a1314d9..3288108a6a 100644 --- a/activerecord/lib/active_record/attributes.rb +++ b/activerecord/lib/active_record/attributes.rb @@ -6,7 +6,9 @@ module ActiveRecord included do class_attribute :user_provided_columns, instance_accessor: false # :internal: + class_attribute :user_provided_defaults, instance_accessor: false # :internal: self.user_provided_columns = {} + self.user_provided_defaults = {} end module ClassMethods # :nodoc: @@ -77,7 +79,11 @@ module ActiveRecord name = name.to_s clear_caches_calculated_from_columns # Assign a new hash to ensure that subclasses do not share a hash - self.user_provided_columns = user_provided_columns.merge(name => connection.new_column(name, options[:default], cast_type)) + self.user_provided_columns = user_provided_columns.merge(name => cast_type) + + if options.key?(:default) + self.user_provided_defaults = user_provided_defaults.merge(name => options[:default]) + end end # Returns an array of column objects for the table associated with this class. @@ -99,11 +105,18 @@ module ActiveRecord def add_user_provided_columns(schema_columns) existing_columns = schema_columns.map do |column| - user_provided_columns[column.name] || column + new_type = user_provided_columns[column.name] + if new_type + column.with_type(new_type) + else + column + end end existing_column_names = existing_columns.map(&:name) - new_columns = user_provided_columns.except(*existing_column_names).values + new_columns = user_provided_columns.except(*existing_column_names).map do |(name, type)| + connection.new_column(name, nil, type) + end existing_columns + new_columns end @@ -117,6 +130,10 @@ module ActiveRecord @content_columns = nil @default_attributes = nil end + + def raw_default_values + super.merge(user_provided_defaults) + end end end end diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index c384e8c413..a0d70435fa 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -184,7 +184,9 @@ module ActiveRecord before_save :before_save_collection_association define_non_cyclic_method(save_method) { save_collection_association(reflection) } - after_save save_method + # Doesn't use after_save as that would save associations added in after_create/after_update twice + after_create save_method + after_update save_method elsif reflection.has_one? define_method(save_method) { save_has_one_association(reflection) } unless method_defined?(save_method) # Configures two callbacks instead of a single after_save so that diff --git a/activerecord/lib/active_record/callbacks.rb b/activerecord/lib/active_record/callbacks.rb index 1aa760157a..523d492a48 100644 --- a/activerecord/lib/active_record/callbacks.rb +++ b/activerecord/lib/active_record/callbacks.rb @@ -289,25 +289,25 @@ module ActiveRecord end def destroy #:nodoc: - run_destroy_callbacks { super } + _run_destroy_callbacks { super } end def touch(*) #:nodoc: - run_touch_callbacks { super } + _run_touch_callbacks { super } end private def create_or_update #:nodoc: - run_save_callbacks { super } + _run_save_callbacks { super } end def _create_record #:nodoc: - run_create_callbacks { super } + _run_create_callbacks { super } end def _update_record(*) #:nodoc: - run_update_callbacks { super } + _run_update_callbacks { super } end end end 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 da43e5bb10..46812b75bb 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -2,6 +2,7 @@ require 'thread' require 'thread_safe' require 'monitor' require 'set' +require 'active_support/core_ext/string/filters' module ActiveRecord # Raised when a connection could not be obtained within the connection @@ -360,7 +361,7 @@ module ActiveRecord synchronize do owner = conn.owner - conn.run_checkin_callbacks do + conn._run_checkin_callbacks do conn.expire end @@ -449,7 +450,7 @@ module ActiveRecord end def checkout_and_verify(c) - c.run_checkout_callbacks do + c._run_checkout_callbacks do c.verify! end c @@ -518,10 +519,11 @@ module ActiveRecord end def connection_pools - ActiveSupport::Deprecation.warn( - "In the next release, this will return the same as #connection_pool_list. " \ - "(An array of pools, rather than a hash mapping specs to pools.)" - ) + ActiveSupport::Deprecation.warn(<<-MSG.squish) + In the next release, this will return the same as `#connection_pool_list`. + (An array of pools, rather than a hash mapping specs to pools.) + MSG + Hash[connection_pool_list.map { |pool| [pool.spec, pool] }] end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb index ff8b3e9890..12b16b2473 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb @@ -287,10 +287,6 @@ module ActiveRecord "DEFAULT VALUES" end - def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key) - "WHERE #{quoted_primary_key} IN (SELECT #{quoted_primary_key} FROM #{quoted_table_name} #{where_sql})" - end - # Sanitizes the given LIMIT parameter in order to prevent SQL injection. # # The +limit+ may be anything that can evaluate to a string via #to_s. It @@ -337,8 +333,9 @@ module ActiveRecord # Returns an ActiveRecord::Result instance. def select(sql, name = nil, binds = []) + exec_query(sql, name, binds) end - undef_method :select + # Returns the last auto-generated ID from the affected table. def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb index eb88845913..679878d860 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb @@ -108,7 +108,7 @@ module ActiveRecord when Numeric, ActiveSupport::Duration then value.to_s when Date, Time then "'#{quoted_date(value)}'" when Symbol then "'#{quote_string(value.to_s)}'" - when Class then "'#{value.to_s}'" + when Class then "'#{value}'" else "'#{quote_string(YAML.dump(value))}'" end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index fe00f9d750..d2236d046b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -60,11 +60,11 @@ module ActiveRecord def emit_warning_if_null_unspecified(options) return if options.key?(:null) - ActiveSupport::Deprecation.warn \ - "`timestamp` was called without specifying an option for `null`. In Rails " \ - "5.0, this behavior will change to `null: false`. You should manually " \ - "specify `null: true` to prevent the behavior of your existing migrations " \ - "from changing." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + `#timestamp` was called without specifying an option for `null`. In Rails 5, + this behavior will change to `null: false`. You should manually specify + `null: true` to prevent the behavior of your existing migrations from changing. + MSG end end @@ -124,8 +124,8 @@ module ActiveRecord # which is one of the following: # <tt>:primary_key</tt>, <tt>:string</tt>, <tt>:text</tt>, # <tt>:integer</tt>, <tt>:float</tt>, <tt>:decimal</tt>, - # <tt>:datetime</tt>, <tt>:timestamp</tt>, <tt>:time</tt>, - # <tt>:date</tt>, <tt>:binary</tt>, <tt>:boolean</tt>. + # <tt>:datetime</tt>, <tt>:time</tt>, <tt>:date</tt>, + # <tt>:binary</tt>, <tt>:boolean</tt>. # # You may use a type not in this list as long as it is supported by your # database (for example, "polygon" in MySQL), but this will not be database @@ -226,7 +226,7 @@ module ActiveRecord # t.integer :shop_id, :creator_id # t.string :item_number, index: true # t.string :name, :value, default: "Untitled" - # t.timestamps + # t.timestamps null: false # end # # There's a short-hand method for each of the type values declared at the top. And then there's @@ -256,7 +256,7 @@ module ActiveRecord name = name.to_s type = type.to_sym - if primary_key_column_name == name + if @columns_hash[name] && @columns_hash[name].primary_key? raise ArgumentError, "you can't redefine the primary key column '#{name}'. To define a custom primary key, pass { id: false } to create_table." end @@ -270,7 +270,7 @@ module ActiveRecord @columns_hash.delete name.to_s end - [:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type| + [:string, :text, :integer, :bigint, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type| define_method column_type do |*args| options = args.extract_options! column_names = args @@ -287,7 +287,9 @@ module ActiveRecord end # Appends <tt>:datetime</tt> columns <tt>:created_at</tt> and - # <tt>:updated_at</tt> to the table. + # <tt>:updated_at</tt> to the table. See SchemaStatements#add_timestamps + # + # t.timestamps null: false def timestamps(*args) options = args.extract_options! emit_warning_if_null_unspecified(options) @@ -312,13 +314,13 @@ module ActiveRecord args.each do |col| column("#{col}_id", type, options) column("#{col}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic - index(polymorphic ? %w(id type).map { |t| "#{col}_#{t}" } : "#{col}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options + index(polymorphic ? %w(type id).map { |t| "#{col}_#{t}" } : "#{col}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options end end alias :belongs_to :references def new_column_definition(name, type, options) # :nodoc: - type = aliased_types[type] || type + type = aliased_types(type.to_s, type) column = create_column_definition name, type limit = options.fetch(:limit) do native[type][:limit] if native[type].is_a?(Hash) @@ -340,19 +342,12 @@ module ActiveRecord ColumnDefinition.new name, type end - def primary_key_column_name - primary_key_column = columns.detect { |c| c.primary_key? } - primary_key_column && primary_key_column.name - end - def native @native end - def aliased_types - HashWithIndifferentAccess.new( - timestamp: :datetime, - ) + def aliased_types(name, fallback) + 'timestamp' == name ? :datetime : fallback end end @@ -419,10 +414,10 @@ module ActiveRecord # end # class Table - include TimestampDefaultDeprecation + attr_reader :name def initialize(table_name, base) - @table_name = table_name + @name = table_name @base = base end @@ -432,12 +427,12 @@ module ActiveRecord # ====== Creating a simple column # t.column(:name, :string) def column(column_name, type, options = {}) - @base.add_column(@table_name, column_name, type, options) + @base.add_column(name, column_name, type, options) end # Checks to see if a column exists. See SchemaStatements#column_exists? def column_exists?(column_name, type = nil, options = {}) - @base.column_exists?(@table_name, column_name, type, options) + @base.column_exists?(name, column_name, type, options) end # Adds a new index to the table. +column_name+ can be a single Symbol, or @@ -450,27 +445,26 @@ module ActiveRecord # ====== Creating a named index # t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party') def index(column_name, options = {}) - @base.add_index(@table_name, column_name, options) + @base.add_index(name, column_name, options) end # Checks to see if an index exists. See SchemaStatements#index_exists? def index_exists?(column_name, options = {}) - @base.index_exists?(@table_name, column_name, options) + @base.index_exists?(name, column_name, options) end # Renames the given index on the table. # # t.rename_index(:user_id, :account_id) def rename_index(index_name, new_index_name) - @base.rename_index(@table_name, index_name, new_index_name) + @base.rename_index(name, index_name, new_index_name) end # Adds timestamps (+created_at+ and +updated_at+) columns to the table. See SchemaStatements#add_timestamps # - # t.timestamps + # t.timestamps null: false def timestamps(options = {}) - emit_warning_if_null_unspecified(options) - @base.add_timestamps(@table_name, options) + @base.add_timestamps(name, options) end # Changes the column's definition according to the new options. @@ -479,7 +473,7 @@ module ActiveRecord # t.change(:name, :string, limit: 80) # t.change(:description, :text) def change(column_name, type, options = {}) - @base.change_column(@table_name, column_name, type, options) + @base.change_column(name, column_name, type, options) end # Sets a new default value for a column. See SchemaStatements#change_column_default @@ -487,7 +481,7 @@ module ActiveRecord # t.change_default(:qualification, 'new') # t.change_default(:authorized, 1) def change_default(column_name, default) - @base.change_column_default(@table_name, column_name, default) + @base.change_column_default(name, column_name, default) end # Removes the column(s) from the table definition. @@ -495,7 +489,7 @@ module ActiveRecord # t.remove(:qualification) # t.remove(:qualification, :experience) def remove(*column_names) - @base.remove_columns(@table_name, *column_names) + @base.remove_columns(name, *column_names) end # Removes the given index from the table. @@ -509,21 +503,21 @@ module ActiveRecord # ====== Remove the index named by_branch_party in the table_name table # t.remove_index name: :by_branch_party def remove_index(options = {}) - @base.remove_index(@table_name, options) + @base.remove_index(name, options) end # Removes the timestamp columns (+created_at+ and +updated_at+) from the table. # # t.remove_timestamps def remove_timestamps - @base.remove_timestamps(@table_name) + @base.remove_timestamps(name) end # Renames a column. # # t.rename(:description, :name) def rename(column_name, new_column_name) - @base.rename_column(@table_name, column_name, new_column_name) + @base.rename_column(name, column_name, new_column_name) end # Adds a reference. Optionally adds a +type+ column, if <tt>:polymorphic</tt> option is provided. @@ -538,7 +532,7 @@ module ActiveRecord def references(*args) options = args.extract_options! args.each do |ref_name| - @base.add_reference(@table_name, ref_name, options) + @base.add_reference(name, ref_name, options) end end alias :belongs_to :references @@ -553,7 +547,7 @@ module ActiveRecord def remove_references(*args) options = args.extract_options! args.each do |ref_name| - @base.remove_reference(@table_name, ref_name, options) + @base.remove_reference(name, ref_name, options) end end alias :remove_belongs_to :remove_references @@ -565,8 +559,8 @@ module ActiveRecord [:string, :text, :integer, :float, :decimal, :datetime, :timestamp, :time, :date, :binary, :boolean].each do |column_type| define_method column_type do |*args| options = args.extract_options! - args.each do |name| - @base.add_column(@table_name, name, column_type, options) + args.each do |column_name| + @base.add_column(name, column_name, column_type, options) end end end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb index b05a4f8440..6eab11b88b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb @@ -8,7 +8,7 @@ module ActiveRecord module ColumnDumper def column_spec(column, types) spec = prepare_column_options(column, types) - (spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k.to_s}: ")} + (spec.keys - [:name, :type]).each{ |k| spec[k].insert(0, "#{k}: ")} spec end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb index 7105df1ee4..99fa9b7d29 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -571,6 +571,9 @@ module ActiveRecord # rename_index :people, 'index_people_on_last_name', 'index_users_on_last_name' # def rename_index(table_name, old_name, new_name) + if new_name.length > allowed_index_name_length + raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters" + end # this is a naive implementation; some DBs may support this more efficiently (Postgres, for instance) old_index_def = indexes(table_name).detect { |i| i.name == old_name } return unless old_index_def @@ -629,7 +632,7 @@ module ActiveRecord type = options.delete(:type) || :integer add_column(table_name, "#{ref_name}_id", type, options) add_column(table_name, "#{ref_name}_type", :string, polymorphic.is_a?(Hash) ? polymorphic : options) if polymorphic - add_index(table_name, polymorphic ? %w[id type].map{ |t| "#{ref_name}_#{t}" } : "#{ref_name}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options + add_index(table_name, polymorphic ? %w[type id].map{ |t| "#{ref_name}_#{t}" } : "#{ref_name}_id", index_options.is_a?(Hash) ? index_options : {}) if index_options end alias :add_belongs_to :add_reference @@ -740,7 +743,7 @@ module ActiveRecord end fk_name_to_delete = options.fetch(:name) do - fk_to_delete = foreign_keys(from_table).detect {|fk| fk.column == options[:column] } + fk_to_delete = foreign_keys(from_table).detect {|fk| fk.column == options[:column].to_s } if fk_to_delete fk_to_delete.name @@ -835,11 +838,14 @@ module ActiveRecord columns end - # Adds timestamps (+created_at+ and +updated_at+) columns to the named table. + include TimestampDefaultDeprecation + # Adds timestamps (+created_at+ and +updated_at+) columns to +table_name+. + # Additional options (like <tt>null: false</tt>) are forwarded to #add_column. # - # add_timestamps(:suppliers) + # add_timestamps(:suppliers, null: false) # def add_timestamps(table_name, options = {}) + emit_warning_if_null_unspecified(options) add_column table_name, :created_at, :datetime, options add_column table_name, :updated_at, :datetime, options end diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index a0d9086875..e0a4af5359 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -14,10 +14,7 @@ module ActiveRecord module ConnectionAdapters # :nodoc: extend ActiveSupport::Autoload - autoload_at 'active_record/connection_adapters/column' do - autoload :Column - autoload :NullColumn - end + autoload :Column autoload :ConnectionSpecification autoload_at 'active_record/connection_adapters/abstract/schema_definitions' do @@ -27,6 +24,7 @@ module ActiveRecord autoload :TableDefinition autoload :Table autoload :AlterTable + autoload :TimestampDefaultDeprecation end autoload_at 'active_record/connection_adapters/abstract/connection_pool' do @@ -265,10 +263,10 @@ module ActiveRecord # QUOTING ================================================== - # Returns a bind substitution value given a bind +index+ and +column+ + # Returns a bind substitution value given a bind +column+ # NOTE: The column param is currently being used by the sqlserver-adapter - def substitute_at(column, index) - Arel::Nodes::BindParam.new '?' + def substitute_at(column, _unused = 0) + Arel::Nodes::BindParam.new end # REFERENTIAL INTEGRITY ==================================== @@ -386,6 +384,10 @@ module ActiveRecord type_map.lookup(sql_type) end + def column_name_for_operation(operation, node) # :nodoc: + node.to_sql + end + protected def initialize_type_map(m) # :nodoc: 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 e4cfe843a8..c824a7b11b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -91,6 +91,13 @@ module ActiveRecord collation && !collation.match(/_ci$/) end + def ==(other) + super && + collation == other.collation && + strict == other.strict && + extra == other.extra + end + private # MySQL misreports NOT NULL column default when none is given. @@ -109,6 +116,10 @@ module ActiveRecord raise ArgumentError, "#{type} columns cannot have a default value: #{default.inspect}" end end + + def attributes_for_hash + super + [collation, strict, extra] + end end ## @@ -274,7 +285,9 @@ module ActiveRecord end end + #-- # DATABASE STATEMENTS ====================================== + #++ def clear_cache! super @@ -485,7 +498,7 @@ module ActiveRecord end end - def change_column_default(table_name, column_name, default) + def change_column_default(table_name, column_name, default) #:nodoc: column = column_for(table_name, column_name) change_column table_name, column_name, column.sql_type, :default => default end @@ -574,14 +587,6 @@ module ActiveRecord end end - def add_column_position!(sql, options) - if options[:first] - sql << " FIRST" - elsif options[:after] - sql << " AFTER #{quote_column_name(options[:after])}" - end - end - # SHOW VARIABLES LIKE 'name' def show_variable(name) variables = select_all("SHOW VARIABLES LIKE '#{name}'", 'SCHEMA') @@ -628,10 +633,6 @@ module ActiveRecord end end - def limited_update_conditions(where_sql, quoted_table_name, quoted_primary_key) - where_sql - end - def strict_mode? self.class.type_cast_config_to_boolean(@config.fetch(:strict, true)) end @@ -645,11 +646,7 @@ module ActiveRecord def initialize_type_map(m) # :nodoc: super - m.register_type(%r(enum)i) do |sql_type| - limit = sql_type[/^enum\((.+)\)/i, 1] - .split(',').map{|enum| enum.strip.length - 2}.max - Type::String.new(limit: limit) - end + register_class_with_limit m, %r(char)i, MysqlString m.register_type %r(tinytext)i, Type::Text.new(limit: 2**8 - 1) m.register_type %r(tinyblob)i, Type::Binary.new(limit: 2**8 - 1) @@ -671,6 +668,12 @@ module ActiveRecord m.alias_type %r(set)i, 'varchar' m.alias_type %r(year)i, 'integer' m.alias_type %r(bit)i, 'binary' + + m.register_type(%r(enum)i) do |sql_type| + limit = sql_type[/^enum\((.+)\)/i, 1] + .split(',').map{|enum| enum.strip.length - 2}.max + MysqlString.new(limit: limit) + end end # MySQL is too stupid to create a temporary table for use subquery, so we have @@ -825,9 +828,9 @@ module ActiveRecord # Gather up all of the SET variables... variable_assignments = variables.map do |k, v| if v == ':default' || v == :default - "@@SESSION.#{k.to_s} = DEFAULT" # Sets the value to the global or compile default + "@@SESSION.#{k} = DEFAULT" # Sets the value to the global or compile default elsif !v.nil? - "@@SESSION.#{k.to_s} = #{quote(v)}" + "@@SESSION.#{k} = #{quote(v)}" end # or else nil; compact to clear nils out end.compact.join(', ') @@ -844,6 +847,26 @@ module ActiveRecord end end end + + class MysqlString < Type::String # :nodoc: + def type_cast_for_database(value) + case value + when true then "1" + when false then "0" + else super + end + end + + private + + def cast_value(value) + case value + when true then "1" + when false then "0" + else super + end + end + end end end end diff --git a/activerecord/lib/active_record/connection_adapters/column.rb b/activerecord/lib/active_record/connection_adapters/column.rb index 5f9cc6edd0..dd303c73d5 100644 --- a/activerecord/lib/active_record/connection_adapters/column.rb +++ b/activerecord/lib/active_record/connection_adapters/column.rb @@ -56,6 +56,26 @@ module ActiveRecord clone.instance_variable_set('@cast_type', type) end end + + def ==(other) + other.name == name && + other.default == default && + other.cast_type == cast_type && + other.sql_type == sql_type && + other.null == null && + other.default_function == default_function + end + alias :eql? :== + + def hash + attributes_for_hash.hash + end + + private + + def attributes_for_hash + [self.class, name, default, cast_type, sql_type, null, default_function] + end end end # :startdoc: diff --git a/activerecord/lib/active_record/connection_adapters/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/connection_specification.rb index e02824b33d..e54e3199ff 100644 --- a/activerecord/lib/active_record/connection_adapters/connection_specification.rb +++ b/activerecord/lib/active_record/connection_adapters/connection_specification.rb @@ -1,4 +1,5 @@ require 'uri' +require 'active_support/core_ext/string/filters' module ActiveRecord module ConnectionAdapters @@ -221,15 +222,19 @@ module ActiveRecord # this ambiguous behaviour and in the future this function # can be removed in favor of resolve_url_connection. if configurations.key?(spec) || spec !~ /:/ - ActiveSupport::Deprecation.warn "Passing a string to ActiveRecord::Base.establish_connection " \ - "for a configuration lookup is deprecated, please pass a symbol (#{spec.to_sym.inspect}) instead" + ActiveSupport::Deprecation.warn(<<-MSG.squish) + Passing a string to ActiveRecord::Base.establish_connection for a + configuration lookup is deprecated, please pass a symbol + (#{spec.to_sym.inspect}) instead. + MSG + resolve_symbol_connection(spec) else resolve_url_connection(spec) end end - # Takes the environment such as `:production` or `:development`. + # Takes the environment such as +:production+ or +:development+. # This requires that the @configurations was initialized with a key that # matches. # diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb index 38bdddefba..d19bd80576 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb @@ -66,7 +66,9 @@ module ActiveRecord exception.error_number if exception.respond_to?(:error_number) end + #-- # QUOTING ================================================== + #++ def quote_string(string) @connection.escape(string) @@ -80,7 +82,9 @@ module ActiveRecord end end + #-- # CONNECTION MANAGEMENT ==================================== + #++ def active? return false unless @connection @@ -104,7 +108,9 @@ module ActiveRecord end end + #-- # DATABASE STATEMENTS ====================================== + #++ def explain(arel, binds = []) sql = "EXPLAIN #{to_sql(arel, binds.dup)}" @@ -232,11 +238,6 @@ module ActiveRecord alias exec_without_stmt exec_query - # Returns an ActiveRecord::Result instance. - def select(sql, name = nil, binds = []) - exec_query(sql, name) - end - def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil) super id_value || @connection.last_id diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index da3aecf69a..53ad71b445 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -58,7 +58,7 @@ module ActiveRecord # * <tt>:encoding</tt> - (Optional) Sets the client encoding by executing "SET NAMES <encoding>" after connection. # * <tt>:reconnect</tt> - Defaults to false (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html). # * <tt>:strict</tt> - Defaults to true. Enable STRICT_ALL_TABLES. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html) - # * <tt>:variables</tt> - (Optional) A hash session variables to send as `SET @@SESSION.key = value` on each database connection. Use the value `:default` to set a variable to its DEFAULT value. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/set-statement.html). + # * <tt>:variables</tt> - (Optional) A hash session variables to send as <tt>SET @@SESSION.key = value</tt> on each database connection. Use the value +:default+ to set a variable to its DEFAULT value. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/set-statement.html). # * <tt>:sslca</tt> - Necessary to use MySQL with an SSL connection. # * <tt>:sslkey</tt> - Necessary to use MySQL with an SSL connection. # * <tt>:sslcert</tt> - Necessary to use MySQL with an SSL connection. @@ -88,7 +88,7 @@ module ActiveRecord end def clear - cache.values.each do |hash| + cache.each_value do |hash| hash[:stmt].close end cache.clear @@ -137,7 +137,9 @@ module ActiveRecord @connection.quote(string) end + #-- # CONNECTION MANAGEMENT ==================================== + #++ def active? if @connection.respond_to?(:stat) @@ -178,7 +180,9 @@ module ActiveRecord end end + #-- # DATABASE STATEMENTS ====================================== + #++ def select_rows(sql, name = nil, binds = []) @connection.query_with_result = true @@ -465,7 +469,7 @@ module ActiveRecord def select(sql, name = nil, binds = []) @connection.query_with_result = true - rows = exec_query(sql, name, binds) + rows = super @connection.more_results && @connection.next_result # invoking stored procedures with CLIENT_MULTI_RESULTS requires this to tidy up else connection will be dropped rows end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb index 89a7257d77..d09468329a 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/database_statements.rb @@ -156,10 +156,6 @@ module ActiveRecord end end - def substitute_at(column, index) - Arel::Nodes::BindParam.new "$#{index + 1}" - end - def exec_query(sql, name = 'SQL', binds = []) execute_and_clear(sql, name, binds) do |result| types = {} diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/cidr.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/cidr.rb index a53b4ee8e2..222f10fa8f 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/cidr.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/cidr.rb @@ -12,15 +12,15 @@ module ActiveRecord # If the subnet mask is equal to /32, don't output it if subnet_mask == (2**32 - 1) - "\"#{value.to_s}\"" + "\"#{value}\"" else - "\"#{value.to_s}/#{subnet_mask.to_s(2).count('1')}\"" + "\"#{value}/#{subnet_mask.to_s(2).count('1')}\"" end end def type_cast_for_database(value) if IPAddr === value - "#{value.to_s}/#{value.instance_variable_get(:@mask_addr).to_s(2).count('1')}" + "#{value}/#{value.instance_variable_get(:@mask_addr).to_s(2).count('1')}" else value 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 84b9490ba3..961e6224c4 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/string/filters' + module ActiveRecord module ConnectionAdapters module PostgreSQL @@ -25,10 +27,11 @@ module ActiveRecord if !infinity?(from) && extracted[:exclude_start] if from.respond_to?(:succ) from = from.succ - ActiveSupport::Deprecation.warn \ - "Excluding the beginning of a Range is only partialy supported " \ - "through `#succ`. This is not reliable and will be removed in " \ - "the future." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + Excluding the beginning of a Range is only partialy supported + through `#succ`. This is not reliable and will be removed in + the future. + MSG else raise ArgumentError, "The Ruby Range object does not support excluding the beginning of a Range. (unsupported value: '#{value}')" end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb index e396ff4a1e..35e699eeda 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb @@ -4,7 +4,7 @@ module ActiveRecord module OID # :nodoc: # This class uses the data from PostgreSQL pg_type table to build # the OID -> Type mapping. - # - OID is and integer representing the type. + # - OID is an integer representing the type. # - Type is an OID::Type object. # This class has side effects on the +store+ passed during initialization. class TypeMapInitializer # :nodoc: diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb index cf5c8d288e..991c41327f 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb @@ -14,22 +14,6 @@ module ActiveRecord @connection.unescape_bytea(value) if value end - # Quotes PostgreSQL-specific data types for SQL input. - def quote(value, column = nil) #:nodoc: - return super unless column - - case value - when Float - if value.infinite? || value.nan? - "'#{value.to_s}'" - else - super - end - else - super - end - end - # Quotes strings for use in SQL input. def quote_string(s) #:nodoc: @connection.escape(s) @@ -94,6 +78,12 @@ module ActiveRecord elsif value.hex? "X'#{value}'" end + when Float + if value.infinite? || value.nan? + "'#{value}'" + else + super + end else super end 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 799aafbd99..193c950261 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -293,6 +293,23 @@ module ActiveRecord result.rows.first.first end + # Sets the sequence of a table's primary key to the specified value. + def set_pk_sequence!(table, value) #:nodoc: + pk, sequence = pk_and_sequence_for(table) + + if pk + if sequence + quoted_sequence = quote_table_name(sequence) + + select_value <<-end_sql, 'SCHEMA' + SELECT setval('#{quoted_sequence}', #{value}) + end_sql + else + @logger.warn "#{table} has primary key #{pk} with no default sequence" if @logger + end + end + end + # Resets the sequence of a table's primary key to the maximum value. def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc: unless pk and sequence @@ -394,7 +411,10 @@ module ActiveRecord pk, seq = pk_and_sequence_for(new_name) if seq && seq.identifier == "#{table_name}_#{pk}_seq" new_seq = "#{new_name}_#{pk}_seq" + idx = "#{table_name}_pkey" + new_idx = "#{new_name}_pkey" execute "ALTER TABLE #{quote_table_name(seq)} RENAME TO #{quote_table_name(new_seq)}" + execute "ALTER INDEX #{quote_table_name(idx)} RENAME TO #{quote_table_name(new_idx)}" end rename_table_indexes(table_name, new_name) @@ -413,7 +433,12 @@ module ActiveRecord quoted_table_name = quote_table_name(table_name) sql_type = type_to_sql(type, options[:limit], options[:precision], options[:scale]) sql_type << "[]" if options[:array] - execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{sql_type}" + sql = "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{sql_type}" + sql << " USING #{options[:using]}" if options[:using] + if options[:cast_as] + sql << " USING CAST(#{quote_column_name(column_name)} AS #{type_to_sql(options[:cast_as], options[:limit], options[:precision], options[:scale])})" + end + execute sql change_column_default(table_name, column_name, options[:default]) if options_include_default?(options) change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null) @@ -461,6 +486,9 @@ module ActiveRecord end def rename_index(table_name, old_name, new_name) + if new_name.length > allowed_index_name_length + raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters" + end execute "ALTER INDEX #{quote_column_name(old_name)} RENAME TO #{quote_table_name(new_name)}" end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb b/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb index 0290bcb48c..9a0b80d7d3 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/utils.rb @@ -18,7 +18,11 @@ module ActiveRecord end def quoted - parts.map { |p| PGconn.quote_ident(p) }.join SEPARATOR + if schema + PGconn.quote_ident(schema) << SEPARATOR << PGconn.quote_ident(identifier) + else + PGconn.quote_ident(identifier) + end end def ==(o) @@ -32,8 +36,11 @@ module ActiveRecord protected def unquote(part) - return unless part - part.gsub(/(^"|"$)/,'') + if part && part.start_with?('"') + part[1..-2] + else + part + end end def parts @@ -57,7 +64,11 @@ module ActiveRecord # * <tt>"schema_name".table_name</tt> # * <tt>"schema.name"."table name"</tt> def extract_schema_qualified_name(string) - table, schema = string.scan(/[^".\s]+|"[^"]*"/)[0..1].reverse + schema, table = string.scan(/[^".\s]+|"[^"]*"/) + if table.nil? + table = schema + schema = nil + end PostgreSQL::Name.new(schema, table) end end diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 0d74cb6707..3698957d8d 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -13,7 +13,7 @@ require 'active_record/connection_adapters/postgresql/database_statements' require 'arel/visitors/bind_visitor' # Make sure we're using pg high enough for PGResult#values -gem 'pg', '~> 0.11' +gem 'pg', '~> 0.15' require 'pg' require 'ipaddr' @@ -78,6 +78,7 @@ module ActiveRecord NATIVE_DATABASE_TYPES = { primary_key: "serial primary key", + bigserial: "bigserial", string: { name: "character varying" }, text: { name: "text" }, integer: { name: "integer" }, @@ -94,6 +95,7 @@ module ActiveRecord int8range: { name: "int8range" }, binary: { name: "bytea" }, boolean: { name: "boolean" }, + bigint: { name: "bigint" }, xml: { name: "xml" }, tsvector: { name: "tsvector" }, hstore: { name: "hstore" }, @@ -102,6 +104,7 @@ module ActiveRecord macaddr: { name: "macaddr" }, uuid: { name: "uuid" }, json: { name: "json" }, + jsonb: { name: "jsonb" }, ltree: { name: "ltree" }, citext: { name: "citext" }, point: { name: "point" }, @@ -122,7 +125,7 @@ module ActiveRecord PostgreSQL::SchemaCreation.new self end - # Adds `:array` option to the default set provided by the + # Adds +:array+ option to the default set provided by the # AbstractAdapter def prepare_column_options(column, types) # :nodoc: spec = super @@ -131,7 +134,7 @@ module ActiveRecord spec end - # Adds `:array` as a valid migration key + # Adds +:array+ as a valid migration key def migration_keys super + [:array] end @@ -391,6 +394,16 @@ module ActiveRecord super(oid) end + def column_name_for_operation(operation, node) # :nodoc: + OPERATION_ALIASES.fetch(operation) { operation.downcase } + end + + OPERATION_ALIASES = { # :nodoc: + "maximum" => "max", + "minimum" => "min", + "average" => "avg", + } + protected # Returns the version of the connected PostgreSQL server. @@ -583,9 +596,7 @@ module ActiveRecord } log(sql, name, type_casted_binds, stmt_key) do - @connection.send_query_prepared(stmt_key, type_casted_binds.map { |_, val| val }) - @connection.block - @connection.get_last_result + @connection.exec_prepared(stmt_key, type_casted_binds.map { |_, val| val }) end rescue ActiveRecord::StatementInvalid => e pgerror = e.original_exception @@ -677,9 +688,9 @@ module ActiveRecord variables.map do |k, v| if v == ':default' || v == :default # Sets the value to the global or compile default - execute("SET SESSION #{k.to_s} TO DEFAULT", 'SCHEMA') + execute("SET SESSION #{k} TO DEFAULT", 'SCHEMA') elsif !v.nil? - execute("SET SESSION #{k.to_s} TO #{quote(v)}", 'SCHEMA') + execute("SET SESSION #{k} TO #{quote(v)}", 'SCHEMA') end end end @@ -697,12 +708,6 @@ module ActiveRecord exec_query("SELECT currval('#{sequence_name}')", 'SQL') end - # Executes a SELECT query and returns the results, performing any data type - # conversions that are required to be performed here instead of in PostgreSQLColumn. - def select(sql, name = nil, binds = []) - exec_query(sql, name, binds) - end - # Returns the list of a table's column names, data types, and default values. # # The underlying query is roughly: diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb index ebb311df57..0b8b6a2bf8 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb @@ -115,7 +115,7 @@ module ActiveRecord end def clear - cache.values.each do |hash| + cache.each_value do |hash| dealloc hash[:stmt] end cache.clear @@ -179,10 +179,6 @@ module ActiveRecord true end - def supports_add_column? - true - end - def supports_views? true end @@ -270,7 +266,9 @@ module ActiveRecord end end + #-- # DATABASE STATEMENTS ====================================== + #++ def explain(arel, binds = []) sql = "EXPLAIN QUERY PLAN #{to_sql(arel, binds)}" @@ -451,12 +449,12 @@ module ActiveRecord # See: http://www.sqlite.org/lang_altertable.html # SQLite has an additional restriction on the ALTER TABLE statement - def valid_alter_table_options( type, options) + def valid_alter_table_type?(type) type.to_sym != :primary_key end def add_column(table_name, column_name, type, options = {}) #:nodoc: - if supports_add_column? && valid_alter_table_options( type, options ) + if valid_alter_table_type?(type) super(table_name, column_name, type, options) else alter_table(table_name) do |definition| @@ -514,10 +512,6 @@ module ActiveRecord register_class_with_limit m, %r(char)i, SQLite3String end - def select(sql, name = nil, binds = []) #:nodoc: - exec_query(sql, name, binds) - end - def table_structure(table_name) structure = exec_query("PRAGMA table_info(#{quote_table_name(table_name)})", 'SCHEMA').to_hash raise(ActiveRecord::StatementInvalid, "Could not find table '#{table_name}'") if structure.empty? diff --git a/activerecord/lib/active_record/connection_handling.rb b/activerecord/lib/active_record/connection_handling.rb index 31e7390bf7..8f51590c99 100644 --- a/activerecord/lib/active_record/connection_handling.rb +++ b/activerecord/lib/active_record/connection_handling.rb @@ -1,6 +1,6 @@ module ActiveRecord module ConnectionHandling - RAILS_ENV = -> { Rails.env if defined?(Rails) } + RAILS_ENV = -> { (Rails.env if defined?(Rails)) || ENV["RAILS_ENV"] || ENV["RACK_ENV"] } DEFAULT_ENV = -> { RAILS_ENV.call || "default_env" } # Establishes the connection to the database. Accepts a hash as input where diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index 5571a2d297..89d8932e9e 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -1,6 +1,7 @@ +require 'thread' require 'active_support/core_ext/hash/indifferent_access' require 'active_support/core_ext/object/duplicable' -require 'thread' +require 'active_support/core_ext/string/filters' module ActiveRecord module Core @@ -88,8 +89,10 @@ module ActiveRecord mattr_accessor :maintain_test_schema, instance_accessor: false def self.disable_implicit_join_references=(value) - ActiveSupport::Deprecation.warn("Implicit join references were removed with Rails 4.1." \ - "Make sure to remove this configuration because it does nothing.") + ActiveSupport::Deprecation.warn(<<-MSG.squish) + Implicit join references were removed with Rails 4.1. + Make sure to remove this configuration because it does nothing. + MSG end class_attribute :default_connection_handler, instance_writer: false @@ -135,8 +138,10 @@ module ActiveRecord id = ids.first if ActiveRecord::Base === id id = id.id - ActiveSupport::Deprecation.warn "You are passing an instance of ActiveRecord::Base to `find`." \ - "Please pass the id of the object by calling `.id`" + ActiveSupport::Deprecation.warn(<<-MSG.squish) + You are passing an instance of ActiveRecord::Base to `find`. + Please pass the id of the object by calling `.id` + MSG end key = primary_key @@ -150,6 +155,8 @@ module ActiveRecord raise RecordNotFound, "Couldn't find #{name} with '#{primary_key}'=#{id}" end record + rescue RangeError + raise RecordNotFound, "Couldn't find #{name} with an out of range value for '#{primary_key}'" end def find_by(*args) @@ -180,6 +187,8 @@ module ActiveRecord s.execute(hash.values, self, connection).first rescue TypeError => e raise ActiveRecord::StatementInvalid.new(e.message, e) + rescue RangeError + nil end end @@ -261,7 +270,7 @@ module ActiveRecord # # Instantiates a single new object # User.new(first_name: 'Jamie') def initialize(attributes = nil, options = {}) - @attributes = self.class.default_attributes.dup + @attributes = self.class._default_attributes.dup init_internals initialize_internals_callback @@ -272,7 +281,7 @@ module ActiveRecord init_attributes(attributes, options) if attributes yield self if block_given? - run_initialize_callbacks + _run_initialize_callbacks end # Initialize an empty model object from +coder+. +coder+ must contain @@ -294,8 +303,8 @@ module ActiveRecord self.class.define_attribute_methods - run_find_callbacks - run_initialize_callbacks + _run_find_callbacks + _run_initialize_callbacks self end @@ -331,7 +340,7 @@ module ActiveRecord @attributes = @attributes.dup @attributes.reset(self.class.primary_key) - run_initialize_callbacks + _run_initialize_callbacks @aggregation_cache = {} @association_cache = {} @@ -527,8 +536,6 @@ module ActiveRecord end def init_internals - @attributes.ensure_initialized(self.class.primary_key) - @aggregation_cache = {} @association_cache = {} @readonly = false diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb index 5958373e88..f053372cfb 100644 --- a/activerecord/lib/active_record/enum.rb +++ b/activerecord/lib/active_record/enum.rb @@ -142,7 +142,7 @@ module ActiveRecord private def save_changed_attribute(attr_name, old) if (mapping = self.class.defined_enums[attr_name.to_s]) - value = read_attribute(attr_name) + value = _read_attribute(attr_name) if attribute_changed?(attr_name) if mapping[old] == value clear_attribute_changes([attr_name]) diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb index 52c70977ef..14819aab54 100644 --- a/activerecord/lib/active_record/errors.rb +++ b/activerecord/lib/active_record/errors.rb @@ -52,10 +52,29 @@ module ActiveRecord # Raised by ActiveRecord::Base.save! and ActiveRecord::Base.create! methods when record cannot be # saved because record is invalid. class RecordNotSaved < ActiveRecordError + attr_reader :record + + def initialize(record) + @record = record + super() + end end # Raised by ActiveRecord::Base.destroy! when a call to destroy would return false. + # + # begin + # complex_operation_that_internally_calls_destroy! + # rescue ActiveRecord::RecordNotDestroyed => invalid + # puts invalid.record.errors + # end + # class RecordNotDestroyed < ActiveRecordError + attr_reader :record + + def initialize(record) + @record = record + super() + end end # Superclass for all database execution errors. @@ -167,7 +186,7 @@ module ActiveRecord def initialize(record, attribute) @record = record @attribute = attribute.to_s - super("unknown attribute: #{attribute}") + super("unknown attribute '#{attribute}' for #{@record.class}.") end end @@ -177,6 +196,7 @@ module ActiveRecord # offending attribute. class AttributeAssignmentError < ActiveRecordError attr_reader :exception, :attribute + def initialize(message, exception, attribute) super(message) @exception = exception @@ -189,6 +209,7 @@ module ActiveRecord # objects, each corresponding to the error while assigning to an attribute. class MultiparameterAssignmentErrors < ActiveRecordError attr_reader :errors + def initialize(errors) @errors = errors end diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 44cc1a079f..7c53ee0a9a 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -649,7 +649,7 @@ module ActiveRecord model_class end - reflection_class._reflections.values.each do |association| + reflection_class._reflections.each_value do |association| case association.macro when :belongs_to # Do not replace association name with association foreign key if they are named the same @@ -806,7 +806,9 @@ module ActiveRecord def find if model_class - model_class.find(fixture[model_class.primary_key]) + model_class.unscoped do + model_class.find(fixture[model_class.primary_key]) + end else raise FixtureClassNotFound, "No class attached to find." end @@ -870,34 +872,9 @@ module ActiveRecord end self.fixture_table_names |= fixture_set_names - require_fixture_classes(fixture_set_names, self.config) setup_fixture_accessors(fixture_set_names) end - def try_to_load_dependency(file_name) - require_dependency file_name - rescue LoadError => e - unless fixture_class_names.key?(file_name.pluralize) - if ActiveRecord::Base.logger - ActiveRecord::Base.logger.warn("Unable to load #{file_name}, make sure you added it to ActiveSupport::TestCase.set_fixture_class") - ActiveRecord::Base.logger.warn("underlying cause #{e.message} \n\n #{e.backtrace.join("\n")}") - end - end - end - - def require_fixture_classes(fixture_set_names = nil, config = ActiveRecord::Base) - if fixture_set_names - fixture_set_names = fixture_set_names.map { |n| n.to_s } - else - fixture_set_names = fixture_table_names - end - - fixture_set_names.each do |file_name| - file_name = file_name.singularize if config.pluralize_table_names - try_to_load_dependency(file_name) - end - end - def setup_fixture_accessors(fixture_set_names = nil) fixture_set_names = Array(fixture_set_names || fixture_table_names) methods = Module.new do @@ -974,7 +951,7 @@ module ActiveRecord end # Instantiate fixtures for every test if requested. - instantiate_fixtures(config) if use_instantiated_fixtures + instantiate_fixtures if use_instantiated_fixtures end def teardown_fixtures @@ -1001,16 +978,9 @@ module ActiveRecord Hash[fixtures.map { |f| [f.name, f] }] end - # for pre_loaded_fixtures, only require the classes once. huge speed improvement - @@required_fixture_classes = false - - def instantiate_fixtures(config) + def instantiate_fixtures if pre_loaded_fixtures raise RuntimeError, 'Load fixtures before instantiating them.' if ActiveRecord::FixtureSet.all_loaded_fixtures.empty? - unless @@required_fixture_classes - self.class.require_fixture_classes ActiveRecord::FixtureSet.all_loaded_fixtures.keys, config - @@required_fixture_classes = true - end ActiveRecord::FixtureSet.instantiate_all_loaded_fixtures(self, load_instances?) else raise RuntimeError, 'Load fixtures before instantiating them.' if @loaded_fixtures.nil? diff --git a/activerecord/lib/active_record/gem_version.rb b/activerecord/lib/active_record/gem_version.rb index 91747d2ccf..e820835626 100644 --- a/activerecord/lib/active_record/gem_version.rb +++ b/activerecord/lib/active_record/gem_version.rb @@ -8,7 +8,7 @@ module ActiveRecord MAJOR = 4 MINOR = 2 TINY = 0 - PRE = "beta2" + PRE = "beta4" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb index 251d682a02..f58145ab05 100644 --- a/activerecord/lib/active_record/inheritance.rb +++ b/activerecord/lib/active_record/inheritance.rb @@ -80,12 +80,12 @@ module ActiveRecord end def symbolized_base_class - ActiveSupport::Deprecation.warn("ActiveRecord::Base.symbolized_base_class is deprecated and will be removed without replacement.") + ActiveSupport::Deprecation.warn('`ActiveRecord::Base.symbolized_base_class` is deprecated and will be removed without replacement.') @symbolized_base_class ||= base_class.to_s.to_sym end def symbolized_sti_name - ActiveSupport::Deprecation.warn("ActiveRecord::Base.symbolized_sti_name is deprecated and will be removed without replacement.") + ActiveSupport::Deprecation.warn('`ActiveRecord::Base.symbolized_sti_name` is deprecated and will be removed without replacement.') @symbolized_sti_name ||= sti_name.present? ? sti_name.to_sym : symbolized_base_class end diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb index 52eeb8ae1f..ced694ba9a 100644 --- a/activerecord/lib/active_record/locking/optimistic.rb +++ b/activerecord/lib/active_record/locking/optimistic.rb @@ -120,7 +120,7 @@ module ActiveRecord if locking_enabled? column_name = self.class.locking_column column = self.class.columns_hash[column_name] - substitute = self.class.connection.substitute_at(column, relation.bind_values.length) + substitute = self.class.connection.substitute_at(column) relation = relation.where(self.class.arel_table[column_name].eq(substitute)) relation.bind_values << [column, self[column_name].to_i] diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index d0d9304a36..92f2951f2d 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -184,8 +184,8 @@ module ActiveRecord # you wish to downgrade. Alternatively, you can also use the STEP option if you # wish to rollback last few migrations. <tt>rake db:migrate STEP=2</tt> will rollback # the latest two migrations. - # - # If any of the migrations throw an <tt>ActiveRecord::IrreversibleMigration</tt> exception, + # + # If any of the migrations throw an <tt>ActiveRecord::IrreversibleMigration</tt> exception, # that step will fail and you'll have some manual work to do. # # == Database support @@ -394,8 +394,15 @@ module ActiveRecord end def load_schema_if_pending! - if ActiveRecord::Migrator.needs_migration? - ActiveRecord::Tasks::DatabaseTasks.load_schema_current + if ActiveRecord::Migrator.needs_migration? || !ActiveRecord::Migrator.any_migrations? + # Roundrip to Rake to allow plugins to hook into database initialization. + FileUtils.cd Rails.root do + current_config = Base.connection_config + Base.clear_all_connections! + system("bin/rake db:test:prepare") + # Establish a new connection, the old database may be gone (db:test:prepare uses purge) + Base.establish_connection(current_config) + end check_pending! end end @@ -848,6 +855,10 @@ module ActiveRecord (migrations(migrations_paths).collect(&:version) - get_all_versions(connection)).size > 0 end + def any_migrations? + migrations(migrations_paths).any? + end + def last_version last_migration.version end diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb index 48e82d28d9..adad7774b9 100644 --- a/activerecord/lib/active_record/model_schema.rb +++ b/activerecord/lib/active_record/model_schema.rb @@ -231,7 +231,7 @@ module ActiveRecord end def attributes_builder # :nodoc: - @attributes_builder ||= AttributeSet::Builder.new(column_types) + @attributes_builder ||= AttributeSet::Builder.new(column_types, primary_key) end def column_types # :nodoc: @@ -247,12 +247,12 @@ module ActiveRecord # Returns a hash where the keys are column names and the values are # default values when instantiating the AR object for this table. def column_defaults - default_attributes.to_hash + _default_attributes.to_hash end - def default_attributes # :nodoc: + def _default_attributes # :nodoc: @default_attributes ||= attributes_builder.build_from_database( - columns_hash.transform_values(&:default)) + raw_default_values) end # Returns an array of column names as strings. @@ -331,6 +331,10 @@ module ActiveRecord base.table_name end end + + def raw_default_values + columns_hash.transform_values(&:default) + end end end end diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index 755ff2b2f1..8d84a3acae 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -139,7 +139,7 @@ module ActiveRecord # Attributes marked as readonly are silently ignored if the record is # being updated. def save!(*) - create_or_update || raise(RecordNotSaved) + create_or_update || raise(RecordNotSaved, self) end # Deletes the record in the database and freezes this instance to @@ -166,7 +166,7 @@ module ActiveRecord # and <tt>destroy</tt> returns +false+. See # ActiveRecord::Callbacks for further details. def destroy - raise ReadOnlyRecord if readonly? + raise ReadOnlyRecord, "#{self.class} is marked as readonly" if readonly? destroy_associations destroy_row if persisted? @destroyed = true @@ -181,7 +181,7 @@ module ActiveRecord # and <tt>destroy!</tt> raises ActiveRecord::RecordNotDestroyed. See # ActiveRecord::Callbacks for further details. def destroy! - destroy || raise(ActiveRecord::RecordNotDestroyed) + destroy || raise(ActiveRecord::RecordNotDestroyed, self) end # Returns an instance of the specified +klass+ with the attributes of the @@ -487,7 +487,7 @@ module ActiveRecord def relation_for_destroy pk = self.class.primary_key column = self.class.columns_hash[pk] - substitute = self.class.connection.substitute_at(column, 0) + substitute = self.class.connection.substitute_at(column) relation = self.class.unscoped.where( self.class.arel_table[pk].eq(substitute)) @@ -497,7 +497,7 @@ module ActiveRecord end def create_or_update - raise ReadOnlyRecord if readonly? + raise ReadOnlyRecord, "#{self.class} is marked as readonly" if readonly? result = new_record? ? _create_record : _update_record result != false end diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb index 45b6b1c925..e8de4db3a7 100644 --- a/activerecord/lib/active_record/querying.rb +++ b/activerecord/lib/active_record/querying.rb @@ -39,7 +39,16 @@ module ActiveRecord result_set = connection.select_all(sanitize_sql(sql), "#{name} Load", binds) column_types = result_set.column_types.dup columns_hash.each_key { |k| column_types.delete k } - result_set.map { |record| instantiate(record, column_types) } + message_bus = ActiveSupport::Notifications.instrumenter + + payload = { + record_count: result_set.length, + class_name: name + } + + message_bus.instrument('instantiation.active_record', payload) do + result_set.map { |record| instantiate(record, column_types) } + end end # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part. diff --git a/activerecord/lib/active_record/railtie.rb b/activerecord/lib/active_record/railtie.rb index a4ceacbf44..f1bdbc845c 100644 --- a/activerecord/lib/active_record/railtie.rb +++ b/activerecord/lib/active_record/railtie.rb @@ -36,8 +36,6 @@ module ActiveRecord config.eager_load_namespaces << ActiveRecord rake_tasks do - require "active_record/base" - namespace :db do task :load_config do ActiveRecord::Tasks::DatabaseTasks.database_configuration = Rails.application.config.database_configuration diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index 44765bd050..21b1c3f721 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -196,7 +196,8 @@ db_namespace = namespace :db do fixture_files = if ENV['FIXTURES'] ENV['FIXTURES'].split(',') else - Pathname.glob("#{fixtures_dir}/**/*.yml").map {|f| f.basename.sub_ext('').to_s } + # The use of String#[] here is to support namespaced fixtures + Dir["#{fixtures_dir}/**/*.yml"].map {|f| f[(fixtures_dir.size + 1)..-5] } end ActiveRecord::FixtureSet.create_fixtures(fixtures_dir, fixture_files) @@ -304,7 +305,7 @@ db_namespace = namespace :db do end # desc "Recreate the test database from the current schema" - task :load => %w(db:test:deprecated db:test:purge) do + task :load => %w(db:test:purge) do case ActiveRecord::Base.schema_format when :ruby db_namespace["test:load_schema"].invoke @@ -314,7 +315,7 @@ db_namespace = namespace :db do end # desc "Recreate the test database from an existent schema.rb file" - task :load_schema => %w(db:test:deprecated db:test:purge) do + task :load_schema => %w(db:test:purge) do begin should_reconnect = ActiveRecord::Base.connection_pool.active_connection? ActiveRecord::Schema.verbose = false @@ -327,7 +328,7 @@ db_namespace = namespace :db do end # desc "Recreate the test database from an existent structure.sql file" - task :load_structure => %w(db:test:deprecated db:test:purge) do + task :load_structure => %w(db:test:purge) do ActiveRecord::Tasks::DatabaseTasks.load_schema_for ActiveRecord::Base.configurations['test'], :sql, ENV['SCHEMA'] end @@ -348,12 +349,12 @@ db_namespace = namespace :db do task :clone_structure => %w(db:test:deprecated db:structure:dump db:test:load_structure) # desc "Empty the test database" - task :purge => %w(db:test:deprecated environment load_config) do + task :purge => %w(environment load_config) do ActiveRecord::Tasks::DatabaseTasks.purge ActiveRecord::Base.configurations['test'] end # desc 'Check for pending migrations and load the test schema' - task :prepare => %w(db:test:deprecated environment load_config) do + task :prepare => %w(environment load_config) do unless ActiveRecord::Base.configurations.blank? db_namespace['test:load'].invoke end diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb index 6b5a592ee5..4219632596 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -1,4 +1,5 @@ require 'thread' +require 'active_support/core_ext/string/filters' module ActiveRecord # = Active Record Reflection @@ -62,7 +63,7 @@ module ActiveRecord # Returns a Hash of name of the reflection as the key and a AssociationReflection as the value. # - # Account.reflections # => {balance: AggregateReflection} + # Account.reflections # => {"balance" => AggregateReflection} # # @api public def reflections @@ -153,8 +154,11 @@ module ActiveRecord end def source_macro - ActiveSupport::Deprecation.warn("ActiveRecord::Base.source_macro is deprecated and " \ - "will be removed without replacement.") + ActiveSupport::Deprecation.warn(<<-MSG.squish) + ActiveRecord::Base.source_macro is deprecated and will be removed + without replacement. + MSG + macro end end @@ -283,7 +287,7 @@ module ActiveRecord def association_scope_cache(conn, owner) key = conn.prepared_statements if polymorphic? - key = [key, owner.read_attribute(@foreign_type)] + key = [key, owner._read_attribute(@foreign_type)] end @association_scope_cache[key] ||= @scope_lock.synchronize { @association_scope_cache[key] ||= yield @@ -339,13 +343,14 @@ module ActiveRecord return unless scope if scope.arity > 0 - ActiveSupport::Deprecation.warn \ - "The association scope '#{name}' is instance dependent (the scope " \ - "block takes an argument). Preloading happens before the individual " \ - "instances are created. This means that there is no instance being " \ - "passed to the association scope. This will most likely result in " \ - "broken or incorrect behavior. Joining, Preloading and eager loading " \ - "of these associations is deprecated and will be removed in the future." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + The association scope '#{name}' is instance dependent (the scope + block takes an argument). Preloading happens before the individual + instances are created. This means that there is no instance being + passed to the association scope. This will most likely result in + broken or incorrect behavior. Joining, Preloading and eager loading + of these associations is deprecated and will be removed in the future. + MSG end end alias :check_eager_loadable! :check_preloadable! @@ -746,8 +751,11 @@ module ActiveRecord # The macro used by the source association def source_macro - ActiveSupport::Deprecation.warn("ActiveRecord::Base.source_macro is deprecated and " \ - "will be removed without replacement.") + ActiveSupport::Deprecation.warn(<<-MSG.squish) + ActiveRecord::Base.source_macro is deprecated and will be removed + without replacement. + MSG + source_reflection.source_macro end @@ -821,7 +829,11 @@ module ActiveRecord end if through_reflection.polymorphic? - raise HasManyThroughAssociationPolymorphicThroughError.new(active_record.name, self) + if has_one? + raise HasOneAssociationPolymorphicThroughError.new(active_record.name, self) + else + raise HasManyThroughAssociationPolymorphicThroughError.new(active_record.name, self) + end end if source_reflection.nil? diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index ad54d84665..561ed222d1 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -4,8 +4,6 @@ require 'arel/collectors/bind' module ActiveRecord # = Active Record Relation class Relation - JoinOperation = Struct.new(:relation, :join_class, :on) - MULTI_VALUE_METHODS = [:includes, :eager_load, :preload, :select, :group, :order, :joins, :where, :having, :bind, :references, :extending, :unscope] @@ -81,22 +79,26 @@ module ActiveRecord scope.unscope!(where: @klass.inheritance_column) end - um = scope.where(@klass.arel_table[@klass.primary_key].eq(id_was || id)).arel.compile_update(substitutes, @klass.primary_key) + relation = scope.where(@klass.primary_key => (id_was || id)) + bvs = binds + relation.bind_values + um = relation + .arel + .compile_update(substitutes, @klass.primary_key) @klass.connection.update( um, 'SQL', - binds) + bvs, + ) end def substitute_values(values) # :nodoc: - substitutes = values.sort_by { |arel_attr,_| arel_attr.name } - binds = substitutes.map do |arel_attr, value| + binds = values.map do |arel_attr, value| [@klass.columns_hash[arel_attr.name], value] end - substitutes.each_with_index do |tuple, i| - tuple[1] = @klass.connection.substitute_at(binds[i][0], i) + substitutes = values.each_with_index.map do |(arel_attr, _), i| + [arel_attr, @klass.connection.substitute_at(binds[i][0])] end [substitutes, binds] @@ -302,10 +304,11 @@ module ActiveRecord klass.current_scope = previous end - # Updates all records with details given if they match a set of conditions supplied, limits and order can - # also be supplied. This method constructs a single SQL UPDATE statement and sends it straight to the - # database. It does not instantiate the involved models and it does not trigger Active Record callbacks - # or validations. + # Updates all records in the current relation with details given. This method constructs a single SQL UPDATE + # statement and sends it straight to the database. It does not instantiate the involved models and it does not + # trigger Active Record callbacks or validations. Values passed to `update_all` will not go through + # ActiveRecord's type-casting behavior. It should receive only values that can be passed as-is to the SQL + # database. # # ==== Parameters # @@ -338,7 +341,7 @@ module ActiveRecord stmt.wheres = arel.constraints end - bvs = bind_values + arel.bind_values + bvs = arel.bind_values + bind_values @klass.connection.update stmt, 'SQL', bvs end @@ -636,7 +639,7 @@ module ActiveRecord preload = preload_values preload += includes_values unless eager_loading? - preloader = ActiveRecord::Associations::Preloader.new + preloader = build_preloader preload.each do |associations| preloader.preload @records, associations end @@ -647,6 +650,10 @@ module ActiveRecord @records end + def build_preloader + ActiveRecord::Associations::Preloader.new + end + def references_eager_loaded_tables? joined_tables = arel.join_sources.map do |join| if join.is_a?(Arel::Nodes::StringJoin) diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index eaaa409636..c8ebb41131 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -254,6 +254,7 @@ module ActiveRecord select_value = operation_over_aggregate_column(column, operation, distinct) column_alias = select_value.alias + column_alias ||= @klass.connection.column_name_for_operation(operation, select_value) relation.select_values = [select_value] query_builder = relation.arel diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index ed56369f86..eacae73ebb 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -1,4 +1,5 @@ require 'active_support/deprecation' +require 'active_support/core_ext/string/filters' module ActiveRecord module FinderMethods @@ -81,12 +82,16 @@ module ActiveRecord # Post.find_by "published_at < ?", 2.weeks.ago def find_by(*args) where(*args).take + rescue RangeError + nil end # Like <tt>find_by</tt>, except that if no record is found, raises # an <tt>ActiveRecord::RecordNotFound</tt> error. def find_by!(*args) where(*args).take! + rescue RangeError + raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range value" end # Gives a record (or N records if a parameter is supplied) without any implied @@ -138,7 +143,7 @@ module ActiveRecord # Same as +first+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record # is found. Note that <tt>first!</tt> accepts no arguments. def first! - first or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]") + find_nth! 0 end # Find the last record (or last N records if a parameter is supplied). @@ -187,7 +192,7 @@ module ActiveRecord # Same as +second+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record # is found. def second! - second or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]") + find_nth! 1 end # Find the third record. @@ -203,7 +208,7 @@ module ActiveRecord # Same as +third+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record # is found. def third! - third or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]") + find_nth! 2 end # Find the fourth record. @@ -219,7 +224,7 @@ module ActiveRecord # Same as +fourth+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record # is found. def fourth! - fourth or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]") + find_nth! 3 end # Find the fifth record. @@ -235,7 +240,7 @@ module ActiveRecord # Same as +fifth+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record # is found. def fifth! - fifth or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]") + find_nth! 4 end # Find the forty-second record. Also known as accessing "the reddit". @@ -251,7 +256,7 @@ module ActiveRecord # Same as +forty_two+ but raises <tt>ActiveRecord::RecordNotFound</tt> if no record # is found. def forty_two! - forty_two or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]") + find_nth! 41 end # Returns +true+ if a record exists in the table that matches the +id+ or @@ -284,8 +289,10 @@ module ActiveRecord def exists?(conditions = :none) if Base === conditions conditions = conditions.id - ActiveSupport::Deprecation.warn "You are passing an instance of ActiveRecord::Base to `exists?`." \ - "Please pass the id of the object by calling `.id`" + ActiveSupport::Deprecation.warn(<<-MSG.squish) + You are passing an instance of ActiveRecord::Base to `exists?`. + Please pass the id of the object by calling `.id` + MSG end return false if !conditions @@ -430,19 +437,20 @@ module ActiveRecord else find_some(ids) end + rescue RangeError + raise RecordNotFound, "Couldn't find #{@klass.name} with an out of range ID" end def find_one(id) if ActiveRecord::Base === id id = id.id - ActiveSupport::Deprecation.warn "You are passing an instance of ActiveRecord::Base to `find`." \ - "Please pass the id of the object by calling `.id`" + ActiveSupport::Deprecation.warn(<<-MSG.squish) + You are passing an instance of ActiveRecord::Base to `find`. + Please pass the id of the object by calling `.id` + MSG end - column = columns_hash[primary_key] - substitute = connection.substitute_at(column, bind_values.length) - relation = where(table[primary_key].eq(substitute)) - relation.bind_values += [[column, id]] + relation = where(primary_key => id) record = relation.take raise_record_not_found_exception!(id, 0, 1) unless record @@ -451,7 +459,7 @@ module ActiveRecord end def find_some(ids) - result = where(table[primary_key].in(ids)).to_a + result = where(primary_key => ids).to_a expected_size = if limit_value && ids.size > limit_value @@ -489,6 +497,10 @@ module ActiveRecord end end + def find_nth!(index) + find_nth(index, offset_index) or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]") + end + def find_nth_with_limit(offset, limit) relation = if order_values.empty? && primary_key order(arel_table[primary_key].asc) diff --git a/activerecord/lib/active_record/relation/merger.rb b/activerecord/lib/active_record/relation/merger.rb index ac41d0aa80..a27f990f74 100644 --- a/activerecord/lib/active_record/relation/merger.rb +++ b/activerecord/lib/active_record/relation/merger.rb @@ -13,7 +13,7 @@ module ActiveRecord @hash = hash end - def merge + def merge #:nodoc: Merger.new(relation, other).merge end @@ -83,12 +83,12 @@ module ActiveRecord private def merge_joins - return if values[:joins].blank? + return if other.joins_values.blank? if other.klass == relation.klass - relation.joins!(*values[:joins]) + relation.joins!(*other.joins_values) else - joins_dependency, rest = values[:joins].partition do |join| + joins_dependency, rest = other.joins_values.partition do |join| case join when Hash, Symbol, Array true @@ -108,48 +108,36 @@ module ActiveRecord def merge_multi_values lhs_wheres = relation.where_values - rhs_wheres = values[:where] || [] + rhs_wheres = other.where_values lhs_binds = relation.bind_values - rhs_binds = values[:bind] || [] + rhs_binds = other.bind_values removed, kept = partition_overwrites(lhs_wheres, rhs_wheres) where_values = kept + rhs_wheres bind_values = filter_binds(lhs_binds, removed) + rhs_binds - conn = relation.klass.connection - bv_index = 0 - where_values.map! do |node| - if Arel::Nodes::Equality === node && Arel::Nodes::BindParam === node.right - substitute = conn.substitute_at(bind_values[bv_index].first, bv_index) - bv_index += 1 - Arel::Nodes::Equality.new(node.left, substitute) - else - node - end - end - relation.where_values = where_values relation.bind_values = bind_values - if values[:reordering] + if other.reordering_value # override any order specified in the original relation - relation.reorder! values[:order] - elsif values[:order] + relation.reorder! other.order_values + elsif other.order_values # merge in order_values from relation - relation.order! values[:order] + relation.order! other.order_values end - relation.extend(*values[:extending]) unless values[:extending].blank? + relation.extend(*other.extending_values) unless other.extending_values.blank? end def merge_single_values - relation.from_value = values[:from] unless relation.from_value - relation.lock_value = values[:lock] unless relation.lock_value + relation.from_value = other.from_value unless relation.from_value + relation.lock_value = other.lock_value unless relation.lock_value - unless values[:create_with].blank? - relation.create_with_value = (relation.create_with_value || {}).merge(values[:create_with]) + unless other.create_with_value.blank? + relation.create_with_value = (relation.create_with_value || {}).merge(other.create_with_value) end end diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb index 3df0df40ee..e4b6b49087 100644 --- a/activerecord/lib/active_record/relation/predicate_builder.rb +++ b/activerecord/lib/active_record/relation/predicate_builder.rb @@ -109,7 +109,7 @@ module ActiveRecord # FIXME: I think we need to deprecate this behavior register_handler(Class, ->(attribute, value) { attribute.eq(value.name) }) register_handler(Base, ->(attribute, value) { attribute.eq(value.id) }) - register_handler(Range, ->(attribute, value) { attribute.in(value) }) + register_handler(Range, ->(attribute, value) { attribute.between(value) }) register_handler(Relation, RelationHandler.new) register_handler(Array, ArrayHandler.new) diff --git a/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb b/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb index b8d9240bf8..b8f3285c3e 100644 --- a/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb +++ b/activerecord/lib/active_record/relation/predicate_builder/array_handler.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/string/filters' + module ActiveRecord class PredicateBuilder class ArrayHandler # :nodoc: @@ -6,9 +8,12 @@ module ActiveRecord nils, values = values.partition(&:nil?) if values.any? { |val| val.is_a?(Array) } - ActiveSupport::Deprecation.warn "Passing a nested array to Active Record " \ - "finder methods is deprecated and will be removed. Flatten your array " \ - "before using it for 'IN' conditions." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + Passing a nested array to Active Record finder methods is + deprecated and will be removed. Flatten your array before using + it for 'IN' conditions. + MSG + values = values.flatten end @@ -27,7 +32,7 @@ module ActiveRecord values_predicate = values_predicate.or(attribute.eq(nil)) end - array_predicates = ranges.map { |range| attribute.in(range) } + array_predicates = ranges.map { |range| attribute.between(range) } array_predicates.unshift(values_predicate) array_predicates.inject { |composite, predicate| composite.or(predicate) } end diff --git a/activerecord/lib/active_record/relation/predicate_builder/relation_handler.rb b/activerecord/lib/active_record/relation/predicate_builder/relation_handler.rb index 618fa3cdd9..063150958a 100644 --- a/activerecord/lib/active_record/relation/predicate_builder/relation_handler.rb +++ b/activerecord/lib/active_record/relation/predicate_builder/relation_handler.rb @@ -6,7 +6,7 @@ module ActiveRecord value = value.select(value.klass.arel_table[value.klass.primary_key]) end - attribute.in(value.arel.ast) + attribute.in(value.arel) end end end diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index bbddd28ccc..6e384facce 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -1,4 +1,5 @@ require 'active_support/core_ext/array/wrap' +require 'active_support/core_ext/string/filters' require 'active_model/forbidden_attributes_protection' module ActiveRecord @@ -94,8 +95,10 @@ module ActiveRecord def check_cached_relation # :nodoc: if defined?(@arel) && @arel @arel = nil - ActiveSupport::Deprecation.warn "Modifying already cached Relation. The " \ - "cache will be reset. Use a cloned Relation to prevent this warning." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + Modifying already cached Relation. The cache will be reset. Use a + cloned Relation to prevent this warning. + MSG end end @@ -424,19 +427,17 @@ module ActiveRecord # => SELECT "users".* FROM "users" LEFT JOIN bookmarks ON bookmarks.bookmarkable_type = 'Post' AND bookmarks.user_id = users.id def joins(*args) check_if_method_has_arguments!(:joins, args) - - args.compact! - args.flatten! - spawn.joins!(*args) end def joins!(*args) # :nodoc: + args.compact! + args.flatten! self.joins_values += args self end - def bind(value) + def bind(value) # :nodoc: spawn.bind!(value) end @@ -878,13 +879,6 @@ module ActiveRecord arel.from(build_from) if from_value arel.lock(lock_value) if lock_value - # Reorder bind indexes if joins produced bind values - bvs = arel.bind_values + bind_values - arel.ast.grep(Arel::Nodes::BindParam).each_with_index do |bp, i| - column = bvs[i].first - bp.replace connection.substitute_at(column, i) - end - arel end @@ -913,7 +907,7 @@ module ActiveRecord where_values.reject! do |rel| case rel - when Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, Arel::Nodes::NotEqual + when Arel::Nodes::Between, Arel::Nodes::In, Arel::Nodes::NotIn, Arel::Nodes::Equality, Arel::Nodes::NotEqual, Arel::Nodes::LessThanOrEqual, Arel::Nodes::GreaterThanOrEqual subrelation = (rel.left.kind_of?(Arel::Attributes::Attribute) ? rel.left : rel.right) subrelation.name == target_value end @@ -955,8 +949,7 @@ module ActiveRecord when Hash opts = PredicateBuilder.resolve_column_aliases(klass, opts) - bv_len = bind_values.length - tmp_opts, bind_values = create_binds(opts, bv_len) + tmp_opts, bind_values = create_binds(opts) self.bind_values += bind_values attributes = @klass.send(:expand_hash_conditions_for_aggregates, tmp_opts) @@ -968,7 +961,7 @@ module ActiveRecord end end - def create_binds(opts, idx) + def create_binds(opts) bindable, non_binds = opts.partition do |column, value| case value when String, Integer, ActiveRecord::StatementCache::Substitute @@ -978,12 +971,23 @@ module ActiveRecord end end + association_binds, non_binds = non_binds.partition do |column, value| + value.is_a?(Hash) && association_for_table(column) + end + new_opts = {} binds = [] - bindable.each_with_index do |(column,value), index| + bindable.each do |(column,value)| binds.push [@klass.columns_hash[column.to_s], value] - new_opts[column] = connection.substitute_at(column, index + idx) + new_opts[column] = connection.substitute_at(column) + end + + association_binds.each do |(column, value)| + association_relation = association_for_table(column).klass.send(:relation) + association_new_opts, association_bind = association_relation.send(:create_binds, value) + new_opts[column] = association_new_opts + binds += association_bind end non_binds.each { |column,value| new_opts[column] = value } @@ -991,6 +995,12 @@ module ActiveRecord [new_opts, binds] end + def association_for_table(table_name) + table_name = table_name.to_s + @klass._reflect_on_association(table_name) || + @klass._reflect_on_association(table_name.singularize) + end + def build_from opts, name = from_value case opts @@ -1047,8 +1057,13 @@ module ActiveRecord def build_select(arel, selects) if !selects.empty? expanded_select = selects.map do |field| - columns_hash.key?(field.to_s) ? arel_table[field] : field + if (Symbol === field || String === field) && columns_hash.key?(field.to_s) + arel_table[field] + else + field + end end + arel.project(*expanded_select) else arel.project(@klass.arel_table[Arel.star]) diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb index 8405fdaeb9..3a3e65ef32 100644 --- a/activerecord/lib/active_record/result.rb +++ b/activerecord/lib/active_record/result.rb @@ -42,6 +42,10 @@ module ActiveRecord @column_types = column_types end + def length + @rows.length + end + def each if block_given? hash_rows.each { |row| yield row } diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb index ff70cbed0f..6a130c145b 100644 --- a/activerecord/lib/active_record/sanitization.rb +++ b/activerecord/lib/active_record/sanitization.rb @@ -87,6 +87,9 @@ module ActiveRecord # { address: Address.new("123 abc st.", "chicago") } # # => "address_street='123 abc st.' and address_city='chicago'" def sanitize_sql_hash_for_conditions(attrs, default_table_name = self.table_name) + ActiveSupport::Deprecation.warn(<<-EOWARN) +sanitize_sql_hash_for_conditions is deprecated, and will be removed in Rails 5.0 + EOWARN attrs = PredicateBuilder.resolve_column_aliases self, attrs attrs = expand_hash_conditions_for_aggregates(attrs) @@ -134,7 +137,7 @@ module ActiveRecord raise_if_bind_arity_mismatch(statement, statement.count('?'), values.size) bound = values.dup c = connection - statement.gsub('?') do + statement.gsub(/\?/) do replace_bind_variable(bound.shift, c) end end diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index 82c5ca291c..1dd2cadc01 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -118,6 +118,8 @@ HEADER if pkcol if pk != 'id' tbl.print %Q(, primary_key: "#{pk}") + elsif pkcol.sql_type == 'bigint' + tbl.print ", id: :bigserial" elsif pkcol.sql_type == 'uuid' tbl.print ", id: :uuid" tbl.print %Q(, default: "#{pkcol.default_function}") if pkcol.default_function @@ -242,12 +244,7 @@ HEADER def ignored?(table_name) ['schema_migrations', ignore_tables].flatten.any? do |ignored| - case ignored - when String; remove_prefix_and_suffix(table_name) == ignored - when Regexp; remove_prefix_and_suffix(table_name) =~ ignored - else - raise StandardError, 'ActiveRecord::SchemaDumper.ignore_tables accepts an array of String and / or Regexp values.' - end + ignored === remove_prefix_and_suffix(table_name) end end end diff --git a/activerecord/lib/active_record/scoping/named.rb b/activerecord/lib/active_record/scoping/named.rb index 49cadb66d0..35420e6551 100644 --- a/activerecord/lib/active_record/scoping/named.rb +++ b/activerecord/lib/active_record/scoping/named.rb @@ -139,6 +139,10 @@ module ActiveRecord # Article.published.featured.latest_article # Article.featured.titles def scope(name, body, &block) + unless body.respond_to?(:call) + raise ArgumentError, 'The scope body needs to be callable.' + end + if dangerous_class_method?(name) raise ArgumentError, "You tried to define a scope named \"#{name}\" " \ "on the model \"#{self.name}\", but Active Record already defined " \ diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb index f9b54139d5..1228de2bfd 100644 --- a/activerecord/lib/active_record/tasks/database_tasks.rb +++ b/activerecord/lib/active_record/tasks/database_tasks.rb @@ -1,3 +1,5 @@ +require 'active_support/core_ext/string/filters' + module ActiveRecord module Tasks # :nodoc: class DatabaseAlreadyExists < StandardError; end # :nodoc: @@ -187,25 +189,35 @@ module ActiveRecord end def load_schema(format = ActiveRecord::Base.schema_format, file = nil) - ActiveSupport::Deprecation.warn \ - "This method will act on a specific connection in the future. " \ - "To act on the current connection, use `load_schema_current` instead." + ActiveSupport::Deprecation.warn(<<-MSG.squish) + This method will act on a specific connection in the future. + To act on the current connection, use `load_schema_current` instead. + MSG load_schema_current(format, file) end + def schema_file(format = ActiveSupport::Base.schema_format) + case format + when :ruby + File.join(db_dir, "schema.rb") + when :sql + File.join(db_dir, "structure.sql") + end + end + # This method is the successor of +load_schema+. We should rename it # after +load_schema+ went through a deprecation cycle. (Rails > 4.2) def load_schema_for(configuration, format = ActiveRecord::Base.schema_format, file = nil) # :nodoc: + file ||= schema_file(format) + case format when :ruby - file ||= File.join(db_dir, "schema.rb") check_schema_file(file) purge(configuration) ActiveRecord::Base.establish_connection(configuration) load(file) when :sql - file ||= File.join(db_dir, "structure.sql") check_schema_file(file) purge(configuration) structure_load(configuration, file) @@ -214,6 +226,12 @@ module ActiveRecord end end + def load_schema_current_if_exists(format = ActiveRecord::Base.schema_format, file = nil, environment = env) + if File.exist?(file || schema_file(format)) + load_schema_current(format, file, environment) + end + end + def load_schema_current(format = ActiveRecord::Base.schema_format, file = nil, environment = env) each_current_configuration(environment) { |configuration| load_schema_for configuration, format, file diff --git a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb index d890196f47..eafbb2c249 100644 --- a/activerecord/lib/active_record/tasks/mysql_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/mysql_database_tasks.rb @@ -31,6 +31,7 @@ module ActiveRecord end establish_connection configuration else + $stderr.puts error.inspect $stderr.puts "Couldn't create database for #{configuration.inspect}, #{creation_options.inspect}" $stderr.puts "(If you set the charset manually, make sure you have a matching collation)" if configuration['encoding'] end diff --git a/activerecord/lib/active_record/transactions.rb b/activerecord/lib/active_record/transactions.rb index e53297d0ab..f92e1de03b 100644 --- a/activerecord/lib/active_record/transactions.rb +++ b/activerecord/lib/active_record/transactions.rb @@ -11,7 +11,7 @@ module ActiveRecord "\n" \ "You can opt into the new behavior and remove this warning by setting:\n" \ "\n" \ - " config.active_record.raise_in_transactional_callbacks = true" + " config.active_record.raise_in_transactional_callbacks = true\n\n" included do define_callbacks :commit, :rollback, @@ -309,7 +309,7 @@ module ActiveRecord # Ensure that it is not called if the object was never persisted (failed create), # but call it after the commit of a destroyed object. def committed!(should_run_callbacks = true) #:nodoc: - run_commit_callbacks if should_run_callbacks && destroyed? || persisted? + _run_commit_callbacks if should_run_callbacks && destroyed? || persisted? ensure force_clear_transaction_record_state end @@ -317,7 +317,7 @@ module ActiveRecord # Call the +after_rollback+ callbacks. The +force_restore_state+ argument indicates if the record # state should be rolled back to the beginning or just to the last savepoint. def rolledback!(force_restore_state = false, should_run_callbacks = true) #:nodoc: - run_rollback_callbacks if should_run_callbacks + _run_rollback_callbacks if should_run_callbacks ensure restore_transaction_record_state(force_restore_state) clear_transaction_record_state diff --git a/activerecord/lib/active_record/type.rb b/activerecord/lib/active_record/type.rb index e3d6c5957e..e5acbbb6b3 100644 --- a/activerecord/lib/active_record/type.rb +++ b/activerecord/lib/active_record/type.rb @@ -4,6 +4,7 @@ require 'active_record/type/numeric' require 'active_record/type/time_value' require 'active_record/type/value' +require 'active_record/type/big_integer' require 'active_record/type/binary' require 'active_record/type/boolean' require 'active_record/type/date' diff --git a/activerecord/lib/active_record/type/big_integer.rb b/activerecord/lib/active_record/type/big_integer.rb new file mode 100644 index 0000000000..0c72d8914f --- /dev/null +++ b/activerecord/lib/active_record/type/big_integer.rb @@ -0,0 +1,13 @@ +require 'active_record/type/integer' + +module ActiveRecord + module Type + class BigInteger < Integer # :nodoc: + private + + def max_value + ::Float::INFINITY + end + end + end +end diff --git a/activerecord/lib/active_record/type/boolean.rb b/activerecord/lib/active_record/type/boolean.rb index 06dd17ed28..978d16d524 100644 --- a/activerecord/lib/active_record/type/boolean.rb +++ b/activerecord/lib/active_record/type/boolean.rb @@ -10,8 +10,19 @@ module ActiveRecord def cast_value(value) if value == '' nil + elsif ConnectionAdapters::Column::TRUE_VALUES.include?(value) + true else - ConnectionAdapters::Column::TRUE_VALUES.include?(value) + if !ConnectionAdapters::Column::FALSE_VALUES.include?(value) + ActiveSupport::Deprecation.warn(<<-MSG.squish) + You attempted to assign a value which is not explicitly `true` or `false` + to a boolean column. Currently this value casts to `false`. This will + change to match Ruby's semantics, and will cast to `true` in Rails 5. + If you would like to maintain the current behavior, you should + explicitly handle the values you would like cast to `false`. + MSG + end + false end end end diff --git a/activerecord/lib/active_record/type/decimal_without_scale.rb b/activerecord/lib/active_record/type/decimal_without_scale.rb index cabdcecdd7..ff5559e300 100644 --- a/activerecord/lib/active_record/type/decimal_without_scale.rb +++ b/activerecord/lib/active_record/type/decimal_without_scale.rb @@ -1,8 +1,8 @@ -require 'active_record/type/integer' +require 'active_record/type/big_integer' module ActiveRecord module Type - class DecimalWithoutScale < Integer # :nodoc: + class DecimalWithoutScale < BigInteger # :nodoc: def type :decimal 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 bf92680268..82d9327fc0 100644 --- a/activerecord/lib/active_record/type/hash_lookup_type_map.rb +++ b/activerecord/lib/active_record/type/hash_lookup_type_map.rb @@ -3,16 +3,14 @@ module ActiveRecord class HashLookupTypeMap < TypeMap # :nodoc: delegate :key?, to: :@mapping - def lookup(type, *args) - @mapping.fetch(type, proc { default_value }).call(type, *args) + def alias_type(type, alias_type) + register_type(type) { |_, *args| lookup(alias_type, *args) } end - def fetch(type, *args, &block) - @mapping.fetch(type, block).call(type, *args) - end + private - def alias_type(type, alias_type) - register_type(type) { |_, *args| lookup(alias_type, *args) } + def perform_fetch(type, *args, &block) + @mapping.fetch(type, block).call(type, *args) end end end diff --git a/activerecord/lib/active_record/type/integer.rb b/activerecord/lib/active_record/type/integer.rb index 08477d1303..750f353472 100644 --- a/activerecord/lib/active_record/type/integer.rb +++ b/activerecord/lib/active_record/type/integer.rb @@ -3,21 +3,49 @@ module ActiveRecord class Integer < Value # :nodoc: include Numeric + def initialize(*) + super + @range = -max_value...max_value + end + def type :integer end alias type_cast_for_database type_cast + def type_cast_from_database(value) + return if value.nil? + value.to_i + end + + protected + + attr_reader :range + private def cast_value(value) case value when true then 1 when false then 0 - else value.to_i rescue nil + else + result = value.to_i rescue nil + ensure_in_range(result) if result + result end end + + def ensure_in_range(value) + unless range.cover?(value) + raise RangeError, "#{value} is out of range for #{self.class} with limit #{limit || 4}" + end + end + + def max_value + limit = self.limit || 4 + 1 << (limit * 8 - 1) # 8 bits per byte with one bit for sign + end end end end diff --git a/activerecord/lib/active_record/type/serialized.rb b/activerecord/lib/active_record/type/serialized.rb index 17004b3593..3191a868ef 100644 --- a/activerecord/lib/active_record/type/serialized.rb +++ b/activerecord/lib/active_record/type/serialized.rb @@ -1,6 +1,6 @@ module ActiveRecord module Type - class Serialized < SimpleDelegator # :nodoc: + class Serialized < DelegateClass(Type::Value) # :nodoc: include Mutable include Decorator diff --git a/activerecord/lib/active_record/type/string.rb b/activerecord/lib/active_record/type/string.rb index 150defb106..fbc0af2c5a 100644 --- a/activerecord/lib/active_record/type/string.rb +++ b/activerecord/lib/active_record/type/string.rb @@ -15,8 +15,8 @@ module ActiveRecord case value when ::Numeric, ActiveSupport::Duration then value.to_s when ::String then ::String.new(value) - when true then "1" - when false then "0" + when true then "t" + when false then "f" else super end end @@ -25,8 +25,8 @@ module ActiveRecord def cast_value(value) case value - when true then "1" - when false then "0" + when true then "t" + when false then "f" # String.new is slightly faster than dup else ::String.new(value.to_s) end diff --git a/activerecord/lib/active_record/type/type_map.rb b/activerecord/lib/active_record/type/type_map.rb index 88c5f9c497..09f5ba6b74 100644 --- a/activerecord/lib/active_record/type/type_map.rb +++ b/activerecord/lib/active_record/type/type_map.rb @@ -1,24 +1,28 @@ +require 'thread_safe' + module ActiveRecord module Type class TypeMap # :nodoc: def initialize @mapping = {} + @cache = ThreadSafe::Cache.new do |h, key| + h.fetch_or_store(key, ThreadSafe::Cache.new) + end end def lookup(lookup_key, *args) - matching_pair = @mapping.reverse_each.detect do |key, _| - key === lookup_key - end + fetch(lookup_key, *args) { default_value } + end - if matching_pair - matching_pair.last.call(lookup_key, *args) - else - default_value + def fetch(lookup_key, *args, &block) + @cache[lookup_key].fetch_or_store(args) do + perform_fetch(lookup_key, *args, &block) end end def register_type(key, value = nil, &block) raise ::ArgumentError unless value || block + @cache.clear if block @mapping[key] = block @@ -40,6 +44,18 @@ module ActiveRecord private + def perform_fetch(lookup_key, *args) + matching_pair = @mapping.reverse_each.detect do |key, _| + key === lookup_key + end + + if matching_pair + matching_pair.last.call(lookup_key, *args) + else + yield lookup_key, *args + end + end + def default_value @default_value ||= Value.new end diff --git a/activerecord/lib/active_record/validations.rb b/activerecord/lib/active_record/validations.rb index 7f7d49cdb4..a6c8ff7f3a 100644 --- a/activerecord/lib/active_record/validations.rb +++ b/activerecord/lib/active_record/validations.rb @@ -5,13 +5,14 @@ module ActiveRecord # +record+ method to retrieve the record which did not validate. # # begin - # complex_operation_that_calls_save!_internally + # complex_operation_that_internally_calls_save! # rescue ActiveRecord::RecordInvalid => invalid # puts invalid.record.errors # end class RecordInvalid < ActiveRecordError - attr_reader :record # :nodoc: - def initialize(record) # :nodoc: + attr_reader :record + + def initialize(record) @record = record errors = @record.errors.full_messages.join(", ") super(I18n.t(:"#{@record.class.i18n_scope}.errors.messages.record_invalid", :errors => errors, :default => :"errors.messages.record_invalid")) diff --git a/activerecord/lib/active_record/validations/uniqueness.rb b/activerecord/lib/active_record/validations/uniqueness.rb index 2dba4c7b94..3e8afe37a8 100644 --- a/activerecord/lib/active_record/validations/uniqueness.rb +++ b/activerecord/lib/active_record/validations/uniqueness.rb @@ -79,7 +79,7 @@ module ActiveRecord scope_value = record.send(reflection.foreign_key) scope_item = reflection.foreign_key else - scope_value = record.read_attribute(scope_item) + scope_value = record._read_attribute(scope_item) end relation = relation.and(table[scope_item].eq(scope_value)) end diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb index f7bf6987c4..fb0fbb4759 100644 --- a/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb +++ b/activerecord/lib/rails/generators/active_record/migration/templates/create_table_migration.rb @@ -15,5 +15,8 @@ class <%= migration_class_name %> < ActiveRecord::Migration <% attributes_with_index.each do |attribute| -%> add_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %> <% end -%> +<% attributes.select(&:reference?).reject(&:polymorphic?).each do |attribute| -%> + add_foreign_key :<%= table_name %>, :<%= attribute.name.pluralize %> +<% end -%> end end diff --git a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb index ae9c74fd05..7df9bcad25 100644 --- a/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb +++ b/activerecord/lib/rails/generators/active_record/migration/templates/migration.rb @@ -4,6 +4,9 @@ class <%= migration_class_name %> < ActiveRecord::Migration <% attributes.each do |attribute| -%> <%- if attribute.reference? -%> add_reference :<%= table_name %>, :<%= attribute.name %><%= attribute.inject_options %> + <%- unless attribute.polymorphic? -%> + add_foreign_key :<%= table_name %>, :<%= attribute.name.pluralize %> + <%- end -%> <%- else -%> add_column :<%= table_name %>, :<%= attribute.name %>, :<%= attribute.type %><%= attribute.inject_options %> <%- if attribute.has_index? -%> @@ -26,6 +29,9 @@ class <%= migration_class_name %> < ActiveRecord::Migration <%- if migration_action -%> <%- if attribute.reference? -%> remove_reference :<%= table_name %>, :<%= attribute.name %><%= attribute.inject_options %> + <%- unless attribute.polymorphic? -%> + remove_foreign_key :<%= table_name %>, :<%= attribute.name.pluralize %> + <%- end -%> <%- else -%> <%- if attribute.has_index? -%> remove_index :<%= table_name %>, :<%= attribute.index_name %><%= attribute.inject_index_options %> diff --git a/activerecord/test/cases/adapters/mysql/active_schema_test.rb b/activerecord/test/cases/adapters/mysql/active_schema_test.rb index a84673e452..413f67da26 100644 --- a/activerecord/test/cases/adapters/mysql/active_schema_test.rb +++ b/activerecord/test/cases/adapters/mysql/active_schema_test.rb @@ -92,7 +92,7 @@ class ActiveSchemaTest < ActiveRecord::TestCase with_real_execute do begin ActiveRecord::Base.connection.create_table :delete_me - ActiveRecord::Base.connection.add_timestamps :delete_me + ActiveRecord::Base.connection.add_timestamps :delete_me, null: true assert column_present?('delete_me', 'updated_at', 'datetime') assert column_present?('delete_me', 'created_at', 'datetime') ensure diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb index 3dabb1104a..52eebe1886 100644 --- a/activerecord/test/cases/adapters/mysql/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql/connection_test.rb @@ -69,8 +69,8 @@ class MysqlConnectionTest < ActiveRecord::TestCase end def test_bind_value_substitute - bind_param = @connection.substitute_at('foo', 0) - assert_equal Arel.sql('?'), bind_param + bind_param = @connection.substitute_at('foo') + assert_equal Arel.sql('?'), bind_param.to_sql end def test_exec_no_binds diff --git a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb index 49cfafd7a5..3d97182356 100644 --- a/activerecord/test/cases/adapters/mysql2/active_schema_test.rb +++ b/activerecord/test/cases/adapters/mysql2/active_schema_test.rb @@ -92,7 +92,7 @@ class ActiveSchemaTest < ActiveRecord::TestCase with_real_execute do begin ActiveRecord::Base.connection.create_table :delete_me - ActiveRecord::Base.connection.add_timestamps :delete_me + ActiveRecord::Base.connection.add_timestamps :delete_me, null: true assert column_present?('delete_me', 'updated_at', 'datetime') assert column_present?('delete_me', 'created_at', 'datetime') ensure diff --git a/activerecord/test/cases/adapters/mysql2/explain_test.rb b/activerecord/test/cases/adapters/mysql2/explain_test.rb index 675703caa1..f67f21fab1 100644 --- a/activerecord/test/cases/adapters/mysql2/explain_test.rb +++ b/activerecord/test/cases/adapters/mysql2/explain_test.rb @@ -1,5 +1,6 @@ require "cases/helper" require 'models/developer' +require 'models/computer' module ActiveRecord module ConnectionAdapters diff --git a/activerecord/test/cases/adapters/postgresql/array_test.rb b/activerecord/test/cases/adapters/postgresql/array_test.rb index ff553c3f1a..fa7bebf08b 100644 --- a/activerecord/test/cases/adapters/postgresql/array_test.rb +++ b/activerecord/test/cases/adapters/postgresql/array_test.rb @@ -254,6 +254,15 @@ class PostgresqlArrayTest < ActiveRecord::TestCase end end + def test_assigning_non_array_value + record = PgArray.new(tags: "not-an-array") + assert_equal "not-an-array", record.tags + e = assert_raises(ActiveRecord::StatementInvalid) do + record.save! + end + assert_instance_of PG::InvalidTextRepresentation, e.original_exception + end + private def assert_cycle field, array # test creation diff --git a/activerecord/test/cases/adapters/postgresql/bytea_test.rb b/activerecord/test/cases/adapters/postgresql/bytea_test.rb index 7872f91943..aeebec034d 100644 --- a/activerecord/test/cases/adapters/postgresql/bytea_test.rb +++ b/activerecord/test/cases/adapters/postgresql/bytea_test.rb @@ -17,7 +17,6 @@ class PostgresqlByteaTest < ActiveRecord::TestCase end end @column = ByteaDataType.columns_hash['payload'] - assert(@column.is_a?(ActiveRecord::ConnectionAdapters::PostgreSQLColumn)) end teardown do @@ -25,9 +24,17 @@ class PostgresqlByteaTest < ActiveRecord::TestCase end def test_column + assert @column.is_a?(ActiveRecord::ConnectionAdapters::PostgreSQLColumn) assert_equal :binary, @column.type end + def test_binary_columns_are_limitless_the_upper_limit_is_one_GB + assert_equal 'bytea', @connection.type_to_sql(:binary, 100_000) + assert_raise ActiveRecord::ActiveRecordError do + @connection.type_to_sql :binary, 4294967295 + end + end + def test_type_cast_binary_converts_the_encoding assert @column diff --git a/activerecord/test/cases/adapters/postgresql/change_schema_test.rb b/activerecord/test/cases/adapters/postgresql/change_schema_test.rb new file mode 100644 index 0000000000..ec1b446dab --- /dev/null +++ b/activerecord/test/cases/adapters/postgresql/change_schema_test.rb @@ -0,0 +1,26 @@ +require 'cases/helper' + +module ActiveRecord + class Migration + class PGChangeSchemaTest < ActiveRecord::TestCase + attr_reader :connection + + def setup + super + @connection = ActiveRecord::Base.connection + connection.create_table(:strings) do |t| + t.string :somedate + end + end + + def teardown + connection.drop_table :strings + end + + def test_change_string_to_date + connection.change_column :strings, :somedate, :timestamp, using: 'CAST("somedate" AS timestamp)' + assert_equal :datetime, connection.columns(:strings).find { |c| c.name == 'somedate' }.type + end + end + end +end diff --git a/activerecord/test/cases/adapters/postgresql/datatype_test.rb b/activerecord/test/cases/adapters/postgresql/datatype_test.rb index a0a34e4b87..2c4839338c 100644 --- a/activerecord/test/cases/adapters/postgresql/datatype_test.rb +++ b/activerecord/test/cases/adapters/postgresql/datatype_test.rb @@ -94,6 +94,13 @@ class PostgresqlDataTypeTest < ActiveRecord::TestCase assert @first_oid.reload assert_equal new_value, @first_oid.obj_id end + + def test_text_columns_are_limitless_the_upper_limit_is_one_GB + assert_equal 'text', @connection.type_to_sql(:text, 100_000) + assert_raise ActiveRecord::ActiveRecordError do + @connection.type_to_sql :text, 4294967295 + end + end end class PostgresqlInternalDataTypeTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/adapters/postgresql/enum_test.rb b/activerecord/test/cases/adapters/postgresql/enum_test.rb index d99c4a292e..83cedc5a7b 100644 --- a/activerecord/test/cases/adapters/postgresql/enum_test.rb +++ b/activerecord/test/cases/adapters/postgresql/enum_test.rb @@ -1,8 +1,6 @@ # -*- coding: utf-8 -*- require "cases/helper" require 'support/connection_helper' -require 'active_record/base' -require 'active_record/connection_adapters/postgresql_adapter' class PostgresqlEnumTest < ActiveRecord::TestCase include ConnectionHelper diff --git a/activerecord/test/cases/adapters/postgresql/explain_test.rb b/activerecord/test/cases/adapters/postgresql/explain_test.rb index 19053b6732..d2dd04b84b 100644 --- a/activerecord/test/cases/adapters/postgresql/explain_test.rb +++ b/activerecord/test/cases/adapters/postgresql/explain_test.rb @@ -1,5 +1,6 @@ require "cases/helper" require 'models/developer' +require 'models/computer' module ActiveRecord module ConnectionAdapters diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb index 1296eb72c0..6a9c6483fe 100644 --- a/activerecord/test/cases/adapters/postgresql/hstore_test.rb +++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb @@ -1,41 +1,38 @@ # encoding: utf-8 - require "cases/helper" -require 'active_record/base' -require 'active_record/connection_adapters/postgresql_adapter' -class PostgresqlHstoreTest < ActiveRecord::TestCase - class Hstore < ActiveRecord::Base - self.table_name = 'hstores' +if ActiveRecord::Base.connection.supports_extensions? + class PostgresqlHstoreTest < ActiveRecord::TestCase + class Hstore < ActiveRecord::Base + self.table_name = 'hstores' - store_accessor :settings, :language, :timezone - end + store_accessor :settings, :language, :timezone + end - def setup - @connection = ActiveRecord::Base.connection + def setup + @connection = ActiveRecord::Base.connection - unless @connection.extension_enabled?('hstore') - @connection.enable_extension 'hstore' - @connection.commit_db_transaction - end + unless @connection.extension_enabled?('hstore') + @connection.enable_extension 'hstore' + @connection.commit_db_transaction + end - @connection.reconnect! + @connection.reconnect! - @connection.transaction do - @connection.create_table('hstores') do |t| - t.hstore 'tags', :default => '' - t.hstore 'payload', array: true - t.hstore 'settings' + @connection.transaction do + @connection.create_table('hstores') do |t| + t.hstore 'tags', :default => '' + t.hstore 'payload', array: true + t.hstore 'settings' + end end + @column = Hstore.columns_hash['tags'] end - @column = Hstore.columns_hash['tags'] - end - teardown do - @connection.execute 'drop table if exists hstores' - end + teardown do + @connection.execute 'drop table if exists hstores' + end - if ActiveRecord::Base.connection.supports_extensions? def test_hstore_included_in_extensions assert @connection.respond_to?(:extensions), "connection should have a list of extensions" assert @connection.extensions.include?('hstore'), "extension list should include hstore" @@ -315,10 +312,8 @@ class PostgresqlHstoreTest < ActiveRecord::TestCase dupe = record.dup assert_equal({"one" => "two"}, dupe.tags.to_hash) end - end - - private + private def assert_array_cycle(array) # test creation x = Hstore.create!(payload: array) @@ -346,4 +341,5 @@ class PostgresqlHstoreTest < ActiveRecord::TestCase x.reload assert_equal(hash, x.tags) end + end end diff --git a/activerecord/test/cases/adapters/postgresql/json_test.rb b/activerecord/test/cases/adapters/postgresql/json_test.rb index 86ba849445..340ca29c0e 100644 --- a/activerecord/test/cases/adapters/postgresql/json_test.rb +++ b/activerecord/test/cases/adapters/postgresql/json_test.rb @@ -1,10 +1,10 @@ # encoding: utf-8 - require "cases/helper" -require 'active_record/base' -require 'active_record/connection_adapters/postgresql_adapter' +require 'support/schema_dumping_helper' module PostgresqlJSONSharedTestCases + include SchemaDumpingHelper + class JsonDataType < ActiveRecord::Base self.table_name = 'json_data_type' @@ -64,6 +64,11 @@ module PostgresqlJSONSharedTestCases JsonDataType.reset_column_information end + def test_schema_dumping + output = dump_table_schema("json_data_type") + assert_match(/t.#{column_type.to_s}\s+"payload",\s+default: {}/, output) + end + def test_cast_value_on_write x = JsonDataType.new payload: {"string" => "foo", :symbol => :bar} assert_equal({"string" => "foo", :symbol => :bar}, x.payload_before_type_cast) diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb index a71c0dfb26..c3c696b871 100644 --- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb +++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb @@ -304,11 +304,8 @@ module ActiveRecord end def test_substitute_at - bind = @connection.substitute_at(nil, 0) - assert_equal Arel.sql('$1'), bind - - bind = @connection.substitute_at(nil, 1) - assert_equal Arel.sql('$2'), bind + bind = @connection.substitute_at(nil) + assert_equal Arel.sql('$1'), bind.to_sql end def test_partial_index diff --git a/activerecord/test/cases/adapters/postgresql/rename_table_test.rb b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb new file mode 100644 index 0000000000..056a035622 --- /dev/null +++ b/activerecord/test/cases/adapters/postgresql/rename_table_test.rb @@ -0,0 +1,34 @@ +require "cases/helper" + +class PostgresqlRenameTableTest < ActiveRecord::TestCase + def setup + @connection = ActiveRecord::Base.connection + @connection.create_table :before_rename, force: true + end + + def teardown + @connection.execute 'DROP TABLE IF EXISTS "before_rename"' + @connection.execute 'DROP TABLE IF EXISTS "after_rename"' + end + + test "renaming a table also renames the primary key index" do + # sanity check + assert_equal 1, num_indices_named("before_rename_pkey") + assert_equal 0, num_indices_named("after_rename_pkey") + + @connection.rename_table :before_rename, :after_rename + + assert_equal 0, num_indices_named("before_rename_pkey") + assert_equal 1, num_indices_named("after_rename_pkey") + end + + private + + def num_indices_named(name) + @connection.execute(<<-SQL).values.length + SELECT 1 FROM "pg_index" + JOIN "pg_class" ON "pg_index"."indexrelid" = "pg_class"."oid" + WHERE "pg_class"."relname" = '#{name}' + SQL + end +end diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb index 6f40b0d2de..350cb3e065 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb @@ -388,6 +388,14 @@ class SchemaTest < ActiveRecord::TestCase assert_equal "1", @connection.select_value("SELECT nextval('#{sequence_name}')") end + def test_set_pk_sequence + table_name = "#{SCHEMA_NAME}.#{PK_TABLE_NAME}" + _, sequence_name = @connection.pk_and_sequence_for table_name + @connection.set_pk_sequence! table_name, 123 + assert_equal "124", @connection.select_value("SELECT nextval('#{sequence_name}')") + @connection.reset_pk_sequence! table_name + end + private def columns(table_name) @connection.send(:column_definitions, table_name).map do |name, type, default| diff --git a/activerecord/test/cases/adapters/postgresql/sql_types_test.rb b/activerecord/test/cases/adapters/postgresql/sql_types_test.rb deleted file mode 100644 index d7d40f6385..0000000000 --- a/activerecord/test/cases/adapters/postgresql/sql_types_test.rb +++ /dev/null @@ -1,18 +0,0 @@ -require "cases/helper" - -class SqlTypesTest < ActiveRecord::TestCase - def test_binary_types - assert_equal 'bytea', type_to_sql(:binary, 100_000) - assert_raise ActiveRecord::ActiveRecordError do - type_to_sql :binary, 4294967295 - end - assert_equal 'text', type_to_sql(:text, 100_000) - assert_raise ActiveRecord::ActiveRecordError do - type_to_sql :text, 4294967295 - end - end - - def type_to_sql(*args) - ActiveRecord::Base.connection.type_to_sql(*args) - end -end diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb index ae5b409f99..5753da1173 100644 --- a/activerecord/test/cases/adapters/postgresql/uuid_test.rb +++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb @@ -1,8 +1,6 @@ # encoding: utf-8 - require "cases/helper" -require 'active_record/base' -require 'active_record/connection_adapters/postgresql_adapter' +require 'support/schema_dumping_helper' module PostgresqlUUIDHelper def connection @@ -110,8 +108,29 @@ class PostgresqlUUIDTest < ActiveRecord::TestCase end end +class PostgresqlLargeKeysTest < ActiveRecord::TestCase + include PostgresqlUUIDHelper + include SchemaDumpingHelper + + def setup + connection.create_table('big_serials', id: :bigserial) do |t| + t.string 'name' + end + end + + def test_omg + schema = dump_table_schema "big_serials" + assert_match "create_table \"big_serials\", id: :bigserial, force: true", schema + end + + def teardown + drop_table "big_serials" + end +end + class PostgresqlUUIDGenerationTest < ActiveRecord::TestCase include PostgresqlUUIDHelper + include SchemaDumpingHelper class UUID < ActiveRecord::Base self.table_name = 'pg_uuids' @@ -171,17 +190,15 @@ class PostgresqlUUIDGenerationTest < ActiveRecord::TestCase end def test_schema_dumper_for_uuid_primary_key - schema = StringIO.new - ActiveRecord::SchemaDumper.dump(connection, schema) - assert_match(/\bcreate_table "pg_uuids", id: :uuid, default: "uuid_generate_v1\(\)"/, schema.string) - assert_match(/t\.uuid "other_uuid", default: "uuid_generate_v4\(\)"/, schema.string) + schema = dump_table_schema "pg_uuids" + assert_match(/\bcreate_table "pg_uuids", id: :uuid, default: "uuid_generate_v1\(\)"/, schema) + assert_match(/t\.uuid "other_uuid", default: "uuid_generate_v4\(\)"/, schema) end def test_schema_dumper_for_uuid_primary_key_with_custom_default - schema = StringIO.new - ActiveRecord::SchemaDumper.dump(connection, schema) - assert_match(/\bcreate_table "pg_uuids_2", id: :uuid, default: "my_uuid_generator\(\)"/, schema.string) - assert_match(/t\.uuid "other_uuid_2", default: "my_uuid_generator\(\)"/, schema.string) + schema = dump_table_schema "pg_uuids_2" + assert_match(/\bcreate_table "pg_uuids_2", id: :uuid, default: "my_uuid_generator\(\)"/, schema) + assert_match(/t\.uuid "other_uuid_2", default: "my_uuid_generator\(\)"/, schema) end end end diff --git a/activerecord/test/cases/adapters/sqlite3/explain_test.rb b/activerecord/test/cases/adapters/sqlite3/explain_test.rb index f1d6119d2e..de6e35ef57 100644 --- a/activerecord/test/cases/adapters/sqlite3/explain_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/explain_test.rb @@ -1,5 +1,6 @@ require "cases/helper" require 'models/developer' +require 'models/computer' module ActiveRecord module ConnectionAdapters diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index 8c1c22d3bf..d83c65cf0e 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -133,8 +133,8 @@ module ActiveRecord end def test_bind_value_substitute - bind_param = @conn.substitute_at('foo', 0) - assert_equal Arel.sql('?'), bind_param + bind_param = @conn.substitute_at('foo') + assert_equal Arel.sql('?'), bind_param.to_sql end def test_exec_no_binds diff --git a/activerecord/test/cases/ar_schema_test.rb b/activerecord/test/cases/ar_schema_test.rb index b6333240a8..025c9fe6f9 100644 --- a/activerecord/test/cases/ar_schema_test.rb +++ b/activerecord/test/cases/ar_schema_test.rb @@ -115,6 +115,15 @@ if ActiveRecord::Base.connection.supports_migrations? end end + def test_timestamps_without_null_is_deprecated_on_add_timestamps + assert_deprecated do + ActiveRecord::Schema.define do + create_table :has_timestamps + add_timestamps :has_timestamps + end + end + end + def test_no_deprecation_warning_from_timestamps_on_create_table assert_not_deprecated do ActiveRecord::Schema.define do diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 25555bd75c..17394cb6f7 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -1,5 +1,6 @@ require 'cases/helper' require 'models/developer' +require 'models/computer' require 'models/project' require 'models/company' require 'models/topic' @@ -57,6 +58,35 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase end end + def test_default_scope_on_relations_is_not_cached + counter = 0 + + comments = Class.new(ActiveRecord::Base) { + self.table_name = 'comments' + self.inheritance_column = 'not_there' + + posts = Class.new(ActiveRecord::Base) { + self.table_name = 'posts' + self.inheritance_column = 'not_there' + + default_scope -> { + counter += 1 + where("id = :inc", :inc => counter) + } + + has_many :comments, :class => comments + } + belongs_to :post, :class => posts, :inverse_of => false + } + + assert_equal 0, counter + comment = comments.first + assert_equal 0, counter + sql = capture_sql { comment.post } + comment.reload + assert_not_equal sql, capture_sql { comment.post } + end + def test_proxy_assignment account = Account.find(1) assert_nothing_raised { account.firm = account.firm } diff --git a/activerecord/test/cases/associations/callbacks_test.rb b/activerecord/test/cases/associations/callbacks_test.rb index 5b7e462f64..a531e0e02c 100644 --- a/activerecord/test/cases/associations/callbacks_test.rb +++ b/activerecord/test/cases/associations/callbacks_test.rb @@ -3,6 +3,7 @@ require 'models/post' require 'models/author' require 'models/project' require 'models/developer' +require 'models/computer' require 'models/company' class AssociationCallbacksTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index b852bd3536..dd4f530791 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -17,6 +17,7 @@ require 'models/subscriber' require 'models/subscription' require 'models/book' require 'models/developer' +require 'models/computer' require 'models/project' require 'models/member' require 'models/membership' @@ -903,6 +904,12 @@ class EagerAssociationTest < ActiveRecord::TestCase assert_no_queries {assert_equal posts(:sti_comments), comment.post} end + def test_eager_association_with_scope_with_joins + assert_nothing_raised do + Post.includes(:very_special_comment_with_post_with_joins).to_a + end + end + def test_preconfigured_includes_with_has_many posts = authors(:david).posts_with_comments one = posts.detect { |p| p.id == 1 } @@ -935,6 +942,42 @@ class EagerAssociationTest < ActiveRecord::TestCase assert_equal 3, authors(:david).posts_with_comments.where("length(comments.body) > 15").references(:comments).count end + def test_association_loading_notification + notifications = messages_for('instantiation.active_record') do + Developer.all.merge!(:includes => 'projects', :where => { 'developers_projects.access_level' => 1 }, :limit => 5).to_a.size + end + + message = notifications.first + payload = message.last + count = Developer.all.merge!(:includes => 'projects', :where => { 'developers_projects.access_level' => 1 }, :limit => 5).to_a.size + + # eagerloaded row count should be greater than just developer count + assert_operator payload[:record_count], :>, count + assert_equal Developer.name, payload[:class_name] + end + + def test_base_messages + notifications = messages_for('instantiation.active_record') do + Developer.all.to_a + end + message = notifications.first + payload = message.last + + assert_equal Developer.all.to_a.count, payload[:record_count] + assert_equal Developer.name, payload[:class_name] + end + + def messages_for(name) + notifications = [] + ActiveSupport::Notifications.subscribe(name) do |*args| + notifications << args + end + yield + notifications + ensure + ActiveSupport::Notifications.unsubscribe(name) + end + def test_load_with_sti_sharing_association assert_queries(2) do #should not do 1 query per subclass Comment.includes(:post).to_a diff --git a/activerecord/test/cases/associations/extension_test.rb b/activerecord/test/cases/associations/extension_test.rb index 4c1fdfdd9a..9d373cd73b 100644 --- a/activerecord/test/cases/associations/extension_test.rb +++ b/activerecord/test/cases/associations/extension_test.rb @@ -3,6 +3,7 @@ require 'models/post' require 'models/comment' require 'models/project' require 'models/developer' +require 'models/computer' require 'models/company_in_module' class AssociationsExtensionsTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb index 859310575e..092e85949c 100644 --- a/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_and_belongs_to_many_associations_test.rb @@ -1,5 +1,6 @@ require "cases/helper" require 'models/developer' +require 'models/computer' require 'models/project' require 'models/company' require 'models/customer' @@ -78,9 +79,13 @@ class SubDeveloper < Developer :association_foreign_key => "developer_id" end +class DeveloperWithSymbolClassName < Developer + has_and_belongs_to_many :projects, class_name: :ProjectWithSymbolsForKeys +end + class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase fixtures :accounts, :companies, :categories, :posts, :categories_posts, :developers, :projects, :developers_projects, - :parrots, :pirates, :parrots_pirates, :treasures, :price_estimates, :tags, :taggings + :parrots, :pirates, :parrots_pirates, :treasures, :price_estimates, :tags, :taggings, :computers def setup_data_for_habtm_case ActiveRecord::Base.connection.execute('delete from countries_treaties') @@ -883,4 +888,18 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase child.special_projects << SpecialProject.new("name" => "Special Project") assert child.save, 'child object should be saved' end + + def test_habtm_with_reflection_using_class_name_and_fixtures + assert_not_nil Developer._reflections['shared_computers'] + # Checking the fixture for named association is important here, because it's the only way + # we've been able to reproduce this bug + assert_not_nil File.read(File.expand_path("../../../fixtures/developers.yml", __FILE__)).index("shared_computers") + assert_equal developers(:david).shared_computers.first, computers(:laptop) + end + + def test_with_symbol_class_name + assert_nothing_raised NoMethodError do + DeveloperWithSymbolClassName.new + end + end end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index e34b993029..8b7ab11570 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1,5 +1,6 @@ require "cases/helper" require 'models/developer' +require 'models/computer' require 'models/project' require 'models/company' require 'models/contract' @@ -76,6 +77,32 @@ class HasManyAssociationsTest < ActiveRecord::TestCase dev.developer_projects.map(&:project_id).sort end + def test_default_scope_on_relations_is_not_cached + counter = 0 + posts = Class.new(ActiveRecord::Base) { + self.table_name = 'posts' + self.inheritance_column = 'not_there' + post = self + + comments = Class.new(ActiveRecord::Base) { + self.table_name = 'comments' + self.inheritance_column = 'not_there' + belongs_to :post, :class => post + default_scope -> { + counter += 1 + where("id = :inc", :inc => counter) + } + } + has_many :comments, :class => comments, :foreign_key => 'post_id' + } + assert_equal 0, counter + post = posts.first + assert_equal 0, counter + sql = capture_sql { post.comments.to_a } + post.comments.reset + assert_not_equal sql, capture_sql { post.comments.to_a } + end + def test_has_many_build_with_options college = College.create(name: 'UFMT') Student.create(active: true, college_id: college.id, name: 'Sarah') @@ -387,6 +414,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal "Summit", Firm.all.merge!(:order => "id").first.clients_using_primary_key.first.name end + def test_update_all_on_association_accessed_before_save + firm = Firm.new(name: 'Firm') + firm.clients << Client.first + firm.save! + assert_equal firm.clients.count, firm.clients.update_all(description: 'Great!') + end + def test_belongs_to_sanity c = Client.new assert_nil c.firm, "belongs_to failed sanity check on new object" @@ -1895,6 +1929,14 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal [bulb1, bulb2], car.all_bulbs.sort_by(&:id) end + test 'unscopes the default scope of associated model when used with include' do + car = Car.create! + bulb = Bulb.create! name: "other", car: car + + assert_equal bulb, Car.find(car.id).all_bulbs.first + assert_equal bulb, Car.includes(:all_bulbs).find(car.id).all_bulbs.first + end + test "raises RecordNotDestroyed when replaced child can't be destroyed" do car = Car.create! original_child = FailedBulb.create!(car: car) @@ -1955,4 +1997,68 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert_equal 1, car.bulbs.count assert_equal 1, car.tyres.count end + + test 'associations replace in memory when records have the same id' do + bulb = Bulb.create! + car = Car.create!(bulbs: [bulb]) + + new_bulb = Bulb.find(bulb.id) + new_bulb.name = "foo" + car.bulbs = [new_bulb] + + assert_equal "foo", car.bulbs.first.name + end + + test 'in memory replacement executes no queries' do + bulb = Bulb.create! + car = Car.create!(bulbs: [bulb]) + + new_bulb = Bulb.find(bulb.id) + + assert_no_queries do + car.bulbs = [new_bulb] + end + end + + test 'in memory replacements do not execute callbacks' do + raise_after_add = false + klass = Class.new(ActiveRecord::Base) do + self.table_name = :cars + has_many :bulbs, after_add: proc { raise if raise_after_add } + + def self.name + "Car" + end + end + bulb = Bulb.create! + car = klass.create!(bulbs: [bulb]) + + new_bulb = Bulb.find(bulb.id) + raise_after_add = true + + assert_nothing_raised do + car.bulbs = [new_bulb] + end + end + + test 'in memory replacements sets inverse instance' do + bulb = Bulb.create! + car = Car.create!(bulbs: [bulb]) + + new_bulb = Bulb.find(bulb.id) + car.bulbs = [new_bulb] + + assert_same car, new_bulb.car + end + + test 'in memory replacement maintains order' do + first_bulb = Bulb.create! + second_bulb = Bulb.create! + car = Car.create!(bulbs: [first_bulb, second_bulb]) + + same_bulb = Bulb.find(first_bulb.id) + car.bulbs = [second_bulb, same_bulb] + + assert_equal [first_bulb, second_bulb], car.bulbs + end end diff --git a/activerecord/test/cases/associations/has_many_through_associations_test.rb b/activerecord/test/cases/associations/has_many_through_associations_test.rb index cddf1a1f72..df4a30ae9b 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -15,6 +15,7 @@ require 'models/toy' require 'models/contract' require 'models/company' require 'models/developer' +require 'models/computer' require 'models/subscriber' require 'models/book' require 'models/subscription' diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index d412b3168e..2ecfcb521d 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -1,5 +1,6 @@ require "cases/helper" require 'models/developer' +require 'models/computer' require 'models/project' require 'models/company' require 'models/ship' diff --git a/activerecord/test/cases/associations/has_one_through_associations_test.rb b/activerecord/test/cases/associations/has_one_through_associations_test.rb index 089cb0a3a2..19d1aa87a8 100644 --- a/activerecord/test/cases/associations/has_one_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_through_associations_test.rb @@ -289,6 +289,12 @@ class HasOneThroughAssociationsTest < ActiveRecord::TestCase end end + def test_has_one_through_polymorphic_association + assert_raise(ActiveRecord::HasOneAssociationPolymorphicThroughError) do + @member.premium_club + end + end + def test_has_one_through_belongs_to_should_update_when_the_through_foreign_key_changes minivan = minivans(:cool_first) diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index 9b0cf4c18f..04ef50e58a 100644 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -1,6 +1,7 @@ require "cases/helper" require 'models/computer' require 'models/developer' +require 'models/computer' require 'models/project' require 'models/company' require 'models/categorization' diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index 7ca7349528..731d433706 100644 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -1,6 +1,7 @@ require "cases/helper" require 'models/minimalistic' require 'models/developer' +require 'models/computer' require 'models/auto_id' require 'models/boolean' require 'models/computer' @@ -736,11 +737,11 @@ class AttributeMethodsTest < ActiveRecord::TestCase def test_bulk_update_raise_unknown_attribute_error error = assert_raises(ActiveRecord::UnknownAttributeError) { - @target.new(:hello => "world") + Topic.new(hello: "world") } - assert_instance_of @target, error.record + assert_instance_of Topic, error.record assert_equal "hello", error.attribute - assert_equal "unknown attribute: hello", error.message + assert_equal "unknown attribute 'hello' for Topic.", error.message end def test_methods_override_in_multi_level_subclass diff --git a/activerecord/test/cases/attribute_set_test.rb b/activerecord/test/cases/attribute_set_test.rb index dc20c3c676..de63672963 100644 --- a/activerecord/test/cases/attribute_set_test.rb +++ b/activerecord/test/cases/attribute_set_test.rb @@ -109,7 +109,15 @@ module ActiveRecord test "fetch_value returns nil for unknown attributes" do attributes = attributes_with_uninitialized_key - assert_nil attributes.fetch_value(:wibble) + assert_nil attributes.fetch_value(:wibble) { "hello" } + end + + test "fetch_value returns nil for unknown attributes when types has a default" do + types = Hash.new(Type::Value.new) + builder = AttributeSet::Builder.new(types) + attributes = builder.build_from_database + + assert_nil attributes.fetch_value(:wibble) { "hello" } end test "fetch_value uses the given block for uninitialized attributes" do @@ -123,6 +131,15 @@ module ActiveRecord assert_nil attributes.fetch_value(:bar) end + test "the primary_key is always initialized" do + builder = AttributeSet::Builder.new({ foo: Type::Integer.new }, :foo) + attributes = builder.build_from_database + + assert attributes.key?(:foo) + assert_equal [:foo], attributes.keys + assert attributes[:foo].initialized? + end + class MyType def type_cast_from_user(value) return if value.nil? diff --git a/activerecord/test/cases/attributes_test.rb b/activerecord/test/cases/attributes_test.rb index 79ef0502cb..dbe1eb48db 100644 --- a/activerecord/test/cases/attributes_test.rb +++ b/activerecord/test/cases/attributes_test.rb @@ -20,7 +20,7 @@ end module ActiveRecord class CustomPropertiesTest < ActiveRecord::TestCase - def test_overloading_types + test "overloading types" do data = OverloadedType.new data.overloaded_float = "1.1" @@ -30,7 +30,7 @@ module ActiveRecord assert_equal 1.1, data.unoverloaded_float end - def test_overloaded_properties_save + test "overloaded properties save" do data = OverloadedType.new data.overloaded_float = "2.2" @@ -43,18 +43,18 @@ module ActiveRecord assert_kind_of Float, UnoverloadedType.last.overloaded_float end - def test_properties_assigned_in_constructor + test "properties assigned in constructor" do data = OverloadedType.new(overloaded_float: '3.3') assert_equal 3, data.overloaded_float end - def test_overloaded_properties_with_limit + test "overloaded properties with limit" do assert_equal 50, OverloadedType.columns_hash['overloaded_string_with_limit'].limit assert_equal 255, UnoverloadedType.columns_hash['overloaded_string_with_limit'].limit end - def test_nonexistent_attribute + test "nonexistent attribute" do data = OverloadedType.new(non_existent_decimal: 1) assert_equal BigDecimal.new(1), data.non_existent_decimal @@ -63,7 +63,7 @@ module ActiveRecord end end - def test_changing_defaults + test "changing defaults" do data = OverloadedType.new unoverloaded_data = UnoverloadedType.new @@ -71,24 +71,28 @@ module ActiveRecord assert_equal 'the original default', unoverloaded_data.string_with_default end - def test_children_inherit_custom_properties + test "defaults are not touched on the columns" do + assert_equal 'the original default', OverloadedType.columns_hash['string_with_default'].default + end + + test "children inherit custom properties" do data = ChildOfOverloadedType.new(overloaded_float: '4.4') assert_equal 4, data.overloaded_float end - def test_children_can_override_parents + test "children can override parents" do data = GrandchildOfOverloadedType.new(overloaded_float: '4.4') assert_equal 4.4, data.overloaded_float end - def test_overloading_properties_does_not_change_column_order + test "overloading properties does not change column order" do column_names = OverloadedType.column_names assert_equal %w(id overloaded_float unoverloaded_float overloaded_string_with_limit string_with_default non_existent_decimal), column_names end - def test_caches_are_cleared + test "caches are cleared" do klass = Class.new(OverloadedType) assert_equal 6, klass.columns.length diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index b2a7d3956d..71c34d816a 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -1,8 +1,10 @@ require 'cases/helper' require 'models/bird' +require 'models/comment' require 'models/company' require 'models/customer' require 'models/developer' +require 'models/computer' require 'models/invoice' require 'models/line_item' require 'models/order' @@ -616,6 +618,14 @@ class TestDefaultAutosaveAssociationOnNewRecord < ActiveRecord::TestCase firm.save! assert !account.persisted? end + + def test_autosave_new_record_with_after_create_callback + post = PostWithAfterCreateCallback.new(title: 'Captain Murphy', body: 'is back') + post.comments.build(body: 'foo') + post.save! + + assert_not_nil post.author_id + end end class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index fb535e74fc..098d5b8451 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -10,6 +10,7 @@ require 'models/category' require 'models/company' require 'models/customer' require 'models/developer' +require 'models/computer' require 'models/project' require 'models/default' require 'models/auto_id' @@ -522,6 +523,10 @@ class BasicsTest < ActiveRecord::TestCase assert_equal Topic.find(['1-meowmeow', '2-hello']), Topic.find([1, 2]) end + def test_find_by_slug_with_range + assert_equal Topic.where(id: '1-meowmeow'..'2-hello'), Topic.where(id: 1..2) + end + def test_equality_of_new_records assert_not_equal Topic.new, Topic.new assert_equal false, Topic.new == Topic.new @@ -985,7 +990,6 @@ class BasicsTest < ActiveRecord::TestCase class NumericData < ActiveRecord::Base self.table_name = 'numeric_data' - attribute :world_population, Type::Integer.new attribute :my_house_population, Type::Integer.new attribute :atoms_in_universe, Type::Integer.new end @@ -1383,7 +1387,10 @@ class BasicsTest < ActiveRecord::TestCase c1 = Post.connection.schema_cache.columns('posts') ActiveRecord::Base.clear_cache! c2 = Post.connection.schema_cache.columns('posts') - assert_not_equal c1, c2 + c1.each_with_index do |v, i| + assert_not_same v, c2[i] + end + assert_equal c1, c2 end def test_current_scope_is_reset diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb index 0bc7ee6d64..c4634d11e2 100644 --- a/activerecord/test/cases/bind_parameter_test.rb +++ b/activerecord/test/cases/bind_parameter_test.rb @@ -31,9 +31,9 @@ module ActiveRecord if ActiveRecord::Base.connection.supports_statement_cache? def test_binds_are_logged - sub = @connection.substitute_at(@pk, 0) + sub = @connection.substitute_at(@pk) binds = [[@pk, 1]] - sql = "select * from topics where id = #{sub}" + sql = "select * from topics where id = #{sub.to_sql}" @connection.exec_query(sql, 'SQL', binds) @@ -42,9 +42,9 @@ module ActiveRecord end def test_binds_are_logged_after_type_cast - sub = @connection.substitute_at(@pk, 0) + sub = @connection.substitute_at(@pk) binds = [[@pk, "3"]] - sql = "select * from topics where id = #{sub}" + sql = "select * from topics where id = #{sub.to_sql}" @connection.exec_query(sql, 'SQL', binds) diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index ec6a319ab5..e886268a72 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -461,7 +461,6 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal 7, Company.includes(:contracts).sum(:developer_id) end - def test_from_option_with_specified_index if Edge.connection.adapter_name == 'MySQL' or Edge.connection.adapter_name == 'Mysql2' assert_equal Edge.count(:all), Edge.from('edges USE INDEX(unique_edge_index)').count(:all) diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb index c8f56e3c73..e3c3c2fcdf 100644 --- a/activerecord/test/cases/callbacks_test.rb +++ b/activerecord/test/cases/callbacks_test.rb @@ -1,4 +1,6 @@ require "cases/helper" +require 'models/developer' +require 'models/computer' class CallbackDeveloper < ActiveRecord::Base self.table_name = 'developers' @@ -441,7 +443,8 @@ class CallbacksTest < ActiveRecord::TestCase david = ImmutableDeveloper.find(1) assert david.valid? assert !david.save - assert_raise(ActiveRecord::RecordNotSaved) { david.save! } + exc = assert_raise(ActiveRecord::RecordNotSaved) { david.save! } + assert_equal exc.record, david david = ImmutableDeveloper.find(1) david.salary = 10_000_000 @@ -475,7 +478,8 @@ class CallbacksTest < ActiveRecord::TestCase def test_before_destroy_returning_false david = ImmutableDeveloper.find(1) assert !david.destroy - assert_raise(ActiveRecord::RecordNotDestroyed) { david.destroy! } + exc = assert_raise(ActiveRecord::RecordNotDestroyed) { david.destroy! } + assert_equal exc.record, david assert_not_nil ImmutableDeveloper.find_by_id(1) someone = CallbackCancellationDeveloper.find(1) 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 e1b2804a18..37ad469476 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 @@ -5,10 +5,14 @@ module ActiveRecord class MergeAndResolveDefaultUrlConfigTest < ActiveRecord::TestCase def setup @previous_database_url = ENV.delete("DATABASE_URL") + @previous_rack_env = ENV.delete("RACK_ENV") + @previous_rails_env = ENV.delete("RAILS_ENV") end teardown do ENV["DATABASE_URL"] = @previous_database_url + ENV["RACK_ENV"] = @previous_rack_env + ENV["RAILS_ENV"] = @previous_rails_env end def resolve_config(config) @@ -27,6 +31,26 @@ module ActiveRecord assert_equal expected, actual end + def test_resolver_with_database_uri_and_current_env_symbol_key_and_rails_env + ENV['DATABASE_URL'] = "postgres://localhost/foo" + ENV['RAILS_ENV'] = "foo" + + config = { "not_production" => { "adapter" => "not_postgres", "database" => "not_foo" } } + actual = resolve_spec(:foo, config) + expected = { "adapter" => "postgresql", "database" => "foo", "host" => "localhost" } + assert_equal expected, actual + end + + def test_resolver_with_database_uri_and_current_env_symbol_key_and_rack_env + ENV['DATABASE_URL'] = "postgres://localhost/foo" + ENV['RACK_ENV'] = "foo" + + config = { "not_production" => { "adapter" => "not_postgres", "database" => "not_foo" } } + actual = resolve_spec(:foo, config) + expected = { "adapter" => "postgresql", "database" => "foo", "host" => "localhost" } + assert_equal expected, actual + end + def test_resolver_with_database_uri_and_and_current_env_string_key ENV['DATABASE_URL'] = "postgres://localhost/foo" config = { "default_env" => { "adapter" => "not_postgres", "database" => "not_foo" } } @@ -35,6 +59,26 @@ module ActiveRecord assert_equal expected, actual end + def test_resolver_with_database_uri_and_and_current_env_string_key_and_rails_env + ENV['DATABASE_URL'] = "postgres://localhost/foo" + ENV['RAILS_ENV'] = "foo" + + config = { "not_production" => {"adapter" => "not_postgres", "database" => "not_foo" } } + actual = assert_deprecated { resolve_spec("foo", config) } + expected = { "adapter" => "postgresql", "database" => "foo", "host" => "localhost" } + assert_equal expected, actual + end + + def test_resolver_with_database_uri_and_and_current_env_string_key_and_rack_env + ENV['DATABASE_URL'] = "postgres://localhost/foo" + ENV['RACK_ENV'] = "foo" + + config = { "not_production" => {"adapter" => "not_postgres", "database" => "not_foo" } } + actual = assert_deprecated { resolve_spec("foo", config) } + expected = { "adapter" => "postgresql", "database" => "foo", "host" => "localhost" } + assert_equal expected, actual + end + def test_resolver_with_database_uri_and_known_key ENV['DATABASE_URL'] = "postgres://localhost/foo" config = { "production" => { "adapter" => "not_postgres", "database" => "not_foo", "host" => "localhost" } } @@ -139,6 +183,51 @@ module ActiveRecord assert_equal nil, actual["production"] assert_equal nil, actual["development"] assert_equal nil, actual["test"] + assert_equal nil, actual[:default_env] + assert_equal nil, actual[:production] + assert_equal nil, actual[:development] + assert_equal nil, actual[:test] + end + + def test_blank_with_database_url_with_rails_env + ENV['RAILS_ENV'] = "not_production" + ENV['DATABASE_URL'] = "postgres://localhost/foo" + + config = {} + actual = resolve_config(config) + expected = { "adapter" => "postgresql", + "database" => "foo", + "host" => "localhost" } + + assert_equal expected, actual["not_production"] + assert_equal nil, actual["production"] + assert_equal nil, actual["default_env"] + assert_equal nil, actual["development"] + assert_equal nil, actual["test"] + assert_equal nil, actual[:default_env] + assert_equal nil, actual[:not_production] + assert_equal nil, actual[:production] + assert_equal nil, actual[:development] + assert_equal nil, actual[:test] + end + + def test_blank_with_database_url_with_rack_env + ENV['RACK_ENV'] = "not_production" + ENV['DATABASE_URL'] = "postgres://localhost/foo" + + config = {} + actual = resolve_config(config) + expected = { "adapter" => "postgresql", + "database" => "foo", + "host" => "localhost" } + + assert_equal expected, actual["not_production"] + assert_equal nil, actual["production"] + assert_equal nil, actual["default_env"] + assert_equal nil, actual["development"] + assert_equal nil, actual["test"] + assert_equal nil, actual[:default_env] + assert_equal nil, actual[:not_production] assert_equal nil, actual[:production] assert_equal nil, actual[:development] assert_equal nil, actual[:test] 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 d4d67487db..80244d1439 100644 --- a/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb +++ b/activerecord/test/cases/connection_adapters/mysql_type_lookup_test.rb @@ -22,6 +22,10 @@ module ActiveRecord assert_lookup_type :string, "SET('one', 'two', 'three')" end + def test_enum_type_with_value_matching_other_type + assert_lookup_type :string, "ENUM('unicode', '8bit', 'none')" + end + def test_binary_types assert_lookup_type :binary, 'bit' assert_lookup_type :binary, 'BIT' diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index ac570ecbe0..33a59d4678 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -10,6 +10,7 @@ require 'models/reply' require 'models/entrant' require 'models/project' require 'models/developer' +require 'models/computer' require 'models/customer' require 'models/toy' require 'models/matey' @@ -99,21 +100,10 @@ class FinderTest < ActiveRecord::TestCase end def test_exists_fails_when_parameter_has_invalid_type - if current_adapter?(:PostgreSQLAdapter, :MysqlAdapter) - assert_raises ActiveRecord::StatementInvalid do - Topic.exists?(("9"*53).to_i) # number that's bigger than int - end - else + assert_raises(RangeError) do assert_equal false, Topic.exists?(("9"*53).to_i) # number that's bigger than int end - - if current_adapter?(:PostgreSQLAdapter) - assert_raises ActiveRecord::StatementInvalid do - Topic.exists?("foo") - end - else - assert_equal false, Topic.exists?("foo") - end + assert_equal false, Topic.exists?("foo") end def test_exists_does_not_select_columns_without_alias @@ -209,6 +199,28 @@ class FinderTest < ActiveRecord::TestCase assert_equal 2, last_devs.size end + def test_find_with_large_number + assert_raises(ActiveRecord::RecordNotFound) { Topic.find('9999999999999999999999999999999') } + end + + def test_find_by_with_large_number + assert_nil Topic.find_by(id: '9999999999999999999999999999999') + end + + def test_find_by_id_with_large_number + assert_nil Topic.find_by_id('9999999999999999999999999999999') + end + + def test_find_on_relation_with_large_number + assert_nil Topic.where('1=1').find_by(id: 9999999999999999999999999999999) + end + + def test_find_by_bang_on_relation_with_large_number + assert_raises(ActiveRecord::RecordNotFound) do + Topic.where('1=1').find_by!(id: 9999999999999999999999999999999) + end + end + def test_find_an_empty_array assert_equal [], Topic.find([]) end diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 1050047a43..9edeb8b47f 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -5,11 +5,13 @@ require 'models/admin/randomly_named_c1' require 'models/admin/user' require 'models/binary' require 'models/book' +require 'models/bulb' require 'models/category' require 'models/company' require 'models/computer' require 'models/course' require 'models/developer' +require 'models/computer' require 'models/joke' require 'models/matey' require 'models/parrot' @@ -822,25 +824,6 @@ class ActiveSupportSubclassWithFixturesTest < ActiveRecord::TestCase end end -class FixtureLoadingTest < ActiveRecord::TestCase - def test_logs_message_for_failed_dependency_load - ActiveRecord::Base.logger.expects(:warn).twice - ActiveRecord::TestCase.try_to_load_dependency('does_not_exist') - end - - def test_does_not_logs_message_for_dependency_that_has_been_defined_with_set_fixture_class - ActiveRecord::TestCase.set_fixture_class unknown_dead_parrots: DeadParrot - ActiveRecord::Base.logger.expects(:warn).never - ActiveRecord::TestCase.try_to_load_dependency('unknown_dead_parrot') - end - - def test_does_not_logs_message_for_successful_dependency_load - ActiveRecord::TestCase.expects(:require_dependency).with('works_out_fine') - ActiveRecord::Base.logger.expects(:warn).never - ActiveRecord::TestCase.try_to_load_dependency('works_out_fine') - end -end - class CustomNameForFixtureOrModelTest < ActiveRecord::TestCase ActiveRecord::FixtureSet.reset_cache @@ -871,3 +854,16 @@ class CustomNameForFixtureOrModelTest < ActiveRecord::TestCase assert_equal 'randomly_named_table', Admin::ClassNameThatDoesNotFollowCONVENTIONS.table_name end end + +class FixturesWithDefaultScopeTest < ActiveRecord::TestCase + fixtures :bulbs + + test "inserts fixtures excluded by a default scope" do + assert_equal 1, Bulb.count + assert_equal 2, Bulb.unscoped.count + end + + test "allows access to fixtures excluded by a default scope" do + assert_equal "special", bulbs(:special).name + end +end diff --git a/activerecord/test/cases/helper.rb b/activerecord/test/cases/helper.rb index be635aeef9..80ac57ec7c 100644 --- a/activerecord/test/cases/helper.rb +++ b/activerecord/test/cases/helper.rb @@ -95,7 +95,7 @@ EXPECTED_TIME_ZONE_AWARE_ATTRIBUTES = false def verify_default_timezone_config if Time.zone != EXPECTED_ZONE $stderr.puts <<-MSG -\n#{self.to_s} +\n#{self} Global state `Time.zone` was leaked. Expected: #{EXPECTED_ZONE} Got: #{Time.zone} @@ -103,7 +103,7 @@ def verify_default_timezone_config end if ActiveRecord::Base.default_timezone != EXPECTED_DEFAULT_TIMEZONE $stderr.puts <<-MSG -\n#{self.to_s} +\n#{self} Global state `ActiveRecord::Base.default_timezone` was leaked. Expected: #{EXPECTED_DEFAULT_TIMEZONE} Got: #{ActiveRecord::Base.default_timezone} @@ -111,7 +111,7 @@ def verify_default_timezone_config end if ActiveRecord::Base.time_zone_aware_attributes != EXPECTED_TIME_ZONE_AWARE_ATTRIBUTES $stderr.puts <<-MSG -\n#{self.to_s} +\n#{self} Global state `ActiveRecord::Base.time_zone_aware_attributes` was leaked. Expected: #{EXPECTED_TIME_ZONE_AWARE_ATTRIBUTES} Got: #{ActiveRecord::Base.time_zone_aware_attributes} @@ -136,19 +136,6 @@ def disable_extension!(extension, connection) connection.reconnect! end -unless ENV['FIXTURE_DEBUG'] - module ActiveRecord::TestFixtures::ClassMethods - def try_to_load_dependency_with_silence(*args) - old = ActiveRecord::Base.logger.level - ActiveRecord::Base.logger.level = ActiveSupport::Logger::ERROR - try_to_load_dependency_without_silence(*args) - ActiveRecord::Base.logger.level = old - end - - alias_method_chain :try_to_load_dependency, :silence - end -end - require "cases/validations_repair_helper" class ActiveSupport::TestCase include ActiveRecord::TestFixtures diff --git a/activerecord/test/cases/inheritance_test.rb b/activerecord/test/cases/inheritance_test.rb index 792950d24d..0338669016 100644 --- a/activerecord/test/cases/inheritance_test.rb +++ b/activerecord/test/cases/inheritance_test.rb @@ -22,7 +22,7 @@ class InheritanceTest < ActiveRecord::TestCase company = Company.first company = company.dup company.extend(Module.new { - def read_attribute(name) + def _read_attribute(name) return ' ' if name == 'type' super end diff --git a/activerecord/test/cases/integration_test.rb b/activerecord/test/cases/integration_test.rb index dfb8a608cb..0021988083 100644 --- a/activerecord/test/cases/integration_test.rb +++ b/activerecord/test/cases/integration_test.rb @@ -3,6 +3,7 @@ require 'cases/helper' require 'models/company' require 'models/developer' +require 'models/computer' require 'models/owner' require 'models/pet' diff --git a/activerecord/test/cases/migration/change_schema_test.rb b/activerecord/test/cases/migration/change_schema_test.rb index bd3dd29f4d..d91e7142b3 100644 --- a/activerecord/test/cases/migration/change_schema_test.rb +++ b/activerecord/test/cases/migration/change_schema_test.rb @@ -97,6 +97,25 @@ module ActiveRecord end end + def test_create_table_with_bigint + connection.create_table :testings do |t| + t.bigint :eight_int + end + columns = connection.columns(:testings) + eight = columns.detect { |c| c.name == "eight_int" } + + if current_adapter?(:OracleAdapter) + assert_equal 'NUMBER(8)', eight.sql_type + elsif current_adapter?(:SQLite3Adapter) + assert_equal 'bigint', eight.sql_type + else + assert_equal :integer, eight.type + assert_equal 8, eight.limit + end + ensure + connection.drop_table :testings + end + def test_create_table_with_limits connection.create_table :testings do |t| t.column :foo, :string, :limit => 255 diff --git a/activerecord/test/cases/migration/change_table_test.rb b/activerecord/test/cases/migration/change_table_test.rb index 777a48ad14..6613783fba 100644 --- a/activerecord/test/cases/migration/change_table_test.rb +++ b/activerecord/test/cases/migration/change_table_test.rb @@ -213,6 +213,12 @@ module ActiveRecord t.rename :bar, :baz end end + + def test_table_name_set + with_change_table do |t| + assert_equal :delete_me, t.name + end + end end end end diff --git a/activerecord/test/cases/migration/foreign_key_test.rb b/activerecord/test/cases/migration/foreign_key_test.rb index 406dd70c37..51e21528c2 100644 --- a/activerecord/test/cases/migration/foreign_key_test.rb +++ b/activerecord/test/cases/migration/foreign_key_test.rb @@ -17,11 +17,11 @@ module ActiveRecord setup do @connection = ActiveRecord::Base.connection - @connection.create_table "rockets" do |t| + @connection.create_table "rockets", force: true do |t| t.string :name end - @connection.create_table "astronauts" do |t| + @connection.create_table "astronauts", force: true do |t| t.string :name t.references :rocket end @@ -162,6 +162,14 @@ module ActiveRecord assert_equal [], @connection.foreign_keys("astronauts") end + def test_remove_foreign_key_by_symbol_column + @connection.add_foreign_key :astronauts, :rockets, column: :rocket_id + + assert_equal 1, @connection.foreign_keys("astronauts").size + @connection.remove_foreign_key :astronauts, column: :rocket_id + assert_equal [], @connection.foreign_keys("astronauts") + end + def test_remove_foreign_key_by_name @connection.add_foreign_key :astronauts, :rockets, column: "rocket_id", name: "fancy_named_fk" diff --git a/activerecord/test/cases/migration/index_test.rb b/activerecord/test/cases/migration/index_test.rb index ac932378fd..b23b9a679f 100644 --- a/activerecord/test/cases/migration/index_test.rb +++ b/activerecord/test/cases/migration/index_test.rb @@ -36,6 +36,20 @@ module ActiveRecord assert connection.index_name_exists?(table_name, 'new_idx', true) end + def test_rename_index_too_long + too_long_index_name = good_index_name + 'x' + # keep the names short to make Oracle and similar behave + connection.add_index(table_name, [:foo], :name => 'old_idx') + e = assert_raises(ArgumentError) { + connection.rename_index(table_name, 'old_idx', too_long_index_name) + } + assert_match(/too long; the limit is #{connection.allowed_index_name_length} characters/, e.message) + + # if the adapter doesn't support the indexes call, pick defaults that let the test pass + assert connection.index_name_exists?(table_name, 'old_idx', false) + end + + def test_double_add_index connection.add_index(table_name, [:foo], :name => 'some_idx') assert_raises(ArgumentError) { diff --git a/activerecord/test/cases/migration/references_index_test.rb b/activerecord/test/cases/migration/references_index_test.rb index 4485701a4e..ad6b828d0b 100644 --- a/activerecord/test/cases/migration/references_index_test.rb +++ b/activerecord/test/cases/migration/references_index_test.rb @@ -55,7 +55,7 @@ module ActiveRecord t.references :foo, :polymorphic => true, :index => true end - assert connection.index_exists?(table_name, [:foo_id, :foo_type], :name => :index_testings_on_foo_id_and_foo_type) + assert connection.index_exists?(table_name, [:foo_type, :foo_id], name: :index_testings_on_foo_type_and_foo_id) end end @@ -93,7 +93,7 @@ module ActiveRecord t.references :foo, :polymorphic => true, :index => true end - assert connection.index_exists?(table_name, [:foo_id, :foo_type], :name => :index_testings_on_foo_id_and_foo_type) + assert connection.index_exists?(table_name, [:foo_type, :foo_id], name: :index_testings_on_foo_type_and_foo_id) end end end diff --git a/activerecord/test/cases/migration/references_statements_test.rb b/activerecord/test/cases/migration/references_statements_test.rb index b8b4fa1135..988bd9c89f 100644 --- a/activerecord/test/cases/migration/references_statements_test.rb +++ b/activerecord/test/cases/migration/references_statements_test.rb @@ -42,7 +42,7 @@ module ActiveRecord def test_creates_polymorphic_index add_reference table_name, :taggable, polymorphic: true, index: true - assert index_exists?(table_name, [:taggable_id, :taggable_type]) + assert index_exists?(table_name, [:taggable_type, :taggable_id]) end def test_creates_reference_type_column_with_default diff --git a/activerecord/test/cases/migration_test.rb b/activerecord/test/cases/migration_test.rb index 270e446c69..3192b797b4 100644 --- a/activerecord/test/cases/migration_test.rb +++ b/activerecord/test/cases/migration_test.rb @@ -5,6 +5,7 @@ require 'bigdecimal/util' require 'models/person' require 'models/topic' require 'models/developer' +require 'models/computer' require MIGRATIONS_ROOT + "/valid/2_we_need_reminders" require MIGRATIONS_ROOT + "/rename/1_we_need_things" @@ -15,7 +16,6 @@ class BigNumber < ActiveRecord::Base unless current_adapter?(:PostgreSQLAdapter, :SQLite3Adapter) attribute :value_of_e, Type::Integer.new end - attribute :world_population, Type::Integer.new attribute :my_house_population, Type::Integer.new end @@ -101,6 +101,19 @@ class MigrationTest < ActiveRecord::TestCase ActiveRecord::Migrator.migrations_paths = old_path end + def test_any_migrations + old_path = ActiveRecord::Migrator.migrations_paths + ActiveRecord::Migrator.migrations_paths = MIGRATIONS_ROOT + "/valid" + + assert ActiveRecord::Migrator.any_migrations? + + ActiveRecord::Migrator.migrations_paths = MIGRATIONS_ROOT + "/empty" + + assert_not ActiveRecord::Migrator.any_migrations? + ensure + ActiveRecord::Migrator.migrations_paths = old_path + end + def test_migration_version ActiveRecord::Migrator.run(:up, MIGRATIONS_ROOT + "/version_check", 20131219224947) end diff --git a/activerecord/test/cases/migrator_test.rb b/activerecord/test/cases/migrator_test.rb index 9809d83315..f05ca900aa 100644 --- a/activerecord/test/cases/migrator_test.rb +++ b/activerecord/test/cases/migrator_test.rb @@ -357,11 +357,11 @@ class MigratorTest < ActiveRecord::TestCase end private - def m(name, version, &block) + def m(name, version) x = Sensor.new name, version x.extend(Module.new { - define_method(:up) { block.call(:up, x); super() } - define_method(:down) { block.call(:down, x); super() } + define_method(:up) { yield(:up, x); super() } + define_method(:down) { yield(:down, x); super() } }) if block_given? end diff --git a/activerecord/test/cases/modules_test.rb b/activerecord/test/cases/modules_test.rb index e87773df94..6f65bf80eb 100644 --- a/activerecord/test/cases/modules_test.rb +++ b/activerecord/test/cases/modules_test.rb @@ -2,6 +2,7 @@ require "cases/helper" require 'models/company_in_module' require 'models/shop' require 'models/developer' +require 'models/computer' class ModulesTest < ActiveRecord::TestCase fixtures :accounts, :companies, :projects, :developers, :collections, :products, :variants diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb index 2170fe6118..2bcd496415 100644 --- a/activerecord/test/cases/persistence_test.rb +++ b/activerecord/test/cases/persistence_test.rb @@ -8,6 +8,7 @@ require 'models/reply' require 'models/category' require 'models/company' require 'models/developer' +require 'models/computer' require 'models/project' require 'models/minimalistic' require 'models/warehouse_thing' diff --git a/activerecord/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb index 2afd25c989..1c919f0b57 100644 --- a/activerecord/test/cases/readonly_test.rb +++ b/activerecord/test/cases/readonly_test.rb @@ -3,6 +3,7 @@ require 'models/author' require 'models/post' require 'models/comment' require 'models/developer' +require 'models/computer' require 'models/project' require 'models/reader' require 'models/person' @@ -22,9 +23,15 @@ class ReadOnlyTest < ActiveRecord::TestCase assert !dev.save dev.name = 'Forbidden.' end - assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save } - assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save! } - assert_raise(ActiveRecord::ReadOnlyRecord) { dev.destroy } + + e = assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save } + assert_equal "Developer is marked as readonly", e.message + + e = assert_raise(ActiveRecord::ReadOnlyRecord) { dev.save! } + assert_equal "Developer is marked as readonly", e.message + + e = assert_raise(ActiveRecord::ReadOnlyRecord) { dev.destroy } + assert_equal "Developer is marked as readonly", e.message end diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 84abaf0291..094fcccc89 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -209,6 +209,10 @@ class ReflectionTest < ActiveRecord::TestCase assert_not_equal Object.new, Firm._reflections['clients'] end + def test_reflections_should_return_keys_as_strings + assert Category.reflections.keys.all? { |key| key.is_a? String }, "Model.reflections is expected to return string for keys" + end + def test_has_and_belongs_to_many_reflection assert_equal :has_and_belongs_to_many, Category.reflections['posts'].macro assert_equal :posts, Category.reflect_on_all_associations(:has_and_belongs_to_many).first.name diff --git a/activerecord/test/cases/relation/merging_test.rb b/activerecord/test/cases/relation/merging_test.rb index 8f40a1890d..eb76ef6328 100644 --- a/activerecord/test/cases/relation/merging_test.rb +++ b/activerecord/test/cases/relation/merging_test.rb @@ -2,6 +2,7 @@ require 'cases/helper' require 'models/author' require 'models/comment' require 'models/developer' +require 'models/computer' require 'models/post' require 'models/project' require 'models/rating' diff --git a/activerecord/test/cases/relation/where_chain_test.rb b/activerecord/test/cases/relation/where_chain_test.rb index b9e69bdb08..619055f1e7 100644 --- a/activerecord/test/cases/relation/where_chain_test.rb +++ b/activerecord/test/cases/relation/where_chain_test.rb @@ -149,5 +149,33 @@ module ActiveRecord assert_bound_ast value, Post.arel_table['title'], Arel::Nodes::Equality assert_equal 'alone', bind.last end + + def test_rewhere_with_range + relation = Post.where(comments_count: 1..3).rewhere(comments_count: 3..5) + + assert_equal 1, relation.where_values.size + assert_equal Post.where(comments_count: 3..5), relation + end + + def test_rewhere_with_infinite_upper_bound_range + relation = Post.where(comments_count: 1..Float::INFINITY).rewhere(comments_count: 3..5) + + assert_equal 1, relation.where_values.size + assert_equal Post.where(comments_count: 3..5), relation + end + + def test_rewhere_with_infinite_lower_bound_range + relation = Post.where(comments_count: -Float::INFINITY..1).rewhere(comments_count: 3..5) + + assert_equal 1, relation.where_values.size + assert_equal Post.where(comments_count: 3..5), relation + end + + def test_rewhere_with_infinite_range + relation = Post.where(comments_count: -Float::INFINITY..Float::INFINITY).rewhere(comments_count: 3..5) + + assert_equal 1, relation.where_values.size + assert_equal Post.where(comments_count: 3..5), relation + end end end diff --git a/activerecord/test/cases/relation/where_test.rb b/activerecord/test/cases/relation/where_test.rb index 39c8afdd23..a453203e15 100644 --- a/activerecord/test/cases/relation/where_test.rb +++ b/activerecord/test/cases/relation/where_test.rb @@ -7,6 +7,7 @@ require 'models/comment' require 'models/edge' require 'models/topic' require 'models/binary' +require 'models/vertex' module ActiveRecord class WhereTest < ActiveRecord::TestCase diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index 410b5ba5a3..ca86d58b35 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -7,6 +7,7 @@ require 'models/comment' require 'models/author' require 'models/entrant' require 'models/developer' +require 'models/computer' require 'models/reply' require 'models/company' require 'models/bird' @@ -1702,7 +1703,7 @@ class RelationTest < ActiveRecord::TestCase end def test_unscope_removes_binds - left = Post.where(id: Arel::Nodes::BindParam.new('?')) + left = Post.where(id: Arel::Nodes::BindParam.new) column = Post.columns_hash['id'] left.bind_values += [[column, 20]] diff --git a/activerecord/test/cases/result_test.rb b/activerecord/test/cases/result_test.rb index d6decafad9..dec01dfa76 100644 --- a/activerecord/test/cases/result_test.rb +++ b/activerecord/test/cases/result_test.rb @@ -10,6 +10,10 @@ module ActiveRecord ]) end + test "length" do + assert_equal 3, result.length + end + test "to_hash returns row_hashes" do assert_equal [ {'col_1' => 'row 1 col 1', 'col_2' => 'row 1 col 2'}, diff --git a/activerecord/test/cases/sanitize_test.rb b/activerecord/test/cases/sanitize_test.rb index dca85fb5eb..f477cf7d92 100644 --- a/activerecord/test/cases/sanitize_test.rb +++ b/activerecord/test/cases/sanitize_test.rb @@ -13,7 +13,9 @@ class SanitizeTest < ActiveRecord::TestCase quoted_table_name = ActiveRecord::Base.connection.quote_table_name("adorable_animals") expected_value = "#{quoted_table_name}.#{quoted_column_name} = #{quoted_bambi}" - assert_equal expected_value, Binary.send(:sanitize_sql_hash, {adorable_animals: {name: 'Bambi'}}) + assert_deprecated do + assert_equal expected_value, Binary.send(:sanitize_sql_hash, {adorable_animals: {name: 'Bambi'}}) + end end def test_sanitize_sql_array_handles_string_interpolation diff --git a/activerecord/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index 93fb502410..8731531f54 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -19,7 +19,7 @@ class SchemaDumperTest < ActiveRecord::TestCase def test_dump_schema_information_outputs_lexically_ordered_versions versions = %w{ 20100101010101 20100201010101 20100301010101 } - versions.reverse.each do |v| + versions.reverse_each do |v| ActiveRecord::SchemaMigration.create!(:version => v) end @@ -162,16 +162,6 @@ class SchemaDumperTest < ActiveRecord::TestCase assert_no_match %r{create_table "schema_migrations"}, output end - def test_schema_dump_illegal_ignored_table_value - stream = StringIO.new - old_ignore_tables, ActiveRecord::SchemaDumper.ignore_tables = ActiveRecord::SchemaDumper.ignore_tables, [5] - assert_raise(StandardError) do - ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream) - end - ensure - ActiveRecord::SchemaDumper.ignore_tables = old_ignore_tables - end - def test_schema_dumps_index_columns_in_right_order index_definition = standard_dump.split(/\n/).grep(/add_index.*companies/).first.strip if current_adapter?(:MysqlAdapter, :Mysql2Adapter, :PostgreSQLAdapter) @@ -271,13 +261,6 @@ class SchemaDumperTest < ActiveRecord::TestCase end end - def test_schema_dump_includes_json_shorthand_definition - output = standard_dump - if %r{create_table "postgresql_json_data_type"} =~ output - assert_match %r|t.json "json_data", default: {}|, output - end - end - def test_schema_dump_includes_inet_shorthand_definition output = standard_dump if %r{create_table "postgresql_network_addresses"} =~ output diff --git a/activerecord/test/cases/scoping/default_scoping_test.rb b/activerecord/test/cases/scoping/default_scoping_test.rb index a5c4404175..880d0e8293 100644 --- a/activerecord/test/cases/scoping/default_scoping_test.rb +++ b/activerecord/test/cases/scoping/default_scoping_test.rb @@ -2,6 +2,7 @@ require 'cases/helper' require 'models/post' require 'models/comment' require 'models/developer' +require 'models/computer' class DefaultScopingTest < ActiveRecord::TestCase fixtures :developers, :posts, :comments diff --git a/activerecord/test/cases/scoping/named_scoping_test.rb b/activerecord/test/cases/scoping/named_scoping_test.rb index d3546bd471..41f3449828 100644 --- a/activerecord/test/cases/scoping/named_scoping_test.rb +++ b/activerecord/test/cases/scoping/named_scoping_test.rb @@ -5,6 +5,7 @@ require 'models/comment' require 'models/reply' require 'models/author' require 'models/developer' +require 'models/computer' class NamedScopingTest < ActiveRecord::TestCase fixtures :posts, :authors, :topics, :comments, :author_addresses @@ -132,6 +133,13 @@ class NamedScopingTest < ActiveRecord::TestCase assert_equal Post.ranked_by_comments.limit_by(5), Post.top(5) end + def test_scopes_body_is_a_callable + e = assert_raises ArgumentError do + Class.new(Post).class_eval { scope :containing_the_letter_z, where("body LIKE '%z%'") } + end + assert_equal "The scope body needs to be callable.", e.message + end + def test_active_records_have_scope_named__all__ assert !Topic.all.empty? diff --git a/activerecord/test/cases/scoping/relation_scoping_test.rb b/activerecord/test/cases/scoping/relation_scoping_test.rb index 8e512e118a..d7bcbf6203 100644 --- a/activerecord/test/cases/scoping/relation_scoping_test.rb +++ b/activerecord/test/cases/scoping/relation_scoping_test.rb @@ -2,6 +2,7 @@ require "cases/helper" require 'models/post' require 'models/author' require 'models/developer' +require 'models/computer' require 'models/project' require 'models/comment' require 'models/category' @@ -15,6 +16,26 @@ class RelationScopingTest < ActiveRecord::TestCase developers(:david) end + def test_unscoped_breaks_caching + author = authors :mary + assert_nil author.first_post + post = FirstPost.unscoped do + author.reload.first_post + end + assert post + end + + def test_scope_breaks_caching_on_collections + author = authors :david + ids = author.reload.special_posts_with_default_scope.map(&:id) + assert_equal [1,5,6], ids.sort + scoped_posts = SpecialPostWithDefaultScope.unscoped do + author = authors :david + author.reload.special_posts_with_default_scope.to_a + end + assert_equal author.posts.map(&:id).sort, scoped_posts.map(&:id).sort + end + def test_reverse_order assert_equal Developer.order("id DESC").to_a.reverse, Developer.order("id DESC").reverse_order end diff --git a/activerecord/test/cases/serialization_test.rb b/activerecord/test/cases/serialization_test.rb index 3f52e80e11..35b13ea247 100644 --- a/activerecord/test/cases/serialization_test.rb +++ b/activerecord/test/cases/serialization_test.rb @@ -2,6 +2,8 @@ require "cases/helper" require 'models/contact' require 'models/topic' require 'models/book' +require 'models/author' +require 'models/post' class SerializationTest < ActiveRecord::TestCase fixtures :books @@ -92,4 +94,11 @@ class SerializationTest < ActiveRecord::TestCase book = klazz.find(books(:awdr).id) assert_equal 'paperback', book.read_attribute_for_serialization(:format) end + + def test_find_records_by_serialized_attributes_through_join + author = Author.create!(name: "David") + author.serialized_posts.create!(title: "Hello") + + assert_equal 1, Author.joins(:serialized_posts).where(name: "David", serialized_posts: { title: "Hello" }).length + end end diff --git a/activerecord/test/cases/serialized_attribute_test.rb b/activerecord/test/cases/serialized_attribute_test.rb index c5fb491b10..66f345d805 100644 --- a/activerecord/test/cases/serialized_attribute_test.rb +++ b/activerecord/test/cases/serialized_attribute_test.rb @@ -140,11 +140,10 @@ class SerializedAttributeTest < ActiveRecord::TestCase assert_equal 1, Topic.where(:content => nil).count end - def test_serialized_attribute_should_raise_exception_on_save_with_wrong_type + def test_serialized_attribute_should_raise_exception_on_assignment_with_wrong_type Topic.serialize(:content, Hash) assert_raise(ActiveRecord::SerializationTypeMismatch) do - topic = Topic.new(content: 'string') - topic.save + Topic.new(content: 'string') end end diff --git a/activerecord/test/cases/timestamp_test.rb b/activerecord/test/cases/timestamp_test.rb index abf6becc17..db474c63a4 100644 --- a/activerecord/test/cases/timestamp_test.rb +++ b/activerecord/test/cases/timestamp_test.rb @@ -1,6 +1,7 @@ require 'cases/helper' require 'support/ddl_helper' require 'models/developer' +require 'models/computer' require 'models/owner' require 'models/pet' require 'models/toy' diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index 5cccf2dda5..7160e8324d 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -2,6 +2,7 @@ require "cases/helper" require 'models/topic' require 'models/reply' require 'models/developer' +require 'models/computer' require 'models/book' require 'models/author' require 'models/post' diff --git a/activerecord/test/cases/type/integer_test.rb b/activerecord/test/cases/type/integer_test.rb new file mode 100644 index 0000000000..53d6a3a6aa --- /dev/null +++ b/activerecord/test/cases/type/integer_test.rb @@ -0,0 +1,106 @@ +require "cases/helper" +require "models/company" + +module ActiveRecord + module Type + class IntegerTest < ActiveRecord::TestCase + test "simple values" do + type = Type::Integer.new + assert_equal 1, type.type_cast_from_user(1) + assert_equal 1, type.type_cast_from_user('1') + assert_equal 1, type.type_cast_from_user('1ignore') + assert_equal 0, type.type_cast_from_user('bad1') + assert_equal 0, type.type_cast_from_user('bad') + assert_equal 1, type.type_cast_from_user(1.7) + assert_equal 0, type.type_cast_from_user(false) + assert_equal 1, type.type_cast_from_user(true) + assert_nil type.type_cast_from_user(nil) + end + + test "random objects cast to nil" do + type = Type::Integer.new + assert_nil type.type_cast_from_user([1,2]) + assert_nil type.type_cast_from_user({1 => 2}) + assert_nil type.type_cast_from_user((1..2)) + end + + test "casting ActiveRecord models" do + type = Type::Integer.new + firm = Firm.create(:name => 'Apple') + assert_nil type.type_cast_from_user(firm) + end + + test "casting objects without to_i" do + type = Type::Integer.new + assert_nil type.type_cast_from_user(::Object.new) + end + + test "casting nan and infinity" do + type = Type::Integer.new + assert_nil type.type_cast_from_user(::Float::NAN) + assert_nil type.type_cast_from_user(1.0/0.0) + end + + test "changed?" do + type = Type::Integer.new + + assert type.changed?(5, 5, '5wibble') + assert_not type.changed?(5, 5, '5') + assert_not type.changed?(5, 5, '5.0') + assert_not type.changed?(nil, nil, nil) + end + + test "values below int min value are out of range" do + assert_raises(::RangeError) do + Integer.new.type_cast_from_user("-2147483649") + end + end + + test "values above int max value are out of range" do + assert_raises(::RangeError) do + Integer.new.type_cast_from_user("2147483648") + end + end + + test "very small numbers are out of range" do + assert_raises(::RangeError) do + Integer.new.type_cast_from_user("-9999999999999999999999999999999") + end + end + + test "very large numbers are in range" do + assert_raises(::RangeError) do + Integer.new.type_cast_from_user("9999999999999999999999999999999") + end + end + + test "normal numbers are in range" do + type = Integer.new + assert_equal(0, type.type_cast_from_user("0")) + assert_equal(-1, type.type_cast_from_user("-1")) + assert_equal(1, type.type_cast_from_user("1")) + end + + test "int max value is in range" do + assert_equal(2147483647, Integer.new.type_cast_from_user("2147483647")) + end + + test "int min value is in range" do + assert_equal(-2147483648, Integer.new.type_cast_from_user("-2147483648")) + end + + test "columns with a larger limit have larger ranges" do + type = Integer.new(limit: 8) + + assert_equal(9223372036854775807, type.type_cast_from_user("9223372036854775807")) + assert_equal(-9223372036854775808, type.type_cast_from_user("-9223372036854775808")) + assert_raises(::RangeError) do + type.type_cast_from_user("-9999999999999999999999999999999") + end + assert_raises(::RangeError) do + type.type_cast_from_user("9999999999999999999999999999999") + end + end + end + end +end diff --git a/activerecord/test/cases/type/string_test.rb b/activerecord/test/cases/type/string_test.rb index 420177ed49..4d78f287f1 100644 --- a/activerecord/test/cases/type/string_test.rb +++ b/activerecord/test/cases/type/string_test.rb @@ -4,8 +4,8 @@ module ActiveRecord class StringTypeTest < ActiveRecord::TestCase test "type casting" do type = Type::String.new - assert_equal "1", type.type_cast_from_user(true) - assert_equal "0", type.type_cast_from_user(false) + assert_equal "t", type.type_cast_from_user(true) + assert_equal "f", type.type_cast_from_user(false) assert_equal "123", type.type_cast_from_user(123) end diff --git a/activerecord/test/cases/type/type_map_test.rb b/activerecord/test/cases/type/type_map_test.rb index 4e32f92dd0..172c6dfc4c 100644 --- a/activerecord/test/cases/type/type_map_test.rb +++ b/activerecord/test/cases/type/type_map_test.rb @@ -124,6 +124,53 @@ module ActiveRecord assert_equal mapping.lookup(3), 'string' assert_kind_of Type::Value, mapping.lookup(4) end + + def test_fetch + mapping = TypeMap.new + mapping.register_type(1, "string") + + assert_equal "string", mapping.fetch(1) { "int" } + assert_equal "int", mapping.fetch(2) { "int" } + end + + def test_fetch_yields_args + mapping = TypeMap.new + + assert_equal "foo-1-2-3", mapping.fetch("foo", 1, 2, 3) { |*args| args.join("-") } + assert_equal "bar-1-2-3", mapping.fetch("bar", 1, 2, 3) { |*args| args.join("-") } + end + + def test_fetch_memoizes + mapping = TypeMap.new + + looked_up = false + mapping.register_type(1) do + fail if looked_up + looked_up = true + "string" + end + + assert_equal "string", mapping.fetch(1) + assert_equal "string", mapping.fetch(1) + end + + def test_fetch_memoizes_on_args + mapping = TypeMap.new + mapping.register_type("foo") { |*args| args.join("-") } + + assert_equal "foo-1-2-3", mapping.fetch("foo", 1, 2, 3) { |*args| args.join("-") } + assert_equal "foo-2-3-4", mapping.fetch("foo", 2, 3, 4) { |*args| args.join("-") } + end + + def test_register_clears_cache + mapping = TypeMap.new + + mapping.register_type(1, "string") + mapping.lookup(1) + mapping.register_type(1, "int") + + assert_equal "int", mapping.lookup(1) + end end end end diff --git a/activerecord/test/cases/types_test.rb b/activerecord/test/cases/types_test.rb index db4f78d354..b0979cbe1f 100644 --- a/activerecord/test/cases/types_test.rb +++ b/activerecord/test/cases/types_test.rb @@ -1,5 +1,4 @@ require "cases/helper" -require 'models/company' module ActiveRecord module ConnectionAdapters @@ -29,56 +28,12 @@ module ActiveRecord assert_equal false, type.type_cast_from_user('FALSE') assert_equal false, type.type_cast_from_user('off') assert_equal false, type.type_cast_from_user('OFF') - assert_equal false, type.type_cast_from_user(' ') - assert_equal false, type.type_cast_from_user("\u3000\r\n") - assert_equal false, type.type_cast_from_user("\u0000") - assert_equal false, type.type_cast_from_user('SOMETHING RANDOM') - end - - def test_type_cast_integer - type = Type::Integer.new - assert_equal 1, type.type_cast_from_user(1) - assert_equal 1, type.type_cast_from_user('1') - assert_equal 1, type.type_cast_from_user('1ignore') - assert_equal 0, type.type_cast_from_user('bad1') - assert_equal 0, type.type_cast_from_user('bad') - assert_equal 1, type.type_cast_from_user(1.7) - assert_equal 0, type.type_cast_from_user(false) - assert_equal 1, type.type_cast_from_user(true) - assert_nil type.type_cast_from_user(nil) - end - - def test_type_cast_non_integer_to_integer - type = Type::Integer.new - assert_nil type.type_cast_from_user([1,2]) - assert_nil type.type_cast_from_user({1 => 2}) - assert_nil type.type_cast_from_user((1..2)) - end - - def test_type_cast_activerecord_to_integer - type = Type::Integer.new - firm = Firm.create(:name => 'Apple') - assert_nil type.type_cast_from_user(firm) - end - - def test_type_cast_object_without_to_i_to_integer - type = Type::Integer.new - assert_nil type.type_cast_from_user(Object.new) - end - - def test_type_cast_nan_and_infinity_to_integer - type = Type::Integer.new - assert_nil type.type_cast_from_user(Float::NAN) - assert_nil type.type_cast_from_user(1.0/0.0) - end - - def test_changing_integers - type = Type::Integer.new - - assert type.changed?(5, 5, '5wibble') - assert_not type.changed?(5, 5, '5') - assert_not type.changed?(5, 5, '5.0') - assert_not type.changed?(nil, nil, nil) + assert_deprecated do + assert_equal false, type.type_cast_from_user(' ') + assert_equal false, type.type_cast_from_user("\u3000\r\n") + assert_equal false, type.type_cast_from_user("\u0000") + assert_equal false, type.type_cast_from_user('SOMETHING RANDOM') + end end def test_type_cast_float diff --git a/activerecord/test/cases/validations/uniqueness_validation_test.rb b/activerecord/test/cases/validations/uniqueness_validation_test.rb index 18221cc73d..c6b58d469d 100644 --- a/activerecord/test/cases/validations/uniqueness_validation_test.rb +++ b/activerecord/test/cases/validations/uniqueness_validation_test.rb @@ -41,7 +41,7 @@ class TopicWithUniqEvent < Topic end class UniquenessValidationTest < ActiveRecord::TestCase - fixtures :topics, 'warehouse-things', :developers + fixtures :topics, 'warehouse-things' repair_validations(Topic, Reply) diff --git a/activerecord/test/cases/validations_test.rb b/activerecord/test/cases/validations_test.rb index 55804f9576..db8159eff8 100644 --- a/activerecord/test/cases/validations_test.rb +++ b/activerecord/test/cases/validations_test.rb @@ -4,6 +4,7 @@ require 'models/topic' require 'models/reply' require 'models/person' require 'models/developer' +require 'models/computer' require 'models/parrot' require 'models/company' diff --git a/activerecord/test/config.example.yml b/activerecord/test/config.example.yml index ce30cff9e7..e3b55d640e 100644 --- a/activerecord/test/config.example.yml +++ b/activerecord/test/config.example.yml @@ -69,12 +69,6 @@ connections: username: rails encoding: utf8 - openbase: - arunit: - username: admin - arunit2: - username: admin - oracle: arunit: adapter: oracle_enhanced diff --git a/activerecord/test/fixtures/bulbs.yml b/activerecord/test/fixtures/bulbs.yml new file mode 100644 index 0000000000..e5ce2b796c --- /dev/null +++ b/activerecord/test/fixtures/bulbs.yml @@ -0,0 +1,5 @@ +defaulty: + name: defaulty + +special: + name: special diff --git a/activerecord/test/fixtures/computers.yml b/activerecord/test/fixtures/computers.yml index 7281a4d768..ad5ae2ec71 100644 --- a/activerecord/test/fixtures/computers.yml +++ b/activerecord/test/fixtures/computers.yml @@ -3,3 +3,8 @@ workstation: system: 'Linux' developer: 1 extendedWarranty: 1 + +laptop: + system: 'MacOS 1' + developer: 1 + extendedWarranty: 1 diff --git a/activerecord/test/fixtures/developers.yml b/activerecord/test/fixtures/developers.yml index 1a74563dc6..54b74e7a74 100644 --- a/activerecord/test/fixtures/developers.yml +++ b/activerecord/test/fixtures/developers.yml @@ -2,6 +2,7 @@ david: id: 1 name: David salary: 80000 + shared_computers: laptop jamis: id: 2 diff --git a/activerecord/test/models/author.rb b/activerecord/test/models/author.rb index 8949cf5826..3da3a1fd59 100644 --- a/activerecord/test/models/author.rb +++ b/activerecord/test/models/author.rb @@ -1,5 +1,6 @@ class Author < ActiveRecord::Base has_many :posts + has_many :serialized_posts has_one :post has_many :very_special_comments, :through => :posts has_many :posts_with_comments, -> { includes(:comments) }, :class_name => "Post" @@ -44,6 +45,7 @@ class Author < ActiveRecord::Base has_many :special_posts has_many :special_post_comments, :through => :special_posts, :source => :comments + has_many :special_posts_with_default_scope, :class_name => 'SpecialPostWithDefaultScope' has_many :sti_posts, :class_name => 'StiPost' has_many :sti_post_comments, :through => :sti_posts, :source => :comments diff --git a/activerecord/test/models/developer.rb b/activerecord/test/models/developer.rb index 3627cfdd09..d2a5a7fc49 100644 --- a/activerecord/test/models/developer.rb +++ b/activerecord/test/models/developer.rb @@ -15,6 +15,8 @@ class Developer < ActiveRecord::Base accepts_nested_attributes_for :projects + has_and_belongs_to_many :shared_computers, class_name: "Computer" + has_and_belongs_to_many :projects_extended_by_name, -> { extending(DeveloperProjectsAssociationExtension) }, :class_name => "Project", diff --git a/activerecord/test/models/member.rb b/activerecord/test/models/member.rb index 72095f9236..dc0566d8a7 100644 --- a/activerecord/test/models/member.rb +++ b/activerecord/test/models/member.rb @@ -27,6 +27,9 @@ class Member < ActiveRecord::Base has_many :clubs, :through => :current_memberships has_one :club_through_many, :through => :current_memberships, :source => :club + + belongs_to :admittable, polymorphic: true + has_one :premium_club, through: :admittable end class SelfMember < ActiveRecord::Base diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 256b720c9a..a9996e5236 100644 --- a/activerecord/test/models/post.rb +++ b/activerecord/test/models/post.rb @@ -78,6 +78,7 @@ class Post < ActiveRecord::Base has_one :very_special_comment has_one :very_special_comment_with_post, -> { includes(:post) }, :class_name => "VerySpecialComment" + has_one :very_special_comment_with_post_with_joins, -> { joins(:post).order('posts.id') }, class_name: "VerySpecialComment" has_many :special_comments has_many :nonexistant_comments, -> { where 'comments.id < 0' }, :class_name => 'Comment' @@ -219,8 +220,21 @@ class PostThatLoadsCommentsInAnAfterSaveHook < ActiveRecord::Base end end +class PostWithAfterCreateCallback < ActiveRecord::Base + self.table_name = 'posts' + has_many :comments, foreign_key: :post_id + + after_create do |post| + update_attribute(:author_id, comments.first.id) + end +end + class PostWithCommentWithDefaultScopeReferencesAssociation < ActiveRecord::Base self.table_name = 'posts' has_many :comment_with_default_scope_references_associations, foreign_key: :post_id has_one :first_comment, class_name: "CommentWithDefaultScopeReferencesAssociation", foreign_key: :post_id end + +class SerializedPost < ActiveRecord::Base + serialize :title +end diff --git a/activerecord/test/schema/postgresql_specific_schema.rb b/activerecord/test/schema/postgresql_specific_schema.rb index e9294a11b9..7c3b170c08 100644 --- a/activerecord/test/schema/postgresql_specific_schema.rb +++ b/activerecord/test/schema/postgresql_specific_schema.rb @@ -1,7 +1,9 @@ ActiveRecord::Schema.define do - %w(postgresql_tsvectors postgresql_hstores postgresql_arrays postgresql_moneys postgresql_numbers postgresql_times postgresql_network_addresses postgresql_uuids postgresql_ltrees - postgresql_oids postgresql_xml_data_type defaults geometrics postgresql_timestamp_with_zones postgresql_partitioned_table postgresql_partitioned_table_parent postgresql_json_data_type postgresql_citext).each do |table_name| + %w(postgresql_tsvectors postgresql_hstores postgresql_arrays postgresql_moneys postgresql_numbers postgresql_times + postgresql_network_addresses postgresql_uuids postgresql_ltrees postgresql_oids postgresql_xml_data_type defaults + geometrics postgresql_timestamp_with_zones postgresql_partitioned_table postgresql_partitioned_table_parent + postgresql_citext).each do |table_name| execute "DROP TABLE IF EXISTS #{quote_table_name table_name}" end @@ -108,15 +110,6 @@ _SQL _SQL end - if 't' == select_value("select 'json'=ANY(select typname from pg_type)") - execute <<_SQL - CREATE TABLE postgresql_json_data_type ( - id SERIAL PRIMARY KEY, - json_data json default '{}'::json - ); -_SQL - end - execute <<_SQL CREATE TABLE postgresql_numbers ( id SERIAL PRIMARY KEY, diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb index 10de3d34cb..720a127585 100644 --- a/activerecord/test/schema/schema.rb +++ b/activerecord/test/schema/schema.rb @@ -228,6 +228,11 @@ ActiveRecord::Schema.define do t.integer :extendedWarranty, null: false end + create_table :computers_developers, id: false, force: true do |t| + t.references :computer + t.references :developer + end + create_table :contracts, force: true do |t| t.integer :developer_id t.integer :company_id @@ -311,7 +316,7 @@ ActiveRecord::Schema.define do end create_table :cold_jokes, force: true do |t| - t.string :name + t.string :cold_name end create_table :friendships, force: true do |t| @@ -585,6 +590,11 @@ ActiveRecord::Schema.define do t.integer :tags_with_nullify_count, default: 0 end + create_table :serialized_posts, force: true do |t| + t.integer :author_id + t.string :title, null: false + end + create_table :price_estimates, force: true do |t| t.string :estimate_of_type t.integer :estimate_of_id diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index 74d57180fe..ed30c7de70 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,4 +1,19 @@ -* Corrected Inflector#underscore handling of multiple successive acroynms. +* The decorated `load` and `require` methods are now kept private. + + Fixes #17553. + + *Xavier Noria* + +* `String#remove` and `String#remove!` accept multiple arguments. + + *Pavel Pravosud* + +* `TimeWithZone#strftime` now delegates every directive to `Time#strftime` except for '%Z', + it also now correctly handles escaped '%' characters placed just before time zone related directives. + + *Pablo Herrero* + +* Corrected `Inflector#underscore` handling of multiple successive acroynms. *James Le Cuirot* @@ -23,8 +38,8 @@ *Joost Lubach* -* Time#change can now change nanoseconds (:nsec) as a higher-precision - alternative to microseconds (:usec). +* `Time#change` can now change nanoseconds (`:nsec`) as a higher-precision + alternative to microseconds (`:usec`). *Agis Anastasooulos* @@ -39,14 +54,14 @@ *Akira Matsuda*, *Godfrey Chan* -* Fixed a bug in Inflector#underscore where acroynms in nested constant names +* Fixed a bug in `Inflector#underscore` where acroynms in nested constant names are incorrectly parsed as camelCase. Fixes #8015. *Fred Wu*, *Matthew Draper* -* Make Time#change throw an exception if the :usec option is out of range and +* Make `Time#change` throw an exception if the `:usec` option is out of range and the time has an offset other than UTC or local. *Agis Anastasopoulos* @@ -63,15 +78,15 @@ *Guo Xiang Tan* -* Added instance_eval version to Object#try, so you can do this: +* Added instance_eval version to Object#try and Object#try!, so you can do this: - person.try { name.first } + person.try { name.first } instead of: - person.try { |person| person.name.first } + person.try { |person| person.name.first } - *DHH* + *DHH*, *Ari Pollak* * Fix the `ActiveSupport::Duration#instance_of?` method to return the right value with the class itself since it was previously delegated to the @@ -79,12 +94,12 @@ *Robin Dupret* -* Fix rounding errors with #travel_to by resetting the usec on any passed time to zero, so we only travel +* Fix rounding errors with `#travel_to` by resetting the usec on any passed time to zero, so we only travel with per-second precision, not anything deeper than that. *DHH* -* Fix DateTime comparison with DateTime::Infinity object. +* Fix DateTime comparison with `DateTime::Infinity` object. *Rafael Mendonça França* @@ -151,7 +166,7 @@ * Fixed `ActiveSupport::Cache::FileStore` exploding with long paths. - *Adam Panzer / Michael Grosser* + *Adam Panzer*, *Michael Grosser* * Fixed `ActiveSupport::TimeWithZone#-` so precision is not unnecessarily lost when working with objects with a nanosecond component. diff --git a/activesupport/lib/active_support/callbacks.rb b/activesupport/lib/active_support/callbacks.rb index 4bc13f20ca..24c702b602 100644 --- a/activesupport/lib/active_support/callbacks.rb +++ b/activesupport/lib/active_support/callbacks.rb @@ -78,7 +78,7 @@ module ActiveSupport # save # end def run_callbacks(kind, &block) - send "run_#{kind}_callbacks", &block + send "_run_#{kind}_callbacks", &block end private @@ -559,7 +559,7 @@ module ActiveSupport # This is used internally to append, prepend and skip callbacks to the # CallbackChain. def __update_callbacks(name) #:nodoc: - ([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse.each do |target| + ([self] + ActiveSupport::DescendantsTracker.descendants(self)).reverse_each do |target| chain = target.get_callbacks name yield target, chain.dup end @@ -730,7 +730,7 @@ module ActiveSupport set_callbacks name, CallbackChain.new(name, options) module_eval <<-RUBY, __FILE__, __LINE__ + 1 - def run_#{name}_callbacks(&block) + def _run_#{name}_callbacks(&block) _run_callbacks(_#{name}_callbacks, &block) end RUBY diff --git a/activesupport/lib/active_support/core_ext/array/access.rb b/activesupport/lib/active_support/core_ext/array/access.rb index caa499dfa2..45b89d2705 100644 --- a/activesupport/lib/active_support/core_ext/array/access.rb +++ b/activesupport/lib/active_support/core_ext/array/access.rb @@ -20,7 +20,11 @@ class Array # %w( a b c d ).to(-2) # => ["a", "b", "c"] # %w( a b c ).to(-10) # => [] def to(position) - self[0..position] + if position >= 0 + first position + 1 + else + self[0..position] + end end # Equal to <tt>self[1]</tt>. diff --git a/activesupport/lib/active_support/core_ext/file/atomic.rb b/activesupport/lib/active_support/core_ext/file/atomic.rb index 0e7e3ba378..38374af388 100644 --- a/activesupport/lib/active_support/core_ext/file/atomic.rb +++ b/activesupport/lib/active_support/core_ext/file/atomic.rb @@ -40,7 +40,7 @@ class File chown(old_stat.uid, old_stat.gid, file_name) # This operation will affect filesystem ACL's chmod(old_stat.mode, file_name) - rescue Errno::EPERM + rescue Errno::EPERM, Errno::EACCES # Changing file ownership failed, moving on. end end diff --git a/activesupport/lib/active_support/core_ext/hash/compact.rb b/activesupport/lib/active_support/core_ext/hash/compact.rb index 6566215a4d..5dc9a05ec7 100644 --- a/activesupport/lib/active_support/core_ext/hash/compact.rb +++ b/activesupport/lib/active_support/core_ext/hash/compact.rb @@ -1,6 +1,6 @@ class Hash # Returns a hash with non +nil+ values. - # + # # hash = { a: true, b: false, c: nil} # hash.compact # => { a: true, b: false} # hash # => { a: true, b: false, c: nil} @@ -8,9 +8,9 @@ class Hash def compact self.select { |_, value| !value.nil? } end - + # Replaces current hash with non +nil+ values. - # + # # hash = { a: true, b: false, c: nil} # hash.compact! # => { a: true, b: false} # hash # => { a: true, b: false} diff --git a/activesupport/lib/active_support/core_ext/hash/except.rb b/activesupport/lib/active_support/core_ext/hash/except.rb index 682d089881..6e397abf51 100644 --- a/activesupport/lib/active_support/core_ext/hash/except.rb +++ b/activesupport/lib/active_support/core_ext/hash/except.rb @@ -1,13 +1,19 @@ class Hash - # Returns a hash that includes everything but the given keys. This is useful for - # limiting a set of parameters to everything but a few known toggles: + # Returns a hash that includes everything but the given keys. + # hash = { a: true, b: false, c: nil} + # hash.except(:c) # => { a: true, b: false} + # hash # => { a: true, b: false, c: nil} # + # This is useful for limiting a set of parameters to everything but a few known toggles: # @person.update(params[:person].except(:admin)) def except(*keys) dup.except!(*keys) end # Replaces the hash without the given keys. + # hash = { a: true, b: false, c: nil} + # hash.except!(:c) # => { a: true, b: false} + # hash # => { a: true, b: false } def except!(*keys) keys.each { |key| delete(key) } self diff --git a/activesupport/lib/active_support/core_ext/hash/slice.rb b/activesupport/lib/active_support/core_ext/hash/slice.rb index 8ad600b171..41b2279013 100644 --- a/activesupport/lib/active_support/core_ext/hash/slice.rb +++ b/activesupport/lib/active_support/core_ext/hash/slice.rb @@ -1,6 +1,12 @@ class Hash - # Slice a hash to include only the given keys. This is useful for - # limiting an options hash to valid keys before passing to a method: + # Slice a hash to include only the given keys. Returns a hash containing + # the given keys. + # + # { a: 1, b: 2, c: 3, d: 4 }.slice(:a, :b) + # # => {:a=>1, :b=>2} + # + # This is useful for limiting an options hash to valid keys before + # passing to a method: # # def search(criteria = {}) # criteria.assert_valid_keys(:mass, :velocity, :time) diff --git a/activesupport/lib/active_support/core_ext/kernel/reporting.rb b/activesupport/lib/active_support/core_ext/kernel/reporting.rb index 80c531b694..f5179552bb 100644 --- a/activesupport/lib/active_support/core_ext/kernel/reporting.rb +++ b/activesupport/lib/active_support/core_ext/kernel/reporting.rb @@ -32,7 +32,7 @@ module Kernel # For compatibility def silence_stderr #:nodoc: ActiveSupport::Deprecation.warn( - "#silence_stderr is deprecated and will be removed in the next release" + "`#silence_stderr` is deprecated and will be removed in the next release." ) #not thread-safe silence_stream(STDERR) { yield } end @@ -87,7 +87,7 @@ module Kernel # stream # => "error\n" def capture(stream) ActiveSupport::Deprecation.warn( - "#capture(stream) is deprecated and will be removed in the next release" + "`#capture(stream)` is deprecated and will be removed in the next release." ) #not thread-safe stream = stream.to_s captured_stream = Tempfile.new(stream) @@ -113,7 +113,7 @@ module Kernel # This method is not thread-safe. def quietly ActiveSupport::Deprecation.warn( - "#quietly is deprecated and will be removed in the next release" + "`#quietly` is deprecated and will be removed in the next release." ) #not thread-safe silence_stream(STDOUT) do silence_stream(STDERR) do diff --git a/activesupport/lib/active_support/core_ext/object/try.rb b/activesupport/lib/active_support/core_ext/object/try.rb index 31919474ed..56da398978 100644 --- a/activesupport/lib/active_support/core_ext/object/try.rb +++ b/activesupport/lib/active_support/core_ext/object/try.rb @@ -9,7 +9,23 @@ class Object # # instead of # - # @person ? @person.name : nil + # @person.name if @person + # + # +try+ calls can be chained: + # + # @person.try(:spouse).try(:name) + # + # instead of + # + # @person.spouse.name if @person && @person.spouse + # + # +try+ will also return +nil+ if the receiver does not respond to the method: + # + # @person.try(:non_existing_method) #=> nil + # + # instead of + # + # @person.non_existing_method if @person.respond_to?(:non_existing_method) #=> nil # # +try+ returns +nil+ when called on +nil+ regardless of whether it responds # to the method: @@ -24,7 +40,7 @@ class Object # # The number of arguments in the signature must match. If the object responds # to the method the call is attempted and +ArgumentError+ is still raised - # otherwise. + # in case of argument mismatch. # # If +try+ is called without arguments it yields the receiver to a given # block unless it is +nil+: @@ -38,12 +54,19 @@ class Object # # @person.try { upcase.truncate(50) } # - # Please also note that +try+ is defined on +Object+, therefore it won't work + # Please also note that +try+ is defined on +Object+. Therefore, it won't work # with instances of classes that do not have +Object+ among their ancestors, # like direct subclasses of +BasicObject+. For example, using +try+ with # +SimpleDelegator+ will delegate +try+ to the target instead of calling it on - # delegator itself. + # the delegator itself. def try(*a, &b) + try!(*a, &b) if a.empty? || respond_to?(a.first) + end + + # Same as #try, but will raise a NoMethodError exception if the receiver is not +nil+ and + # does not implement the tried method. + + def try!(*a, &b) if a.empty? && block_given? if b.arity.zero? instance_eval(&b) @@ -51,16 +74,6 @@ class Object yield self end else - public_send(*a, &b) if respond_to?(a.first) - end - end - - # Same as #try, but will raise a NoMethodError exception if the receiving is not nil and - # does not implement the tried method. - def try!(*a, &b) - if a.empty? && block_given? - yield self - else public_send(*a, &b) end end @@ -68,12 +81,12 @@ end class NilClass # Calling +try+ on +nil+ always returns +nil+. - # It becomes specially helpful when navigating through associations that may return +nil+. + # It becomes especially helpful when navigating through associations that may return +nil+. # # nil.try(:name) # => nil # # Without +try+ - # @person && !@person.children.blank? && @person.children.first.name + # @person && @person.children.any? && @person.children.first.name # # With +try+ # @person.try(:children).try(:first).try(:name) diff --git a/activesupport/lib/active_support/core_ext/object/with_options.rb b/activesupport/lib/active_support/core_ext/object/with_options.rb index 42e87c4424..7d38e1d134 100644 --- a/activesupport/lib/active_support/core_ext/object/with_options.rb +++ b/activesupport/lib/active_support/core_ext/object/with_options.rb @@ -47,7 +47,21 @@ class Object # end # # <tt>with_options</tt> can also be nested since the call is forwarded to its receiver. - # Each nesting level will merge inherited defaults in addition to their own. + # + # NOTE: Each nesting level will merge inherited defaults in addition to their own. + # + # class Post < ActiveRecord::Base + # with_options if: :persisted?, length: { minimum: 50 } do + # validates :content, if: -> { content.present? } + # end + # end + # + # The code is equivalent to: + # + # validates :content, length: { minimum: 50 }, if: -> { content.present? } + # + # Hence the inherited default for `if` key is ignored. + # def with_options(options, &block) option_merger = ActiveSupport::OptionMerger.new(self, options) block.arity.zero? ? option_merger.instance_eval(&block) : block.call(option_merger) diff --git a/activesupport/lib/active_support/core_ext/string/filters.rb b/activesupport/lib/active_support/core_ext/string/filters.rb index 2b1583d4ac..096292dc58 100644 --- a/activesupport/lib/active_support/core_ext/string/filters.rb +++ b/activesupport/lib/active_support/core_ext/string/filters.rb @@ -13,6 +13,9 @@ class String end # Performs a destructive squish. See String#squish. + # str = " foo bar \n \t boo" + # str.squish! # => "foo bar boo" + # str # => "foo bar boo" def squish! gsub!(/\A[[:space:]]+/, '') gsub!(/[[:space:]]+\z/, '') @@ -20,14 +23,24 @@ class String self end - # Returns a new string with all occurrences of the pattern removed. Short-hand for String#gsub(pattern, ''). - def remove(pattern) - gsub pattern, '' + # Returns a new string with all occurrences of the patterns removed. + # str = "foo bar test" + # str.remove(" test") # => "foo bar" + # str # => "foo bar test" + def remove(*patterns) + dup.remove!(*patterns) end - # Alters the string by removing all occurrences of the pattern. Short-hand for String#gsub!(pattern, ''). - def remove!(pattern) - gsub! pattern, '' + # Alters the string by removing all occurrences of the patterns. + # str = "foo bar test" + # str.remove!(" test") # => "foo bar" + # str # => "foo bar" + def remove!(*patterns) + patterns.each do |pattern| + gsub! pattern, "" + end + + self end # Truncates a given +text+ after a given <tt>length</tt> if +text+ is longer than <tt>length</tt>: 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 c761325108..ba92afd5f4 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -150,7 +150,7 @@ module ActiveSupport #:nodoc: else if html_safe? new_safe_buffer = super - new_safe_buffer.instance_eval { @html_safe = true } + new_safe_buffer.instance_variable_set :@html_safe, true new_safe_buffer else to_str[*args] @@ -247,6 +247,11 @@ module ActiveSupport #:nodoc: end class String + # Marks a string as trusted safe. It will be inserted into HTML with no + # additional escaping performed. It is your responsibilty to ensure that the + # string contains no malicious content. This method is equivalent to the + # `raw` helper in views. It is recommended that you use `sanitize` instead of + # this method. It should never be called on user input. def html_safe ActiveSupport::SafeBuffer.new(self) end diff --git a/activesupport/lib/active_support/core_ext/time/zones.rb b/activesupport/lib/active_support/core_ext/time/zones.rb index bbda04d60c..64c3b7201b 100644 --- a/activesupport/lib/active_support/core_ext/time/zones.rb +++ b/activesupport/lib/active_support/core_ext/time/zones.rb @@ -1,4 +1,5 @@ require 'active_support/time_with_zone' +require 'active_support/core_ext/time/acts_like' require 'active_support/core_ext/date_and_time/zones' class Time diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 93a11d4586..65a370dd30 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -30,6 +30,10 @@ module ActiveSupport #:nodoc: mattr_accessor :loaded self.loaded = Set.new + # Stack of files being loaded. + mattr_accessor :loading + self.loading = [] + # Should we load files or require them? mattr_accessor :mechanism self.mechanism = ENV['NO_RELOAD'] ? :require : :load @@ -201,7 +205,10 @@ module ActiveSupport #:nodoc: # Object includes this module. module Loadable #:nodoc: def self.exclude_from(base) - base.class_eval { define_method(:load, Kernel.instance_method(:load)) } + base.class_eval do + define_method(:load, Kernel.instance_method(:load)) + private :load + end end def require_or_load(file_name) @@ -237,18 +244,6 @@ module ActiveSupport #:nodoc: raise end - def load(file, wrap = false) - result = false - load_dependency(file) { result = super } - result - end - - def require(file) - result = false - load_dependency(file) { result = super } - result - end - # Mark the given constant as unloadable. Unloadable constants are removed # each time dependencies are cleared. # @@ -265,6 +260,20 @@ module ActiveSupport #:nodoc: def unloadable(const_desc) Dependencies.mark_for_unload const_desc end + + private + + def load(file, wrap = false) + result = false + load_dependency(file) { result = super } + result + end + + def require(file) + result = false + load_dependency(file) { result = super } + result + end end # Exception file-blaming. @@ -317,6 +326,7 @@ module ActiveSupport #:nodoc: def clear log_call loaded.clear + loading.clear remove_unloadable_constants! end @@ -329,6 +339,7 @@ module ActiveSupport #:nodoc: # Record that we've seen this file *before* loading it to avoid an # infinite loop with mutual dependencies. loaded << expanded + loading << expanded begin if load? @@ -351,6 +362,8 @@ module ActiveSupport #:nodoc: rescue Exception loaded.delete expanded raise + ensure + loading.pop end # Record history *after* loading so first load gets warnings. @@ -475,7 +488,7 @@ module ActiveSupport #:nodoc: expanded = File.expand_path(file_path) expanded.sub!(/\.rb\z/, '') - if loaded.include?(expanded) + if loading.include?(expanded) raise "Circular dependency detected while autoloading constant #{qualified_name}" else require_or_load(expanded, qualified_name) diff --git a/activesupport/lib/active_support/dependencies/autoload.rb b/activesupport/lib/active_support/dependencies/autoload.rb index c0dba5f7fd..13036d521d 100644 --- a/activesupport/lib/active_support/dependencies/autoload.rb +++ b/activesupport/lib/active_support/dependencies/autoload.rb @@ -67,7 +67,7 @@ module ActiveSupport end def eager_load! - @_autoloads.values.each { |file| require file } + @_autoloads.each_value { |file| require file } end def autoloads diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb index 584fc1e1c5..0de1d2c7df 100644 --- a/activesupport/lib/active_support/duration.rb +++ b/activesupport/lib/active_support/duration.rb @@ -1,4 +1,3 @@ -require 'active_support/proxy_object' require 'active_support/core_ext/array/conversions' require 'active_support/core_ext/object/acts_like' @@ -103,6 +102,8 @@ module ActiveSupport @value.respond_to?(method, include_private) end + delegate :<=>, to: :value + protected def sum(sign, time = ::Time.current) #:nodoc: diff --git a/activesupport/lib/active_support/gem_version.rb b/activesupport/lib/active_support/gem_version.rb index 6233c45787..bc7933e38b 100644 --- a/activesupport/lib/active_support/gem_version.rb +++ b/activesupport/lib/active_support/gem_version.rb @@ -8,7 +8,7 @@ module ActiveSupport MAJOR = 4 MINOR = 2 TINY = 0 - PRE = "beta2" + PRE = "beta4" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/activesupport/lib/active_support/hash_with_indifferent_access.rb b/activesupport/lib/active_support/hash_with_indifferent_access.rb index 3d8f2d572b..1468c62151 100644 --- a/activesupport/lib/active_support/hash_with_indifferent_access.rb +++ b/activesupport/lib/active_support/hash_with_indifferent_access.rb @@ -1,4 +1,5 @@ require 'active_support/core_ext/hash/keys' +require 'active_support/core_ext/hash/reverse_merge' module ActiveSupport # Implements a hash where keys <tt>:foo</tt> and <tt>"foo"</tt> are considered diff --git a/activesupport/lib/active_support/inflector/inflections.rb b/activesupport/lib/active_support/inflector/inflections.rb index 97401ccec7..486838bd15 100644 --- a/activesupport/lib/active_support/inflector/inflections.rb +++ b/activesupport/lib/active_support/inflector/inflections.rb @@ -154,7 +154,7 @@ module ActiveSupport end end - # Add uncountable words that shouldn't be attempted inflected. + # Specifies words that are uncountable and should not be inflected. # # uncountable 'money' # uncountable 'money', 'information' diff --git a/activesupport/lib/active_support/inflector/methods.rb b/activesupport/lib/active_support/inflector/methods.rb index 0e3c8517d1..74b3a7c2a9 100644 --- a/activesupport/lib/active_support/inflector/methods.rb +++ b/activesupport/lib/active_support/inflector/methods.rb @@ -73,7 +73,7 @@ module ActiveSupport string = string.sub(/^(?:#{inflections.acronym_regex}(?=\b|[A-Z_])|\w)/) { $&.downcase } end string.gsub!(/(?:_|(\/))([a-z\d]*)/i) { "#{$1}#{inflections.acronyms[$2] || $2.capitalize}" } - string.gsub!('/', '::') + string.gsub!(/\//, '::') string end @@ -90,7 +90,7 @@ module ActiveSupport # 'SSLError'.underscore.camelize # => "SslError" def underscore(camel_cased_word) return camel_cased_word unless camel_cased_word =~ /[A-Z-]|::/ - word = camel_cased_word.to_s.gsub('::', '/') + word = camel_cased_word.to_s.gsub(/::/, '/') word.gsub!(/(?:(?<=([A-Za-z\d]))|\b)(#{inflections.acronym_regex})(?=\b|[^a-z])/) { "#{$1 && '_'}#{$2.downcase}" } word.gsub!(/([A-Z\d]+)([A-Z][a-z])/,'\1_\2') word.gsub!(/([a-z\d])([A-Z])/,'\1_\2') diff --git a/activesupport/lib/active_support/json/decoding.rb b/activesupport/lib/active_support/json/decoding.rb index 8b5fc70dee..35548f3f56 100644 --- a/activesupport/lib/active_support/json/decoding.rb +++ b/activesupport/lib/active_support/json/decoding.rb @@ -12,7 +12,7 @@ module ActiveSupport class << self # Parses a JSON string (JavaScript Object Notation) into a hash. - # See www.json.org for more info. + # See http://www.json.org for more info. # # ActiveSupport::JSON.decode("{\"team\":\"rails\",\"players\":\"36\"}") # => {"team" => "rails", "players" => "36"} diff --git a/activesupport/lib/active_support/json/encoding.rb b/activesupport/lib/active_support/json/encoding.rb index f29d42276d..c0ac5af153 100644 --- a/activesupport/lib/active_support/json/encoding.rb +++ b/activesupport/lib/active_support/json/encoding.rb @@ -13,7 +13,7 @@ module ActiveSupport module JSON # Dumps objects in JSON (JavaScript Object Notation). - # See www.json.org for more info. + # See http://www.json.org for more info. # # ActiveSupport::JSON.encode({ team: 'rails', players: '36' }) # # => "{\"team\":\"rails\",\"players\":\"36\"}" @@ -131,7 +131,7 @@ module ActiveSupport "The JSON encoder in Rails 4.1 no longer supports encoding BigDecimals as JSON numbers. Instead, " \ "the new encoder will always encode them as strings.\n\n" \ "You are seeing this error because you are trying to check the value of the related configuration, " \ - "'active_support.encode_big_decimal_as_string'. If your application depends on this option, you should " \ + "`active_support.encode_big_decimal_as_string`. If your application depends on this option, you should " \ "add the 'activesupport-json_encoder' gem to your Gemfile. For now, this option will always be true. " \ "In the future, it will be removed from Rails, so you should stop checking its value." diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb index 6cb2884fb7..a8a8de5672 100644 --- a/activesupport/lib/active_support/message_verifier.rb +++ b/activesupport/lib/active_support/message_verifier.rb @@ -1,5 +1,6 @@ require 'base64' require 'active_support/core_ext/object/blank' +require 'active_support/security_utils' module ActiveSupport # +MessageVerifier+ makes it easy to generate and verify messages which are @@ -37,9 +38,9 @@ module ActiveSupport raise InvalidSignature if signed_message.blank? data, digest = signed_message.split("--") - if data.present? && digest.present? && secure_compare(digest, generate_digest(data)) + if data.present? && digest.present? && ActiveSupport::SecurityUtils.secure_compare(digest, generate_digest(data)) begin - @serializer.load(::Base64.strict_decode64(data)) + @serializer.load(decode(data)) rescue ArgumentError => argument_error raise InvalidSignature if argument_error.message =~ %r{invalid base64} raise @@ -50,20 +51,17 @@ module ActiveSupport end def generate(value) - data = ::Base64.strict_encode64(@serializer.dump(value)) + data = encode(@serializer.dump(value)) "#{data}--#{generate_digest(data)}" end private - # constant-time comparison algorithm to prevent timing attacks - def secure_compare(a, b) - return false unless a.bytesize == b.bytesize - - l = a.unpack "C#{a.bytesize}" + def encode(data) + ::Base64.strict_encode64(data) + end - res = 0 - b.each_byte { |byte| res |= byte ^ l.shift } - res == 0 + def decode(data) + ::Base64.strict_decode64(data) end def generate_digest(data) diff --git a/activesupport/lib/active_support/multibyte/unicode.rb b/activesupport/lib/active_support/multibyte/unicode.rb index 7d45961515..7ab6293b60 100644 --- a/activesupport/lib/active_support/multibyte/unicode.rb +++ b/activesupport/lib/active_support/multibyte/unicode.rb @@ -11,7 +11,7 @@ module ActiveSupport NORMALIZATION_FORMS = [:c, :kc, :d, :kd] # The Unicode version that is supported by the implementation - UNICODE_VERSION = '6.3.0' + UNICODE_VERSION = '7.0.0' # The default normalization used for operations that require # normalization. It can be set to any of the normalizations diff --git a/activesupport/lib/active_support/notifications.rb b/activesupport/lib/active_support/notifications.rb index 325a3d75dc..b9f8e1ab2c 100644 --- a/activesupport/lib/active_support/notifications.rb +++ b/activesupport/lib/active_support/notifications.rb @@ -16,7 +16,7 @@ module ActiveSupport # render text: 'Foo' # end # - # That executes the block first and notifies all subscribers once done. + # That first executes the block and then notifies all subscribers once done. # # In the example above +render+ is the name of the event, and the rest is called # the _payload_. The payload is a mechanism that allows instrumenters to pass diff --git a/activesupport/lib/active_support/number_helper.rb b/activesupport/lib/active_support/number_helper.rb index 5ecda9593a..34439ee8be 100644 --- a/activesupport/lib/active_support/number_helper.rb +++ b/activesupport/lib/active_support/number_helper.rb @@ -272,12 +272,12 @@ module ActiveSupport # string containing an i18n scope where to find this hash. It # might have the following keys: # * *integers*: <tt>:unit</tt>, <tt>:ten</tt>, - # *<tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>, - # *<tt>:billion</tt>, <tt>:trillion</tt>, - # *<tt>:quadrillion</tt> + # <tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>, + # <tt>:billion</tt>, <tt>:trillion</tt>, + # <tt>:quadrillion</tt> # * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>, - # *<tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>, - # *<tt>:pico</tt>, <tt>:femto</tt> + # <tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>, + # <tt>:pico</tt>, <tt>:femto</tt> # * <tt>:format</tt> - Sets the format of the output string # (defaults to "%n %u"). The field types are: # * %u - The quantifier (ex.: 'thousand') 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 9ae27a896a..fb5adb574a 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 @@ -13,7 +13,7 @@ module ActiveSupport end rounded_number = NumberToRoundedConverter.convert(number, options) - format.gsub('%n', rounded_number).gsub('%u', options[:unit]) + format.gsub(/%n/, rounded_number).gsub(/%u/, options[:unit]) end private diff --git a/activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb b/activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb index eafe2844f7..1af294a03e 100644 --- a/activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_to_percentage_converter.rb @@ -5,7 +5,7 @@ module ActiveSupport def convert rounded_number = NumberToRoundedConverter.convert(number, options) - options[:format].gsub('%n', rounded_number) + options[:format].gsub(/%n/, rounded_number) end end end diff --git a/activesupport/lib/active_support/security_utils.rb b/activesupport/lib/active_support/security_utils.rb new file mode 100644 index 0000000000..64c4801179 --- /dev/null +++ b/activesupport/lib/active_support/security_utils.rb @@ -0,0 +1,20 @@ +module ActiveSupport + module SecurityUtils + # Constant time string comparison. + # + # The values compared should be of fixed length, such as strings + # that have already been processed by HMAC. This should not be used + # on variable length plaintext strings because it could leak length info + # via timing attacks. + def secure_compare(a, b) + return false unless a.bytesize == b.bytesize + + l = a.unpack "C#{a.bytesize}" + + res = 0 + b.each_byte { |byte| res |= byte ^ l.shift } + res == 0 + end + module_function :secure_compare + end +end diff --git a/activesupport/lib/active_support/test_case.rb b/activesupport/lib/active_support/test_case.rb index 4c3e77b7fd..a4ba5989b1 100644 --- a/activesupport/lib/active_support/test_case.rb +++ b/activesupport/lib/active_support/test_case.rb @@ -25,7 +25,7 @@ module ActiveSupport if test_order.nil? ActiveSupport::Deprecation.warn "You did not specify a value for the " \ - "configuration option 'active_support.test_order'. In Rails 5.0, " \ + "configuration option `active_support.test_order`. In Rails 5, " \ "the default value of this option will change from `:sorted` to " \ "`:random`.\n" \ "To disable this warning and keep the current behavior, you can add " \ diff --git a/activesupport/lib/active_support/testing/time_helpers.rb b/activesupport/lib/active_support/testing/time_helpers.rb index 1112c6e0b1..8c63815660 100644 --- a/activesupport/lib/active_support/testing/time_helpers.rb +++ b/activesupport/lib/active_support/testing/time_helpers.rb @@ -90,7 +90,7 @@ module ActiveSupport # Time.current # => Wed, 24 Nov 2004 01:04:44 EST -05:00 # end # Time.current # => Sat, 09 Nov 2013 15:34:49 EST -05:00 - def travel_to(date_or_time, &block) + def travel_to(date_or_time) if date_or_time.is_a?(Date) && !date_or_time.is_a?(DateTime) now = date_or_time.midnight.to_time else @@ -102,7 +102,7 @@ module ActiveSupport if block_given? begin - block.call + yield ensure travel_back end diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb index 4a0ed356b1..dbee145196 100644 --- a/activesupport/lib/active_support/time_with_zone.rb +++ b/activesupport/lib/active_support/time_with_zone.rb @@ -75,8 +75,8 @@ module ActiveSupport # Returns a <tt>Time.local()</tt> instance of the simultaneous time in your # system's <tt>ENV['TZ']</tt> zone. - def localtime - utc.respond_to?(:getlocal) ? utc.getlocal : utc.to_time.getlocal + def localtime(utc_offset = nil) + utc.respond_to?(:getlocal) ? utc.getlocal(utc_offset) : utc.to_time.getlocal(utc_offset) end alias_method :getlocal, :localtime @@ -201,15 +201,11 @@ module ActiveSupport end alias_method :to_formatted_s, :to_s - # Replaces <tt>%Z</tt> and <tt>%z</tt> directives with +zone+ and - # +formatted_offset+, respectively, before passing to Time#strftime, so - # that zone information is correct + # Replaces <tt>%Z</tt> directive with +zone before passing to Time#strftime, + # so that zone information is correct. def strftime(format) - format = format.gsub('%Z', zone) - .gsub('%z', formatted_offset(false)) - .gsub('%:z', formatted_offset(true)) - .gsub('%::z', formatted_offset(true) + ":00") - time.strftime(format) + format = format.gsub(/((?:\A|[^%])(?:%%)*)%Z/, "\\1#{zone}") + getlocal(utc_offset).strftime(format) end # Use the time in UTC for comparisons. diff --git a/activesupport/lib/active_support/values/unicode_tables.dat b/activesupport/lib/active_support/values/unicode_tables.dat Binary files differindex 394ee95f4b..760be4c07a 100644 --- a/activesupport/lib/active_support/values/unicode_tables.dat +++ b/activesupport/lib/active_support/values/unicode_tables.dat diff --git a/activesupport/test/autoloading_fixtures/typo.rb b/activesupport/test/autoloading_fixtures/typo.rb new file mode 100644 index 0000000000..8e047f5fd4 --- /dev/null +++ b/activesupport/test/autoloading_fixtures/typo.rb @@ -0,0 +1,2 @@ +TypO = 1 + diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb index 5a2af7f943..2b893c7cd0 100644 --- a/activesupport/test/core_ext/duration_test.rb +++ b/activesupport/test/core_ext/duration_test.rb @@ -30,7 +30,6 @@ class DurationTest < ActiveSupport::TestCase assert ActiveSupport::Duration === 1.day assert !(ActiveSupport::Duration === 1.day.to_i) assert !(ActiveSupport::Duration === 'foo') - assert !(ActiveSupport::Duration === ActiveSupport::ProxyObject.new) end def test_equals @@ -200,4 +199,16 @@ class DurationTest < ActiveSupport::TestCase def test_hash assert_equal 1.minute.hash, 60.seconds.hash end + + def test_comparable + assert_equal(-1, (0.seconds <=> 1.second)) + assert_equal(-1, (1.second <=> 1.minute)) + assert_equal(-1, (1 <=> 1.minute)) + assert_equal(0, (0.seconds <=> 0.seconds)) + assert_equal(0, (0.seconds <=> 0.minutes)) + assert_equal(0, (1.second <=> 1.second)) + assert_equal(1, (1.second <=> 0.second)) + assert_equal(1, (1.minute <=> 1.second)) + assert_equal(1, (61 <=> 1.minute)) + end end diff --git a/activesupport/test/core_ext/object/try_test.rb b/activesupport/test/core_ext/object/try_test.rb index 225c20fa36..efc6beaf02 100644 --- a/activesupport/test/core_ext/object/try_test.rb +++ b/activesupport/test/core_ext/object/try_test.rb @@ -30,10 +30,6 @@ class ObjectTryTest < ActiveSupport::TestCase assert_raise(NoMethodError) { @string.try!(method, 'llo', 'y') } end - def test_try_only_block_bang - assert_equal @string.reverse, @string.try! { |s| s.reverse } - end - def test_valid_method assert_equal 5, @string.try(:size) end @@ -59,6 +55,10 @@ class ObjectTryTest < ActiveSupport::TestCase assert_equal @string.reverse, @string.try { |s| s.reverse } end + def test_try_only_block_bang + assert_equal @string.reverse, @string.try! { |s| s.reverse } + end + def test_try_only_block_nil ran = false nil.try { ran = true } @@ -69,6 +69,10 @@ class ObjectTryTest < ActiveSupport::TestCase assert_equal @string.reverse, @string.try { reverse } end + def test_try_with_instance_eval_block_bang + assert_equal @string.reverse, @string.try! { reverse } + end + def test_try_with_private_method_bang klass = Class.new do private diff --git a/activesupport/test/core_ext/range_ext_test.rb b/activesupport/test/core_ext/range_ext_test.rb index 98c4ec6b5e..f096328cee 100644 --- a/activesupport/test/core_ext/range_ext_test.rb +++ b/activesupport/test/core_ext/range_ext_test.rb @@ -115,11 +115,11 @@ class RangeTest < ActiveSupport::TestCase def test_date_time_with_each datetime = DateTime.now - assert ((datetime - 1.hour)..datetime).each {} + assert(((datetime - 1.hour)..datetime).each {}) end def test_date_time_with_step datetime = DateTime.now - assert ((datetime - 1.hour)..datetime).step(1) {} + assert(((datetime - 1.hour)..datetime).step(1) {}) end end diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 2f4691817f..e32c178951 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -260,8 +260,24 @@ class StringInflectionsTest < ActiveSupport::TestCase end def test_remove - assert_equal "Summer", "Fast Summer".remove(/Fast /) - assert_equal "Summer", "Fast Summer".remove!(/Fast /) + original = "This is a good day to die" + assert_equal "This is a good day", original.remove(" to die") + assert_equal "This is a good day", original.remove(" to ", /die/) + assert_equal "This is a good day to die", original + end + + def test_remove_for_multiple_occurrences + original = "This is a good day to die to die" + assert_equal "This is a good day", original.remove(" to die") + assert_equal "This is a good day to die to die", original + end + + def test_remove! + original = "This is a very good day to die" + assert_equal "This is a good day to die", original.remove!(" very") + assert_equal "This is a good day to die", original + assert_equal "This is a good day", original.remove!(" to ", /die/) + assert_equal "This is a good day", original end def test_constantize @@ -404,11 +420,11 @@ class StringConversionsTest < ActiveSupport::TestCase end def test_partial_string_to_time - with_env_tz "Europe/Moscow" do + with_env_tz "Europe/Moscow" do # use timezone which does not observe DST. now = Time.now assert_equal Time.local(now.year, now.month, now.day, 23, 50), "23:50".to_time assert_equal Time.utc(now.year, now.month, now.day, 23, 50), "23:50".to_time(:utc) - assert_equal Time.local(now.year, now.month, now.day, 18, 50), "13:50 -0100".to_time + assert_equal Time.local(now.year, now.month, now.day, 17, 50), "13:50 -0100".to_time assert_equal Time.utc(now.year, now.month, now.day, 23, 50), "22:50 -0100".to_time(:utc) end end diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb index 3000da8da4..ad4062e5fe 100644 --- a/activesupport/test/core_ext/time_with_zone_test.rb +++ b/activesupport/test/core_ext/time_with_zone_test.rb @@ -79,6 +79,11 @@ class TimeWithZoneTest < ActiveSupport::TestCase assert_equal '1999-12-31 19:00:00 EST -0500', @twz.strftime('%Y-%m-%d %H:%M:%S %Z %z') end + def test_strftime_with_escaping + assert_equal '%Z %z', @twz.strftime('%%Z %%z') + assert_equal '%EST %-0500', @twz.strftime('%%%Z %%%z') + end + def test_inspect assert_equal 'Fri, 31 Dec 1999 19:00:00 EST -05:00', @twz.inspect end diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index 899bb75eae..96e9bd1e65 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -16,11 +16,16 @@ module ModuleWithConstant end class DependenciesTest < ActiveSupport::TestCase - def teardown - ActiveSupport::Dependencies.clear + include DependenciesTestHelpers + + setup do + @loaded_features_copy = $LOADED_FEATURES.dup end - include DependenciesTestHelpers + teardown do + ActiveSupport::Dependencies.clear + $LOADED_FEATURES.replace(@loaded_features_copy) + end def test_depend_on_path skip "LoadError#path does not exist" if RUBY_VERSION < '2.0.0' @@ -53,8 +58,7 @@ class DependenciesTest < ActiveSupport::TestCase assert_equal 2, ActiveSupport::Dependencies.loaded.size end ensure - Object.send(:remove_const, :ServiceOne) if Object.const_defined?(:ServiceOne) - Object.send(:remove_const, :ServiceTwo) if Object.const_defined?(:ServiceTwo) + remove_constants(:ServiceOne, :ServiceTwo) end def test_tracking_identical_loaded_files @@ -64,7 +68,7 @@ class DependenciesTest < ActiveSupport::TestCase assert_equal 1, ActiveSupport::Dependencies.loaded.size end ensure - Object.send(:remove_const, :ServiceOne) if Object.const_defined?(:ServiceOne) + remove_constants(:ServiceOne) end def test_missing_dependency_raises_missing_source_file @@ -84,8 +88,8 @@ class DependenciesTest < ActiveSupport::TestCase assert_equal 'Loading me failed, so do not add to loaded or history.', e.message assert_equal count + 1, $raises_exception_load_count - assert !ActiveSupport::Dependencies.loaded.include?(filename) - assert !ActiveSupport::Dependencies.history.include?(filename) + assert_not ActiveSupport::Dependencies.loaded.include?(filename) + assert_not ActiveSupport::Dependencies.history.include?(filename) end end end @@ -93,7 +97,6 @@ class DependenciesTest < ActiveSupport::TestCase def test_dependency_which_raises_doesnt_blindly_call_blame_file! with_loading do filename = 'dependencies/raises_exception_without_blame_file' - assert_raises(Exception) { require_dependency filename } end end @@ -101,13 +104,12 @@ class DependenciesTest < ActiveSupport::TestCase def test_warnings_should_be_enabled_on_first_load with_loading 'dependencies' do old_warnings, ActiveSupport::Dependencies.warnings_on_first_load = ActiveSupport::Dependencies.warnings_on_first_load, true - filename = "check_warnings" expanded = File.expand_path("#{File.dirname(__FILE__)}/dependencies/#{filename}") $check_warnings_load_count = 0 - assert !ActiveSupport::Dependencies.loaded.include?(expanded) - assert !ActiveSupport::Dependencies.history.include?(expanded) + assert_not ActiveSupport::Dependencies.loaded.include?(expanded) + assert_not ActiveSupport::Dependencies.history.include?(expanded) silence_warnings { require_dependency filename } assert_equal 1, $check_warnings_load_count @@ -115,7 +117,7 @@ class DependenciesTest < ActiveSupport::TestCase assert ActiveSupport::Dependencies.loaded.include?(expanded) ActiveSupport::Dependencies.clear - assert !ActiveSupport::Dependencies.loaded.include?(expanded) + assert_not ActiveSupport::Dependencies.loaded.include?(expanded) assert ActiveSupport::Dependencies.history.include?(expanded) silence_warnings { require_dependency filename } @@ -124,7 +126,7 @@ class DependenciesTest < ActiveSupport::TestCase assert ActiveSupport::Dependencies.loaded.include?(expanded) ActiveSupport::Dependencies.clear - assert !ActiveSupport::Dependencies.loaded.include?(expanded) + assert_not ActiveSupport::Dependencies.loaded.include?(expanded) assert ActiveSupport::Dependencies.history.include?(expanded) enable_warnings { require_dependency filename } @@ -157,6 +159,31 @@ class DependenciesTest < ActiveSupport::TestCase end end + def test_ensures_the_expected_constant_is_defined + with_autoloading_fixtures do + e = assert_raise(LoadError) { Typo } + assert_match %r{Unable to autoload constant Typo, expected .*activesupport/test/autoloading_fixtures/typo.rb to define it}, e.message + end + end + + def test_require_dependency_does_not_assume_any_particular_constant_is_defined + with_autoloading_fixtures do + require_dependency 'typo' + assert_equal 1, TypO + end + end + + # Regression, see https://github.com/rails/rails/issues/16468. + def test_require_dependency_interaction_with_autoloading + with_autoloading_fixtures do + require_dependency 'typo' + assert_equal 1, TypO + + e = assert_raise(LoadError) { Typo } + assert_match %r{Unable to autoload constant Typo, expected .*activesupport/test/autoloading_fixtures/typo.rb to define it}, e.message + end + end + def test_module_loading with_autoloading_fixtures do assert_kind_of Module, A @@ -178,43 +205,49 @@ class DependenciesTest < ActiveSupport::TestCase def test_directories_manifest_as_modules_unless_const_defined with_autoloading_fixtures do assert_kind_of Module, ModuleFolder - Object.__send__ :remove_const, :ModuleFolder end + ensure + remove_constants(:ModuleFolder) end def test_module_with_nested_class with_autoloading_fixtures do assert_kind_of Class, ModuleFolder::NestedClass - Object.__send__ :remove_const, :ModuleFolder end + ensure + remove_constants(:ModuleFolder) end def test_module_with_nested_inline_class with_autoloading_fixtures do assert_kind_of Class, ModuleFolder::InlineClass - Object.__send__ :remove_const, :ModuleFolder end + ensure + remove_constants(:ModuleFolder) end def test_directories_may_manifest_as_nested_classes with_autoloading_fixtures do assert_kind_of Class, ClassFolder - Object.__send__ :remove_const, :ClassFolder end + ensure + remove_constants(:ClassFolder) end def test_class_with_nested_class with_autoloading_fixtures do assert_kind_of Class, ClassFolder::NestedClass - Object.__send__ :remove_const, :ClassFolder end + ensure + remove_constants(:ClassFolder) end def test_class_with_nested_inline_class with_autoloading_fixtures do assert_kind_of Class, ClassFolder::InlineClass - Object.__send__ :remove_const, :ClassFolder end + ensure + remove_constants(:ClassFolder) end def test_class_with_nested_inline_subclass_of_parent @@ -222,8 +255,9 @@ class DependenciesTest < ActiveSupport::TestCase assert_kind_of Class, ClassFolder::ClassFolderSubclass assert_kind_of Class, ClassFolder assert_equal 'indeed', ClassFolder::ClassFolderSubclass::ConstantInClassFolder - Object.__send__ :remove_const, :ClassFolder end + ensure + remove_constants(:ClassFolder) end def test_nested_class_can_access_sibling @@ -231,16 +265,15 @@ class DependenciesTest < ActiveSupport::TestCase sibling = ModuleFolder::NestedClass.class_eval "NestedSibling" assert defined?(ModuleFolder::NestedSibling) assert_equal ModuleFolder::NestedSibling, sibling - Object.__send__ :remove_const, :ModuleFolder end + ensure + remove_constants(:ModuleFolder) end def test_doesnt_break_normal_require path = File.expand_path("../autoloading_fixtures/load_path", __FILE__) original_path = $:.dup - original_features = $".dup $:.push(path) - with_autoloading_fixtures do # The _ = assignments are to prevent warnings _ = RequiresConstant @@ -252,15 +285,13 @@ class DependenciesTest < ActiveSupport::TestCase assert defined?(LoadedConstant) end ensure - remove_constants(:RequiresConstant, :LoadedConstant, :LoadsConstant) - $".replace(original_features) + remove_constants(:RequiresConstant, :LoadedConstant) $:.replace(original_path) end def test_doesnt_break_normal_require_nested path = File.expand_path("../autoloading_fixtures/load_path", __FILE__) original_path = $:.dup - original_features = $".dup $:.push(path) with_autoloading_fixtures do @@ -275,14 +306,12 @@ class DependenciesTest < ActiveSupport::TestCase end ensure remove_constants(:RequiresConstant, :LoadedConstant, :LoadsConstant) - $".replace(original_features) $:.replace(original_path) end def test_require_returns_true_when_file_not_yet_required path = File.expand_path("../autoloading_fixtures/load_path", __FILE__) original_path = $:.dup - original_features = $".dup $:.push(path) with_loading do @@ -290,14 +319,12 @@ class DependenciesTest < ActiveSupport::TestCase end ensure remove_constants(:LoadedConstant) - $".replace(original_features) $:.replace(original_path) end def test_require_returns_true_when_file_not_yet_required_even_when_no_new_constants_added path = File.expand_path("../autoloading_fixtures/load_path", __FILE__) original_path = $:.dup - original_features = $".dup $:.push(path) with_loading do @@ -306,14 +333,12 @@ class DependenciesTest < ActiveSupport::TestCase end ensure remove_constants(:LoadedConstant) - $".replace(original_features) $:.replace(original_path) end def test_require_returns_false_when_file_already_required path = File.expand_path("../autoloading_fixtures/load_path", __FILE__) original_path = $:.dup - original_features = $".dup $:.push(path) with_loading do @@ -322,7 +347,6 @@ class DependenciesTest < ActiveSupport::TestCase end ensure remove_constants(:LoadedConstant) - $".replace(original_features) $:.replace(original_path) end @@ -330,14 +354,11 @@ class DependenciesTest < ActiveSupport::TestCase with_loading do assert_raise(LoadError) { require 'this_file_dont_exist_dude' } end - ensure - remove_constants(:LoadedConstant) end def test_load_returns_true_when_file_found path = File.expand_path("../autoloading_fixtures/load_path", __FILE__) original_path = $:.dup - original_features = $".dup $:.push(path) with_loading do @@ -346,7 +367,6 @@ class DependenciesTest < ActiveSupport::TestCase end ensure remove_constants(:LoadedConstant) - $".replace(original_features) $:.replace(original_path) end @@ -354,17 +374,16 @@ class DependenciesTest < ActiveSupport::TestCase with_loading do assert_raise(LoadError) { load 'this_file_dont_exist_dude.rb' } end - ensure - remove_constants(:LoadedConstant) end def failing_test_access_thru_and_upwards_fails with_autoloading_fixtures do - assert ! defined?(ModuleFolder) + assert_not defined?(ModuleFolder) assert_raise(NameError) { ModuleFolder::Object } assert_raise(NameError) { ModuleFolder::NestedClass::Object } - Object.__send__ :remove_const, :ModuleFolder end + ensure + remove_constants(:ModuleFolder) end def test_non_existing_const_raises_name_error_with_fully_qualified_name @@ -377,6 +396,8 @@ class DependenciesTest < ActiveSupport::TestCase assert_equal "uninitialized constant A::B::DoesNotExist", e.message assert_equal :DoesNotExist, e.name end + ensure + remove_constants(:A) end def test_smart_name_error_strings @@ -466,9 +487,9 @@ class DependenciesTest < ActiveSupport::TestCase nil_name = Module.new def nil_name.name() nil end assert !ActiveSupport::Dependencies.autoloaded?(nil_name) - - Object.class_eval { remove_const :ModuleFolder } end + ensure + remove_constants(:ModuleFolder) end def test_qualified_name_for @@ -526,6 +547,8 @@ class DependenciesTest < ActiveSupport::TestCase assert_kind_of Module, ::ModuleWithCustomConstMissing::A assert_kind_of String, ::ModuleWithCustomConstMissing::A::B end + ensure + remove_constants(:ModuleWithCustomConstMissing) end def test_const_missing_in_anonymous_modules_loads_top_level_constants @@ -534,6 +557,8 @@ class DependenciesTest < ActiveSupport::TestCase klass = Class.new.class_eval "E" assert_equal E, klass end + ensure + remove_constants(:E) end def test_const_missing_in_anonymous_modules_raises_if_the_constant_belongs_to_Object @@ -545,18 +570,22 @@ class DependenciesTest < ActiveSupport::TestCase assert_equal 'E cannot be autoloaded from an anonymous class or module', e.message assert_equal :E, e.name end + ensure + remove_constants(:E) end def test_removal_from_tree_should_be_detected with_loading 'dependencies' do c = ServiceOne ActiveSupport::Dependencies.clear - assert ! defined?(ServiceOne) + assert_not defined?(ServiceOne) e = assert_raise ArgumentError do ActiveSupport::Dependencies.load_missing_constant(c, :FakeMissing) end assert_match %r{ServiceOne has been removed from the module tree}i, e.message end + ensure + remove_constants(:ServiceOne) end def test_references_should_work @@ -565,18 +594,21 @@ class DependenciesTest < ActiveSupport::TestCase service_one_first = ServiceOne assert_equal service_one_first, c.get("ServiceOne") ActiveSupport::Dependencies.clear - assert ! defined?(ServiceOne) - + assert_not defined?(ServiceOne) service_one_second = ServiceOne assert_not_equal service_one_first, c.get("ServiceOne") assert_equal service_one_second, c.get("ServiceOne") end + ensure + remove_constants(:ServiceOne) end def test_constantize_shortcut_for_cached_constant_lookups with_loading 'dependencies' do assert_equal ServiceOne, ActiveSupport::Dependencies.constantize("ServiceOne") end + ensure + remove_constants(:ServiceOne) end def test_nested_load_error_isnt_rescued @@ -588,19 +620,20 @@ class DependenciesTest < ActiveSupport::TestCase end def test_autoload_once_paths_do_not_add_to_autoloaded_constants + old_path = ActiveSupport::Dependencies.autoload_once_paths with_autoloading_fixtures do ActiveSupport::Dependencies.autoload_once_paths = ActiveSupport::Dependencies.autoload_paths.dup - assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder") - assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass") - assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder) + assert_not ActiveSupport::Dependencies.autoloaded?("ModuleFolder") + assert_not ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass") + assert_not ActiveSupport::Dependencies.autoloaded?(ModuleFolder) 1 if ModuleFolder::NestedClass # 1 if to avoid warning - assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass) + assert_not ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass) end ensure - Object.class_eval { remove_const :ModuleFolder } - ActiveSupport::Dependencies.autoload_once_paths = [] + remove_constants(:ModuleFolder) + ActiveSupport::Dependencies.autoload_once_paths = old_path end def test_autoload_once_pathnames_do_not_add_to_autoloaded_constants @@ -609,15 +642,15 @@ class DependenciesTest < ActiveSupport::TestCase ActiveSupport::Dependencies.autoload_paths = pathnames ActiveSupport::Dependencies.autoload_once_paths = pathnames - assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder") - assert ! ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass") - assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder) + assert_not ActiveSupport::Dependencies.autoloaded?("ModuleFolder") + assert_not ActiveSupport::Dependencies.autoloaded?("ModuleFolder::NestedClass") + assert_not ActiveSupport::Dependencies.autoloaded?(ModuleFolder) 1 if ModuleFolder::NestedClass # 1 if to avoid warning - assert ! ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass) + assert_not ActiveSupport::Dependencies.autoloaded?(ModuleFolder::NestedClass) end ensure - Object.class_eval { remove_const :ModuleFolder } + remove_constants(:ModuleFolder) ActiveSupport::Dependencies.autoload_once_paths = [] end @@ -627,6 +660,8 @@ class DependenciesTest < ActiveSupport::TestCase assert_equal 10, ApplicationController assert ActiveSupport::Dependencies.autoloaded?(:ApplicationController) end + ensure + remove_constants(:ApplicationController) end def test_preexisting_constants_are_not_marked_as_autoloaded @@ -642,9 +677,8 @@ class DependenciesTest < ActiveSupport::TestCase assert ! ActiveSupport::Dependencies.autoloaded?(:E), "E shouldn't be marked autoloaded!" ActiveSupport::Dependencies.clear end - ensure - Object.class_eval { remove_const :E } + remove_constants(:E) end def test_constants_in_capitalized_nesting_marked_as_autoloaded @@ -653,6 +687,8 @@ class DependenciesTest < ActiveSupport::TestCase assert ActiveSupport::Dependencies.autoloaded?("HTML::SomeClass") end + ensure + remove_constants(:HTML) end def test_unloadable @@ -683,7 +719,7 @@ class DependenciesTest < ActiveSupport::TestCase assert_equal false, M.unloadable end ensure - Object.class_eval { remove_const :M } + remove_constants(:M) end def test_unloadable_constants_should_receive_callback @@ -694,7 +730,7 @@ class DependenciesTest < ActiveSupport::TestCase ActiveSupport::Dependencies.clear assert !defined?(C) ensure - Object.class_eval { remove_const :C } if defined?(C) + remove_constants(:C) end def test_new_contants_in_without_constants @@ -708,7 +744,7 @@ class DependenciesTest < ActiveSupport::TestCase }.map(&:to_s) assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? } ensure - Object.class_eval { remove_const :Hello } + remove_constants(:Hello) end def test_new_constants_in_with_nesting @@ -725,9 +761,7 @@ class DependenciesTest < ActiveSupport::TestCase assert_equal ["OuterAfter", "OuterBefore"], outer.sort.map(&:to_s) assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? } ensure - %w(OuterBefore Inner OuterAfter).each do |name| - Object.class_eval { remove_const name if const_defined?(name) } - end + remove_constants(:OuterBefore, :Inner, :OuterAfter) end def test_new_constants_in_module @@ -746,7 +780,7 @@ class DependenciesTest < ActiveSupport::TestCase assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? } ensure - Object.class_eval { remove_const :M } + remove_constants(:M) end def test_new_constants_in_module_using_name @@ -764,7 +798,7 @@ class DependenciesTest < ActiveSupport::TestCase assert_equal ["M::OuterAfter", "M::OuterBefore"], outer.sort assert ActiveSupport::Dependencies.constant_watch_stack.all? {|k,v| v.empty? } ensure - Object.class_eval { remove_const :M } + remove_constants(:M) end def test_new_constants_in_with_inherited_constants @@ -782,26 +816,27 @@ class DependenciesTest < ActiveSupport::TestCase def test_file_with_multiple_constants_and_require_dependency with_autoloading_fixtures do - assert ! defined?(MultipleConstantFile) - assert ! defined?(SiblingConstant) + assert_not defined?(MultipleConstantFile) + assert_not defined?(SiblingConstant) require_dependency 'multiple_constant_file' assert defined?(MultipleConstantFile) assert defined?(SiblingConstant) assert ActiveSupport::Dependencies.autoloaded?(:MultipleConstantFile) assert ActiveSupport::Dependencies.autoloaded?(:SiblingConstant) - ActiveSupport::Dependencies.clear - assert ! defined?(MultipleConstantFile) - assert ! defined?(SiblingConstant) + assert_not defined?(MultipleConstantFile) + assert_not defined?(SiblingConstant) end + ensure + remove_constants(:MultipleConstantFile, :SiblingConstant) end def test_file_with_multiple_constants_and_auto_loading with_autoloading_fixtures do - assert ! defined?(MultipleConstantFile) - assert ! defined?(SiblingConstant) + assert_not defined?(MultipleConstantFile) + assert_not defined?(SiblingConstant) assert_equal 10, MultipleConstantFile @@ -812,15 +847,17 @@ class DependenciesTest < ActiveSupport::TestCase ActiveSupport::Dependencies.clear - assert ! defined?(MultipleConstantFile) - assert ! defined?(SiblingConstant) + assert_not defined?(MultipleConstantFile) + assert_not defined?(SiblingConstant) end + ensure + remove_constants(:MultipleConstantFile, :SiblingConstant) end def test_nested_file_with_multiple_constants_and_require_dependency with_autoloading_fixtures do - assert ! defined?(ClassFolder::NestedClass) - assert ! defined?(ClassFolder::SiblingClass) + assert_not defined?(ClassFolder::NestedClass) + assert_not defined?(ClassFolder::SiblingClass) require_dependency 'class_folder/nested_class' @@ -831,15 +868,17 @@ class DependenciesTest < ActiveSupport::TestCase ActiveSupport::Dependencies.clear - assert ! defined?(ClassFolder::NestedClass) - assert ! defined?(ClassFolder::SiblingClass) + assert_not defined?(ClassFolder::NestedClass) + assert_not defined?(ClassFolder::SiblingClass) end + ensure + remove_constants(:ClassFolder) end def test_nested_file_with_multiple_constants_and_auto_loading with_autoloading_fixtures do - assert ! defined?(ClassFolder::NestedClass) - assert ! defined?(ClassFolder::SiblingClass) + assert_not defined?(ClassFolder::NestedClass) + assert_not defined?(ClassFolder::SiblingClass) assert_kind_of Class, ClassFolder::NestedClass @@ -850,9 +889,11 @@ class DependenciesTest < ActiveSupport::TestCase ActiveSupport::Dependencies.clear - assert ! defined?(ClassFolder::NestedClass) - assert ! defined?(ClassFolder::SiblingClass) + assert_not defined?(ClassFolder::NestedClass) + assert_not defined?(ClassFolder::SiblingClass) end + ensure + remove_constants(:ClassFolder) end def test_autoload_doesnt_shadow_no_method_error_with_relative_constant @@ -863,9 +904,8 @@ class DependenciesTest < ActiveSupport::TestCase assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it should have failed!" end end - ensure - Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) } + remove_constants(:RaisesNoMethodError) end def test_autoload_doesnt_shadow_no_method_error_with_absolute_constant @@ -876,9 +916,8 @@ class DependenciesTest < ActiveSupport::TestCase assert !defined?(::RaisesNoMethodError), "::RaisesNoMethodError is defined but it should have failed!" end end - ensure - Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) } + remove_constants(:RaisesNoMethodError) end def test_autoload_doesnt_shadow_error_when_mechanism_not_set_to_load @@ -894,7 +933,6 @@ class DependenciesTest < ActiveSupport::TestCase def test_autoload_doesnt_shadow_name_error with_autoloading_fixtures do - Object.send(:remove_const, :RaisesNameError) if defined?(::RaisesNameError) 2.times do e = assert_raise NameError do ::RaisesNameError::FooBarBaz.object_id @@ -909,19 +947,20 @@ class DependenciesTest < ActiveSupport::TestCase assert !defined?(::RaisesNameError), "::RaisesNameError is defined but it should have failed!" end end - ensure - Object.class_eval { remove_const :RaisesNoMethodError if const_defined?(:RaisesNoMethodError) } + remove_constants(:RaisesNameError) end def test_remove_constant_handles_double_colon_at_start Object.const_set 'DeleteMe', Module.new DeleteMe.const_set 'OrMe', Module.new ActiveSupport::Dependencies.remove_constant "::DeleteMe::OrMe" - assert ! defined?(DeleteMe::OrMe) + assert_not defined?(DeleteMe::OrMe) assert defined?(DeleteMe) ActiveSupport::Dependencies.remove_constant "::DeleteMe" - assert ! defined?(DeleteMe) + assert_not defined?(DeleteMe) + ensure + remove_constants(:DeleteMe) end def test_remove_constant_does_not_trigger_loading_autoloads @@ -931,7 +970,9 @@ class DependenciesTest < ActiveSupport::TestCase end assert_nil ActiveSupport::Dependencies.remove_constant(constant), "Kernel#autoload has been triggered by remove_constant" - assert !defined?(ShouldNotBeAutoloaded) + assert_not defined?(ShouldNotBeAutoloaded) + ensure + remove_constants(constant) end def test_remove_constant_does_not_autoload_already_removed_parents_as_a_side_effect @@ -940,11 +981,14 @@ class DependenciesTest < ActiveSupport::TestCase _ = ::A::B # assignment to silence parse-time warning "possibly useless use of :: in void context" ActiveSupport::Dependencies.remove_constant('A') ActiveSupport::Dependencies.remove_constant('A::B') - assert !defined?(A) + assert_not defined?(A) end + ensure + remove_constants(:A) end def test_load_once_constants_should_not_be_unloaded + old_path = ActiveSupport::Dependencies.autoload_once_paths with_autoloading_fixtures do ActiveSupport::Dependencies.autoload_once_paths = ActiveSupport::Dependencies.autoload_paths _ = ::A # assignment to silence parse-time warning "possibly useless use of :: in void context" @@ -953,8 +997,8 @@ class DependenciesTest < ActiveSupport::TestCase assert defined?(A) end ensure - ActiveSupport::Dependencies.autoload_once_paths = [] - Object.class_eval { remove_const :A if const_defined?(:A) } + ActiveSupport::Dependencies.autoload_once_paths = old_path + remove_constants(:A) end def test_access_unloaded_constants_for_reload @@ -966,29 +1010,45 @@ class DependenciesTest < ActiveSupport::TestCase A::B # Make sure no circular dependency error end + ensure + remove_constants(:A) end def test_autoload_once_paths_should_behave_when_recursively_loading + old_path = ActiveSupport::Dependencies.autoload_once_paths with_loading 'dependencies', 'autoloading_fixtures' do ActiveSupport::Dependencies.autoload_once_paths = [ActiveSupport::Dependencies.autoload_paths.last] - assert !defined?(CrossSiteDependency) + assert_not defined?(CrossSiteDependency) assert_nothing_raised { CrossSiteDepender.nil? } assert defined?(CrossSiteDependency) - assert !ActiveSupport::Dependencies.autoloaded?(CrossSiteDependency), + assert_not ActiveSupport::Dependencies.autoloaded?(CrossSiteDependency), "CrossSiteDependency shouldn't be marked as autoloaded!" ActiveSupport::Dependencies.clear assert defined?(CrossSiteDependency), "CrossSiteDependency shouldn't have been unloaded!" end ensure - ActiveSupport::Dependencies.autoload_once_paths = [] + ActiveSupport::Dependencies.autoload_once_paths = old_path + remove_constants(:CrossSiteDependency) end def test_hook_called_multiple_times assert_nothing_raised { ActiveSupport::Dependencies.hook! } end + def test_load_and_require_stay_private + assert Object.private_methods.include?(:load) + assert Object.private_methods.include?(:require) + + ActiveSupport::Dependencies.unhook! + + assert Object.private_methods.include?(:load) + assert Object.private_methods.include?(:require) + ensure + ActiveSupport::Dependencies.hook! + end + def test_unhook ActiveSupport::Dependencies.unhook! assert !Module.new.respond_to?(:const_missing_without_dependencies) diff --git a/activesupport/test/dependencies_test_helpers.rb b/activesupport/test/dependencies_test_helpers.rb index 9268512a97..e4d5197112 100644 --- a/activesupport/test/dependencies_test_helpers.rb +++ b/activesupport/test/dependencies_test_helpers.rb @@ -13,6 +13,7 @@ module DependenciesTestHelpers ActiveSupport::Dependencies.autoload_paths = prior_autoload_paths ActiveSupport::Dependencies.mechanism = old_mechanism ActiveSupport::Dependencies.explicitly_unloadable_constants = [] + ActiveSupport::Dependencies.clear end def with_autoloading_fixtures(&block) diff --git a/activesupport/test/hash_with_indifferent_access_test.rb b/activesupport/test/hash_with_indifferent_access_test.rb new file mode 100644 index 0000000000..843994147b --- /dev/null +++ b/activesupport/test/hash_with_indifferent_access_test.rb @@ -0,0 +1,10 @@ +require 'abstract_unit' +require 'active_support/hash_with_indifferent_access' + +class HashWithIndifferentAccessTest < ActiveSupport::TestCase + def test_reverse_merge + hash = HashWithIndifferentAccess.new key: :old_value + hash.reverse_merge! key: :new_value + assert_equal :old_value, hash[:key] + end +end
\ No newline at end of file diff --git a/activesupport/test/inflector_test.rb b/activesupport/test/inflector_test.rb index 5446c5ec3c..be68bb2e2e 100644 --- a/activesupport/test/inflector_test.rb +++ b/activesupport/test/inflector_test.rb @@ -490,8 +490,8 @@ class InflectorTest < ActiveSupport::TestCase assert_equal [], inflect.uncountables # restore all the inflections - singulars.reverse.each { |singular| inflect.singular(*singular) } - plurals.reverse.each { |plural| inflect.plural(*plural) } + singulars.reverse_each { |singular| inflect.singular(*singular) } + plurals.reverse_each { |plural| inflect.plural(*plural) } inflect.uncountable(uncountables) assert_equal singulars, inflect.singulars diff --git a/activesupport/test/json/encoding_test.rb b/activesupport/test/json/encoding_test.rb index ad358ad21d..7e976aa772 100644 --- a/activesupport/test/json/encoding_test.rb +++ b/activesupport/test/json/encoding_test.rb @@ -68,7 +68,7 @@ class TestJSONEncoding < ActiveSupport::TestCase [ 1.0/0.0, %(null) ], [ -1.0/0.0, %(null) ], [ BigDecimal('0.0')/BigDecimal('0.0'), %(null) ], - [ BigDecimal('2.5'), %("#{BigDecimal('2.5').to_s}") ]] + [ BigDecimal('2.5'), %("#{BigDecimal('2.5')}") ]] StringTests = [[ 'this is the <string>', %("this is the \\u003cstring\\u003e")], [ 'a "string" with quotes & an ampersand', %("a \\"string\\" with quotes \\u0026 an ampersand") ], diff --git a/activesupport/test/security_utils_test.rb b/activesupport/test/security_utils_test.rb new file mode 100644 index 0000000000..08d2e3baa6 --- /dev/null +++ b/activesupport/test/security_utils_test.rb @@ -0,0 +1,9 @@ +require 'abstract_unit' +require 'active_support/security_utils' + +class SecurityUtilsTest < ActiveSupport::TestCase + def test_secure_compare_should_perform_string_comparison + assert ActiveSupport::SecurityUtils.secure_compare('a', 'a') + assert !ActiveSupport::SecurityUtils.secure_compare('a', 'b') + end +end diff --git a/guides/Rakefile b/guides/Rakefile index 94d4be8c0a..824bea0b39 100644 --- a/guides/Rakefile +++ b/guides/Rakefile @@ -34,10 +34,12 @@ namespace :guides do task :help do puts <<-help -Guides are taken from the source directory, and the resulting HTML goes into the +Guides are taken from the source directory, and the result goes into the output directory. Assets are stored under files, and copied to output/files as part of the generation process. +You can generate HTML, Kindle or both formats using the `guides:generate` task. + All this process is handled via rake tasks, here's a full list of them: #{%x[rake -T]} diff --git a/guides/bug_report_templates/action_controller_gem.rb b/guides/bug_report_templates/action_controller_gem.rb index 9387e3dc1d..1f0cec1e22 100644 --- a/guides/bug_report_templates/action_controller_gem.rb +++ b/guides/bug_report_templates/action_controller_gem.rb @@ -7,8 +7,8 @@ require 'action_controller/railtie' class TestApp < Rails::Application config.root = File.dirname(__FILE__) config.session_store :cookie_store, key: 'cookie_store_key' - config.secret_token = 'secret_token' - config.secret_key_base = 'secret_key_base' + secrets.secret_token = 'secret_token' + secrets.secret_key_base = 'secret_key_base' config.logger = Logger.new($stdout) Rails.logger = config.logger diff --git a/guides/bug_report_templates/action_controller_master.rb b/guides/bug_report_templates/action_controller_master.rb index 20c64b4a85..0e51eaa0db 100644 --- a/guides/bug_report_templates/action_controller_master.rb +++ b/guides/bug_report_templates/action_controller_master.rb @@ -19,8 +19,8 @@ require 'action_controller/railtie' class TestApp < Rails::Application config.root = File.dirname(__FILE__) config.session_store :cookie_store, key: 'cookie_store_key' - config.secret_token = 'secret_token' - config.secret_key_base = 'secret_key_base' + secrets.secret_token = 'secret_token' + secrets.secret_key_base = 'secret_key_base' config.logger = Logger.new($stdout) Rails.logger = config.logger diff --git a/guides/source/3_0_release_notes.md b/guides/source/3_0_release_notes.md index 46be2613ab..e985f1ab4b 100644 --- a/guides/source/3_0_release_notes.md +++ b/guides/source/3_0_release_notes.md @@ -138,7 +138,7 @@ More Information: - [Rails Edge Architecture](http://yehudakatz.com/2009/06/11/r [Arel](http://github.com/brynary/arel) (or Active Relation) has been taken on as the underpinnings of Active Record and is now required for Rails. Arel provides an SQL abstraction that simplifies out Active Record and provides the underpinnings for the relation functionality in Active Record. -More information: - [Why I wrote Arel](http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/.) +More information: - [Why I wrote Arel](https://web.archive.org/web/20120718093140/http://magicscalingsprinkles.wordpress.com/2010/01/28/why-i-wrote-arel/) ### Mail Extraction @@ -298,7 +298,7 @@ Deprecations More Information: * [The Rails 3 Router: Rack it Up](http://yehudakatz.com/2009/12/26/the-rails-3-router-rack-it-up/) -* [Revamped Routes in Rails 3](http://rizwanreza.com/2009/12/20/revamped-routes-in-rails-3) +* [Revamped Routes in Rails 3](https://medium.com/fusion-of-thoughts/revamped-routes-in-rails-3-b6d00654e5b0) * [Generic Actions in Rails 3](http://yehudakatz.com/2009/12/20/generic-actions-in-rails-3/) diff --git a/guides/source/4_1_release_notes.md b/guides/source/4_1_release_notes.md index 52a5acb75e..c7877a9cb5 100644 --- a/guides/source/4_1_release_notes.md +++ b/guides/source/4_1_release_notes.md @@ -136,7 +136,7 @@ end ### Action Mailer Previews -Action Mailer previews provide a way to visually see how emails look by visiting +Action Mailer previews provide a way to see how emails look by visiting a special URL that renders them. You implement a preview class whose methods return the mail object you'd like diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index a598c7c319..87a4f8b463 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -10,14 +10,11 @@ Highlights in Rails 4.2: These release notes cover only the major changes. To learn about various bug fixes and changes, please refer to the change logs or check out the [list of -commits](https://github.com/rails/rails/commits/master) in the main Rails +commits](https://github.com/rails/rails/commits/4-2-stable) in the main Rails repository on GitHub. -------------------------------------------------------------------------------- -NOTE: This document is a work in progress, please help to improve this by sending -a [pull request](https://github.com/rails/rails/edit/master/guides/source/4_2_release_notes.md). - Upgrading to Rails 4.2 ---------------------- @@ -49,31 +46,31 @@ bog down the controller or model. The new GlobalID library makes it easy to pass Active Record objects to jobs by serializing them in a generic form. This means you no longer have to manually pack and unpack your Active Records by passing ids. Just give the job the -straight Active Record object, and it'll serialize it using GlobalID, and -deserialize it at run time. +Active Record object, and the object will be serialized using GlobalID, and +then deserialized again at run time. ### Adequate Record -Adequate Record is a set of refactorings that make Active Record `find` and -`find_by` methods and some association queries upto 2x faster. +Adequate Record is a set of performance improvements in Active Record that makes +common `find` and `find_by` calls and some association queries up to 2x faster. -It works by caching SQL query patterns while executing the Active Record calls. -The cache helps skip parts of the computation involved in the transformation of -the calls into SQL queries. More details in [Aaron Patterson's -post](http://tenderlovemaking.com/2014/02/19/adequaterecord-pro-like-activerecord.html). +It works by caching common SQL queries as prepared statements and reusing them +on similar calls, skipping most of the query-generation work on subsequent +calls. For more details, please refer to [Aaron Patterson's blog post](http://tenderlovemaking.com/2014/02/19/adequaterecord-pro-like-activerecord.html). -Nothing special has to be done to activate this feature. Most `find` and -`find_by` calls and association queries will use it automatically. Examples: +Active Record will automatically take advantage of this feature on the supported +operations without any user involvement and code changes. Here are some examples +of the supported operations: ```ruby -Post.find 1 # caches query pattern -Post.find 2 # uses the cached pattern +Post.find 1 # First call will generate and cache the prepared statement +Post.find 2 # Second call will reuse the cached statement -Post.find_by_title 'first post' # caches query pattern -Post.find_by_title 'second post' # uses the cached pattern +Post.find_by_title 'first post' +Post.find_by_title 'second post' -post.comments # caches query pattern -post.comments(true) # uses cached pattern +post.comments +post.comments(true) ``` The caching is not used in the following scenarios: @@ -88,7 +85,7 @@ The caching is not used in the following scenarios: Post.find [1,2] ``` -- `find_by` with sql fragments: +- `find_by` with SQL fragments: ```ruby Post.find_by "published_at < ?", 2.weeks.ago @@ -100,19 +97,18 @@ New applications generated from Rails 4.2 now come with the Web Console gem by default. Web Console is a set of debugging tools for your Rails application. It will add -an interactive console on every error page, a `console` view helper and a VT100 -compatible terminal. +an interactive console on every error page and a `console` view and controller +helper. -The interactive console on the error pages lets you execute code where the -exception originated. It's quite handy to introspect the state that led to the -error. +The interactive console on the error pages let you execute code where the +exception originated. It's quite handy being able to introspect the state that +led to the error. The `console` view helper launches an interactive console within the context of the view where it is invoked. -Finally, you can launch a VT100 terminal that runs `rails console`. If you need -to create or modify existing test data, you can do that straight from the -browser. +The `console` controller helper spawns an interactive console within the +context of the controller action it was invoked in. ### Foreign key support @@ -196,9 +192,9 @@ end Due to a [change in Rack](https://github.com/rack/rack/commit/28b014484a8ac0bbb388e7eaeeef159598ec64fc), `rails server` now listens on `localhost` instead of `0.0.0.0` by default. This should have minimal impact on the standard development workflow as both http://127.0.0.1:3000 -and http://localhost:3000 would continue to work as before on your own machine. +and http://localhost:3000 will continue to work as before on your own machine. -However, with this change you would no longer be able to access the Rails server +However, with this change you will no longer be able to access the Rails server from a different machine (e.g. your development environment is in a virtual machine and you would like to access it from the host machine), you would need to start the server with `rails server -b 0.0.0.0` to restore the old behavior. @@ -206,22 +202,6 @@ to start the server with `rails server -b 0.0.0.0` to restore the old behavior. If you do this, be sure to configure your firewall properly such that only trusted machines on your network can access your development server. -### Production logging - -The default log level in the `production` environment is now `:debug`. This -makes it consistent with the other environments, and ensures plenty of -information is available to diagnose problems. - -It can be returned to the previous level, `:info`, in the environment -configuration: - -```ruby -# config/environments/production.rb - -# Decrease the log volume. -config.log_level = :info -``` - ### HTML Sanitizer The HTML sanitizer has been replaced with a new, more robust, implementation @@ -244,10 +224,9 @@ for more detail on the changes in the new sanitizer. ### `assert_select` -`assert_select` is now based on Nokogiri, making it (TODO: betterer). - -As a result, some previously-valid selectors are now unsupported. If your -application is using any of these spellings, you will need to update them: +`assert_select` is now based on Nokogiri. As a result, some previously-valid +selectors are now unsupported. If your application is using any of these +spellings, you will need to update them: * Values in attribute selectors may need to be quoted if they contain non-alphanumeric characters. @@ -300,11 +279,24 @@ Please refer to the [Changelog][railties] for detailed changes. ### Removals +* The `--skip-action-view` option has been removed from the + app generator. ([Pull Request](https://github.com/rails/rails/pull/17042)) + * The `rails application` command has been removed without replacement. ([Pull Request](https://github.com/rails/rails/pull/11616)) ### Deprecations +* Deprecated missing `config.log_level` for production environments. + ([Pull Request](https://github.com/rails/rails/pull/16622)) + +* Deprecated `rake test:all` in favor of `rake test` as it now run all tests + in the `test` folder. + ([Pull Request](https://github.com/rails/rails/pull/17348)) + +* Deprecated `rake test:all:db` in favor of `rake test:db`. + ([Pull Request](https://github.com/rails/rails/pull/17348)) + * Deprecated `Rails::Rack::LogTailer` without replacement. ([Commit](https://github.com/rails/rails/commit/84a13e019e93efaa8994b3f8303d635a7702dbce)) @@ -316,9 +308,6 @@ Please refer to the [Changelog][railties] for detailed changes. * Added a `required` option to the model generator for associations. ([Pull Request](https://github.com/rails/rails/pull/16062)) -* Introduced an `after_bundle` callback for use in Rails templates. - ([Pull Request](https://github.com/rails/rails/pull/16359)) - * Introduced the `x` namespace for defining custom configuration options: ```ruby @@ -358,9 +347,9 @@ Please refer to the [Changelog][railties] for detailed changes. ([Pull Request](https://github.com/rails/rails/pull/16129)) -* Introduced a `--skip-gems` option in the app generator to skip gems such as - `turbolinks` and `coffee-rails` that do not have their own specific flags. - ([Commit](https://github.com/rails/rails/commit/10565895805887d4faf004a6f71219da177f78b7)) +* Introduce a `--skip-turbolinks` option in the app generator to not generate + any turbolinks integration. + ([Commit](https://github.com/rails/rails/commit/bf17c8a531bc8059d50ad731398002a3e7162a7d)) * Introduced a `bin/setup` script to enable automated setup code when bootstrapping an application. @@ -372,6 +361,9 @@ Please refer to the [Changelog][railties] for detailed changes. * Introduced an API to register new extensions for `rake notes`. ([Pull Request](https://github.com/rails/rails/pull/14379)) +* Introduced an `after_bundle` callback for use in Rails templates. + ([Pull Request](https://github.com/rails/rails/pull/16359)) + * Introduced `Rails.gem_version` as a convenience method to return `Gem::Version.new(Rails.version)`. ([Pull Request](https://github.com/rails/rails/pull/14101)) @@ -387,7 +379,8 @@ Please refer to the [Changelog][action-pack] for detailed changes. * `respond_with` and the class-level `respond_to` were removed from Rails and moved to the `responders` gem (version 2.0). Add `gem 'responders', '~> 2.0'` to your `Gemfile` to continue using these features. - ([Pull Request](https://github.com/rails/rails/pull/16526)) + ([Pull Request](https://github.com/rails/rails/pull/16526), + [More Details](http://guides.rubyonrails.org/upgrading_ruby_on_rails.html#responders)) * Removed deprecated `AbstractController::Helpers::ClassMethods::MissingHelperError` in favor of `AbstractController::Helpers::MissingHelperError`. @@ -395,6 +388,9 @@ Please refer to the [Changelog][action-pack] for detailed changes. ### Deprecations +* Deprecated the `only_path` option on `*_path` helpers. + ([Commit](https://github.com/rails/rails/commit/aa1fadd48fb40dd9396a383696134a259aa59db9)) + * Deprecated `assert_tag`, `assert_no_tag`, `find_tag` and `find_all_tag` in favor of `assert_select`. ([Commit](https://github.com/rails/rails-dom-testing/commit/b12850bc5ff23ba4b599bf2770874dd4f11bf750)) @@ -411,19 +407,18 @@ Please refer to the [Changelog][action-pack] for detailed changes. ([Commit](https://github.com/rails/rails/commit/cc26b6b7bccf0eea2e2c1a9ebdcc9d30ca7390d9)) -### Notable changes +* Deprecated support for String keys in URL helpers: -* Rails will now automatically include the template's digest in ETags. - ([Pull Request](https://github.com/rails/rails/pull/16527)) + ```ruby + # bad + Rails.application.routes.url_helpers.root_path('controller' => 'posts', 'action' => 'index') + # good + Rails.application.routes.url_helpers.root_path(controller: 'posts', action: 'index') + ``` -* `render nothing: true` or rendering a `nil` body no longer add a single - space padding to the response body. - ([Pull Request](https://github.com/rails/rails/pull/14883)) + ([Pull Request](https://github.com/rails/rails/pull/17743)) -* Introduced the `always_permitted_parameters` option to configure which - parameters are permitted globally. The default value of this configuration - is `['controller', 'action']`. - ([Pull Request](https://github.com/rails/rails/pull/15933)) +### Notable changes * The `*_filter` family methods have been removed from the documentation. Their usage is discouraged in favor of the `*_action` family methods: @@ -451,6 +446,22 @@ Please refer to the [Changelog][action-pack] for detailed changes. (Commit [1](https://github.com/rails/rails/commit/6c5f43bab8206747a8591435b2aa0ff7051ad3de), [2](https://github.com/rails/rails/commit/489a8f2a44dc9cea09154ee1ee2557d1f037c7d4)) +* `render nothing: true` or rendering a `nil` body no longer add a single + space padding to the response body. + ([Pull Request](https://github.com/rails/rails/pull/14883)) + +* Rails will now automatically include the template's digest in ETags. + ([Pull Request](https://github.com/rails/rails/pull/16527)) + +* Segments that are passed into URL helpers are now automatically escaped. + ([Commit](https://github.com/rails/rails/commit/5460591f0226a9d248b7b4f89186bd5553e7768f)) + + +* Introduced the `always_permitted_parameters` option to configure which + parameters are permitted globally. The default value of this configuration + is `['controller', 'action']`. + ([Pull Request](https://github.com/rails/rails/pull/15933)) + * Added HTTP method `MKCALENDAR` from RFC-4791 ([Pull Request](https://github.com/rails/rails/pull/15121)) @@ -458,9 +469,6 @@ Please refer to the [Changelog][action-pack] for detailed changes. and action name in the payload. ([Pull Request](https://github.com/rails/rails/pull/14137)) -* Segments that are passed into URL helpers are now automatically escaped. - ([Commit](https://github.com/rails/rails/commit/5460591f0226a9d248b7b4f89186bd5553e7768f)) - * Improved the Routing Error page with fuzzy matching for route search. ([Pull Request](https://github.com/rails/rails/pull/14619)) @@ -468,26 +476,13 @@ Please refer to the [Changelog][action-pack] for detailed changes. ([Pull Request](https://github.com/rails/rails/pull/14280)) * When the Rails server is set to serve static assets, gzip assets will now be - served if the client supports it and a pre-generated gzip file (.gz) is on disk. + served if the client supports it and a pre-generated gzip file (`.gz`) is on disk. By default the asset pipeline generates `.gz` files for all compressible assets. Serving gzip files minimizes data transfer and speeds up asset requests. Always [use a CDN](http://guides.rubyonrails.org/asset_pipeline.html#cdns) if you are serving assets from your Rails server in production. ([Pull Request](https://github.com/rails/rails/pull/16466)) -* The way `assert_select` works has changed; specifically a different library - is used to interpret css selectors, build the transient DOM that the - selectors are applied against, and to extract the data from that DOM. These - changes should only affect edge cases. Examples: - * Values in attribute selectors may need to be quoted if they contain - non-alphanumeric characters. - * DOMs built from HTML source containing invalid HTML with improperly - nested elements may differ. - * If the data selected contains entities, the value selected for comparison - used to be raw (e.g. `AT&T`), and now is evaluated - (e.g. `AT&T`). - - Action View ------------- @@ -510,16 +505,16 @@ Please refer to the [Changelog][action-view] for detailed changes. `render file: "foo/bar"`. ([Pull Request](https://github.com/rails/rails/pull/16888)) +* The form helpers no longer generate a `<div>` element with inline CSS around + the hidden fields. + ([Pull Request](https://github.com/rails/rails/pull/14738)) + * Introduced a `#{partial_name}_iteration` special local variable for use with partials that are rendered with a collection. It provides access to the current state of the iteration via the `#index`, `#size`, `#first?` and `#last?` methods. ([Pull Request](https://github.com/rails/rails/pull/7698)) -* The form helpers no longer generate a `<div>` element with inline CSS around - the hidden fields. - ([Pull Request](https://github.com/rails/rails/pull/14738)) - * Placeholder I18n follows the same convention as `label` I18n. ([Pull Request](https://github.com/rails/rails/pull/16438)) @@ -534,7 +529,7 @@ Please refer to the [Changelog][action-mailer] for detailed changes. * Deprecated `*_path` helpers in mailers. Always use `*_url` helpers instead. ([Pull Request](https://github.com/rails/rails/pull/15840)) -* Deprecated `deliver` / `deliver!` in favour of `deliver_now` / `deliver_now!`. +* Deprecated `deliver` / `deliver!` in favor of `deliver_now` / `deliver_now!`. ([Pull Request](https://github.com/rails/rails/pull/16582)) ### Notable changes @@ -575,32 +570,12 @@ Please refer to the [Changelog][active-record] for detailed changes. * Deprecated swallowing of errors inside `after_commit` and `after_rollback`. ([Pull Request](https://github.com/rails/rails/pull/16537)) -* Deprecated calling `DatabaseTasks.load_schema` without a connection. Use - `DatabaseTasks.load_schema_current` instead. - ([Commit](https://github.com/rails/rails/commit/f15cef67f75e4b52fd45655d7c6ab6b35623c608)) - -* Deprecated `Reflection#source_macro` without replacement as it is no longer - needed in Active Record. - ([Pull Request](https://github.com/rails/rails/pull/16373)) - * Deprecated broken support for automatic detection of counter caches on `has_many :through` associations. You should instead manually specify the counter cache on the `has_many` and `belongs_to` associations for the through records. ([Pull Request](https://github.com/rails/rails/pull/15754)) -* Deprecated `serialized_attributes` without replacement. - ([Pull Request](https://github.com/rails/rails/pull/15704)) - -* Deprecated returning `nil` from `column_for_attribute` when no column - exists. It will return a null object in Rails 5.0 - ([Pull Request](https://github.com/rails/rails/pull/15878)) - -* Deprecated using `.joins`, `.preload` and `.eager_load` with associations - that depends on the instance state (i.e. those defined with a scope that - takes an argument) without replacement. - ([Commit](https://github.com/rails/rails/commit/ed56e596a0467390011bc9d56d462539776adac1)) - * Deprecated passing Active Record objects to `.find` or `.exists?`. Call `#id` on the objects first. (Commit [1](https://github.com/rails/rails/commit/d92ae6ccca3bcfd73546d612efaea011270bd270), @@ -618,69 +593,95 @@ Please refer to the [Changelog][active-record] for detailed changes. ([Commit](https://github.com/rails/rails/commit/91949e48cf41af9f3e4ffba3e5eecf9b0a08bfc3)) -### Notable changes +* Deprecated calling `DatabaseTasks.load_schema` without a connection. Use + `DatabaseTasks.load_schema_current` instead. + ([Commit](https://github.com/rails/rails/commit/f15cef67f75e4b52fd45655d7c6ab6b35623c608)) -* The PostgreSQL adapter now supports the `JSONB` datatype in PostgreSQL 9.4+. - ([Pull Request](https://github.com/rails/rails/pull/16220)) +* Deprecated `sanitize_sql_hash_for_conditions` without replacement. Using a + `Relation` for performing queries and updates is the prefered API. + ([Commit](https://github.com/rails/rails/commit/d5902c9e)) -* The `#references` method in migrations now supports a `type` option for - specifying the type of the foreign key (e.g. `:uuid`). - ([Pull Request](https://github.com/rails/rails/pull/16231)) +* Deprecated `Reflection#source_macro` without replacement as it is no longer + needed in Active Record. + ([Pull Request](https://github.com/rails/rails/pull/16373)) -* Added a `:required` option to singular associations, which defines a - presence validation on the association. - ([Pull Request](https://github.com/rails/rails/pull/16056)) +* Deprecated `serialized_attributes` without replacement. + ([Pull Request](https://github.com/rails/rails/pull/15704)) -* Introduced `ActiveRecord::Base#validate!` that raises `RecordInvalid` if the - record is invalid. - ([Pull Request](https://github.com/rails/rails/pull/8639)) +* Deprecated returning `nil` from `column_for_attribute` when no column + exists. It will return a null object in Rails 5.0. + ([Pull Request](https://github.com/rails/rails/pull/15878)) -* `ActiveRecord::Base#reload` now behaves the same as `m = Model.find(m.id)`, - meaning that it no longer retains the extra attributes from custom - `select`s. - ([Pull Request](https://github.com/rails/rails/pull/15866)) +* Deprecated using `.joins`, `.preload` and `.eager_load` with associations + that depends on the instance state (i.e. those defined with a scope that + takes an argument) without replacement. + ([Commit](https://github.com/rails/rails/commit/ed56e596a0467390011bc9d56d462539776adac1)) -* Introduced the `bin/rake db:purge` task to empty the database for the - current environment. - ([Commit](https://github.com/rails/rails/commit/e2f232aba15937a4b9d14bd91e0392c6d55be58d)) +### Notable changes + +* Added a `:required` option to singular associations, which defines a + presence validation on the association. + ([Pull Request](https://github.com/rails/rails/pull/16056)) * `ActiveRecord::Dirty` now detects in-place changes to mutable values. - Serialized attributes on ActiveRecord models will no longer save when + Serialized attributes on Active Record models will no longer save when unchanged. This also works with other types such as string columns and json columns on PostgreSQL. (Pull Requests [1](https://github.com/rails/rails/pull/15674), [2](https://github.com/rails/rails/pull/15786), [3](https://github.com/rails/rails/pull/15788)) -* Added support for `#pretty_print` in `ActiveRecord::Base` objects. - ([Pull Request](https://github.com/rails/rails/pull/15172)) +* Introduced the `bin/rake db:purge` task to empty the database for the + current environment. + ([Commit](https://github.com/rails/rails/commit/e2f232aba15937a4b9d14bd91e0392c6d55be58d)) + +* Introduced `ActiveRecord::Base#validate!` that raises `RecordInvalid` if the + record is invalid. + ([Pull Request](https://github.com/rails/rails/pull/8639)) + +* Introduced `#validate` as an alias for `#valid?`. + ([Pull Request](https://github.com/rails/rails/pull/14456)) + +* `#touch` now accepts multiple attributes to be touched at once. + ([Pull Request](https://github.com/rails/rails/pull/14423)) + +* The PostgreSQL adapter now supports the `JSONB` datatype in PostgreSQL 9.4+. + ([Pull Request](https://github.com/rails/rails/pull/16220)) * PostgreSQL and SQLite adapters no longer add a default limit of 255 characters on string columns. ([Pull Request](https://github.com/rails/rails/pull/14579)) +* Added support for the `citext` column type in PostgreSQL adapter. + ([Pull Request](https://github.com/rails/rails/pull/12523)) + +* Added support for user-created range types in PostgreSQL adapter. + ([Commit](https://github.com/rails/rails/commit/4cb47167e747e8f9dc12b0ddaf82bdb68c03e032)) + * `sqlite3:///some/path` now resolves to the absolute system path `/some/path`. For relative paths, use `sqlite3:some/path` instead. (Previously, `sqlite3:///some/path` resolved to the relative path `some/path`. This behaviour was deprecated on Rails 4.1). ([Pull Request](https://github.com/rails/rails/pull/14569)) -* Introduced `#validate` as an alias for `#valid?`. - ([Pull Request](https://github.com/rails/rails/pull/14456)) - -* `#touch` now accepts multiple attributes to be touched at once. - ([Pull Request](https://github.com/rails/rails/pull/14423)) - * Added support for fractional seconds for MySQL 5.6 and above. (Pull Request [1](https://github.com/rails/rails/pull/8240), [2](https://github.com/rails/rails/pull/14359)) -* Added support for the `citext` column type in PostgreSQL adapter. - ([Pull Request](https://github.com/rails/rails/pull/12523)) +* Added support for `#pretty_print` in `ActiveRecord::Base` objects. + ([Pull Request](https://github.com/rails/rails/pull/15172)) -* Added support for user-created range types in PostgreSQL adapter. - ([Commit](https://github.com/rails/rails/commit/4cb47167e747e8f9dc12b0ddaf82bdb68c03e032)) +* `ActiveRecord::Base#reload` now behaves the same as `m = Model.find(m.id)`, + meaning that it no longer retains the extra attributes from custom + `select`s. + ([Pull Request](https://github.com/rails/rails/pull/15866)) +* `ActiveRecord::Base#reflections` now returns a hash with `String` keys instead of `Symbol` keys. + ([Pull Request](https://github.com/rails/rails/pull/17718)) + +* The `#references` method in migrations now supports a `type` option for + specifying the type of the foreign key (e.g. `:uuid`). + ([Pull Request](https://github.com/rails/rails/pull/16231)) Active Model ------------ @@ -703,6 +704,9 @@ Please refer to the [Changelog][active-model] for detailed changes. ### Notable changes +* Introduced `#validate` as an alias for `#valid?`. + ([Pull Request](https://github.com/rails/rails/pull/14456)) + * Introduced the `restore_attributes` method in `ActiveModel::Dirty` to restore the changed (dirty) attributes to their previous values. (Pull Request [1](https://github.com/rails/rails/pull/14861), @@ -716,10 +720,6 @@ Please refer to the [Changelog][active-model] for detailed changes. characters if validations are enabled. ([Pull Request](https://github.com/rails/rails/pull/15708)) -* Introduced `#validate` as an alias for `#valid?`. - ([Pull Request](https://github.com/rails/rails/pull/14456)) - - Active Support -------------- @@ -755,6 +755,10 @@ Please refer to the [Changelog][active-support] for detailed changes. to `:sorted` but will be changed to `:random` in Rails 5.0. ([Commit](https://github.com/rails/rails/commit/53e877f7d9291b2bf0b8c425f9e32ef35829f35b)) +* `Object#try` and `Object#try!` can now be used without an explicit receiver. + ([Commit](https://github.com/rails/rails/commit/5e51bdda59c9ba8e5faf86294e3e431bd45f1830), + [Pull Request](https://github.com/rails/rails/pull/17361)) + * The `travel_to` test helper now truncates the `usec` component to 0. ([Commit](https://github.com/rails/rails/commit/9f6e82ee4783e491c20f5244a613fdeb4024beb5)) diff --git a/guides/source/_welcome.html.erb b/guides/source/_welcome.html.erb index f84f1cb376..f2315bfe22 100644 --- a/guides/source/_welcome.html.erb +++ b/guides/source/_welcome.html.erb @@ -15,5 +15,5 @@ </p> <% end %> <p> - The guides for earlier releases: <a href="http://guides.rubyonrails.org/v4.1.4/">Rails 4.1.4</a>, <a href="http://guides.rubyonrails.org/v4.0.8/">Rails 4.0.8</a>, <a href="http://guides.rubyonrails.org/v3.2.19/">Rails 3.2.19</a> and <a href="http://guides.rubyonrails.org/v2.3.11/">Rails 2.3.11</a>. + The guides for earlier releases: <a href="http://guides.rubyonrails.org/v4.1.6/">Rails 4.1.6</a>, <a href="http://guides.rubyonrails.org/v4.0.10/">Rails 4.0.10</a>, <a href="http://guides.rubyonrails.org/v3.2.19/">Rails 3.2.19</a> and <a href="http://guides.rubyonrails.org/v2.3.11/">Rails 2.3.11</a>. </p> diff --git a/guides/source/action_controller_overview.md b/guides/source/action_controller_overview.md index ca1e79d3ce..1ca0d9ed55 100644 --- a/guides/source/action_controller_overview.md +++ b/guides/source/action_controller_overview.md @@ -1213,15 +1213,17 @@ Create the controller and views. * `app/views` ``` - errors/ - not_found.html.erb - unprocessable_entity.html.erb - server_error.html.erb - layouts/ - error.html.erb + errors/ + not_found.html.erb + unprocessable_entity.html.erb + server_error.html.erb + layouts/ + error.html.erb ``` -Do not forget to set the correct status code on the controller as shown before. You should avoid using the database or any complex operations because the user is already on the error page. Generating another error while on an error page could cause issues. +Do not forget to set the correct status code on the controller as shown before. + +WARNING: You should avoid using the database or any complex operations because the user is already on the error page. Generating another error while on an error page could cause issues like presenting an empty page for the users. Force HTTPS protocol -------------------- diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md index f6c974c87a..2e8ab83241 100644 --- a/guides/source/action_mailer_basics.md +++ b/guides/source/action_mailer_basics.md @@ -35,10 +35,26 @@ views. ```bash $ bin/rails generate mailer UserMailer create app/mailers/user_mailer.rb +create app/mailers/application_mailer.rb invoke erb create app/views/user_mailer +create app/views/layouts/mailer.text.erb +create app/views/layouts/mailer.html.erb invoke test_unit create test/mailers/user_mailer_test.rb +create test/mailers/previews/user_mailer_preview.rb +``` + +```ruby +# app/mailers/application_mailer.rb +class ApplicationMailer < ActionMailer::Base + default "from@example.com" + layout 'mailer' +end + +# app/mailers/user_mailer.rb +class UserMailer < ApplicationMailer +end ``` As you can see, you can generate mailers just like you use other generators with @@ -63,8 +79,7 @@ delivered via email. `app/mailers/user_mailer.rb` contains an empty mailer: ```ruby -class UserMailer < ActionMailer::Base - default from: 'from@example.com' +class UserMailer < ApplicationMailer end ``` @@ -72,7 +87,7 @@ Let's add a method called `welcome_email`, that will send an email to the user's registered email address: ```ruby -class UserMailer < ActionMailer::Base +class UserMailer < ApplicationMailer default from: 'notifications@example.com' def welcome_email(user) @@ -348,7 +363,7 @@ for the HTML version and `welcome_email.text.erb` for the plain text version. To change the default mailer view for your action you do something like: ```ruby -class UserMailer < ActionMailer::Base +class UserMailer < ApplicationMailer default from: 'notifications@example.com' def welcome_email(user) @@ -370,7 +385,7 @@ If you want more flexibility you can also pass a block and render specific templates or even render inline or text without using a template file: ```ruby -class UserMailer < ActionMailer::Base +class UserMailer < ApplicationMailer default from: 'notifications@example.com' def welcome_email(user) @@ -400,7 +415,7 @@ layout. In order to use a different file, call `layout` in your mailer: ```ruby -class UserMailer < ActionMailer::Base +class UserMailer < ApplicationMailer layout 'awesome' # use awesome.(html|text).erb as the layout end ``` @@ -412,7 +427,7 @@ You can also pass in a `layout: 'layout_name'` option to the render call inside the format block to specify different layouts for different formats: ```ruby -class UserMailer < ActionMailer::Base +class UserMailer < ApplicationMailer def welcome_email(user) mail(to: user.email) do |format| format.html { render layout: 'my_layout' } @@ -510,7 +525,7 @@ while delivering emails, you can do this using `delivery_method_options` in the mailer action. ```ruby -class UserMailer < ActionMailer::Base +class UserMailer < ApplicationMailer def welcome_email(user, company) @user = user @url = user_url(@user) @@ -532,7 +547,7 @@ option. In such cases don't forget to add the `:content_type` option. Rails will default to `text/plain` otherwise. ```ruby -class UserMailer < ActionMailer::Base +class UserMailer < ApplicationMailer def welcome_email(user, email_body) mail(to: user.email, body: email_body, @@ -562,7 +577,7 @@ mailer, and pass the email object to the mailer `receive` instance method. Here's an example: ```ruby -class UserMailer < ActionMailer::Base +class UserMailer < ApplicationMailer def receive(email) page = Page.find_by(address: email.to.first) page.emails.create( @@ -598,7 +613,7 @@ Action Mailer allows for you to specify a `before_action`, `after_action` and using instance variables set in your mailer action. ```ruby -class UserMailer < ActionMailer::Base +class UserMailer < ApplicationMailer after_action :set_delivery_options, :prevent_delivery_to_guests, :set_business_headers diff --git a/guides/source/action_view_overview.md b/guides/source/action_view_overview.md index 683e633668..f4d5bb8272 100644 --- a/guides/source/action_view_overview.md +++ b/guides/source/action_view_overview.md @@ -7,7 +7,6 @@ After reading this guide, you will know: * How best to use templates, partials, and layouts. * What helpers are provided by Action View and how to make your own. * How to use localized views. -* How to use Action View outside of Rails. -------------------------------------------------------------------------------- diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md index 9c34418fab..748467866d 100644 --- a/guides/source/active_job_basics.md +++ b/guides/source/active_job_basics.md @@ -23,7 +23,7 @@ clean-ups, to billing charges, to mailings. Anything that can be chopped up into small units of work and run in parallel, really. -The Purpose of the Active Job +The Purpose of Active Job ----------------------------- The main point is to ensure that all Rails apps will have a job infrastructure in place, even if it's in the form of an "immediate runner". We can then have @@ -41,10 +41,12 @@ This section will provide a step-by-step guide to creating a job and enqueuing i ### Create the Job Active Job provides a Rails generator to create jobs. The following will create a -job in `app/jobs`: +job in `app/jobs` (with an attached test case under `test/jobs`): ```bash $ bin/rails generate job guests_cleanup +invoke test_unit +create test/jobs/guests_cleanup_job_test.rb create app/jobs/guests_cleanup_job.rb ``` @@ -52,12 +54,8 @@ You can also create a job that will run on a specific queue: ```bash $ bin/rails generate job guests_cleanup --queue urgent -create app/jobs/guests_cleanup_job.rb ``` -As you can see, you can generate jobs just like you use other generators with -Rails. - If you don't want to use a generator, you could create your own file inside of `app/jobs`, just make sure that it inherits from `ActiveJob::Base`. @@ -78,15 +76,18 @@ end Enqueue a job like so: ```ruby -MyJob.perform_later record # Enqueue a job to be performed as soon the queueing system is free. +# Enqueue a job to be performed as soon the queueing system is free. +MyJob.perform_later record ``` ```ruby -MyJob.set(wait_until: Date.tomorrow.noon).perform_later(record) # Enqueue a job to be performed tomorrow at noon. +# Enqueue a job to be performed tomorrow at noon. +MyJob.set(wait_until: Date.tomorrow.noon).perform_later(record) ``` ```ruby -MyJob.set(wait: 1.week).perform_later(record) # Enqueue a job to be performed 1 week from now. +# Enqueue a job to be performed 1 week from now. +MyJob.set(wait: 1.week).perform_later(record) ``` That's it! @@ -103,14 +104,19 @@ Active Job has built-in adapters for multiple queueing backends (Sidekiq, Resque, Delayed Job and others). To get an up-to-date list of the adapters see the API Documentation for [ActiveJob::QueueAdapters](http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html). -### Changing the Backend +### Setting the Backend -You can easily change your queueing backend: +You can easily set your queueing backend: ```ruby -# be sure to have the adapter gem in your Gemfile and follow the adapter specific -# installation and deployment instructions -Rails.application.config.active_job.queue_adapter = :sidekiq +# config/application.rb +module YourApp + class Application < Rails::Application + # Be sure to have the adapter's gem in your Gemfile and follow + # the adapter's specific installation and deployment instructions. + config.active_job.queue_adapter = :sidekiq + end +end ``` @@ -145,19 +151,42 @@ class GuestsCleanupJob < ActiveJob::Base end # Now your job will run on queue production_low_priority on your -# production environment and on beta_low_priority on your beta +# production environment and on staging_low_priority on your staging # environment ``` -If you want more control on what queue a job will be run you can pass a :queue -option to #set: +The default queue name prefix delimiter is '_'. This can be changed by setting +`config.active_job.queue_name_delimiter` in `application.rb`: + +```ruby +# config/application.rb +module YourApp + class Application < Rails::Application + config.active_job.queue_name_prefix = Rails.env + config.active_job.queue_name_delimiter = '.' + end +end + +# app/jobs/guests_cleanup.rb +class GuestsCleanupJob < ActiveJob::Base + queue_as :low_priority + #.... +end + +# Now your job will run on queue production.low_priority on your +# production environment and on staging.low_priority on your staging +# environment +``` + +If you want more control on what queue a job will be run you can pass a `:queue` +option to `#set`: ```ruby MyJob.set(queue: :another_queue).perform_later(record) ``` -To control the queue from the job level you can pass a block to queue_as. The -block will be executed in the job context (so you can access self.arguments) +To control the queue from the job level you can pass a block to `#queue_as`. The +block will be executed in the job context (so you can access `self.arguments`) and you must return the queue name: ```ruby @@ -179,7 +208,6 @@ end ProcessVideoJob.perform_later(Video.last) ``` - NOTE: Make sure your queueing backend "listens" on your queue name. For some backends you need to specify the queues to listen to. @@ -222,7 +250,7 @@ end ``` -ActionMailer +Action Mailer ------------ One of the most common jobs in a modern web application is sending emails outside @@ -240,12 +268,13 @@ UserMailer.welcome(@user).deliver_later GlobalID -------- + Active Job supports GlobalID for parameters. This makes it possible to pass live Active Record objects to your job instead of class/id pairs, which you then have to manually deserialize. Before, jobs would look like this: ```ruby -class TrashableCleanupJob +class TrashableCleanupJob < ActiveJob::Base def perform(trashable_class, trashable_id, depth) trashable = trashable_class.constantize.find(trashable_id) trashable.cleanup(depth) @@ -256,14 +285,14 @@ end Now you can simply do: ```ruby -class TrashableCleanupJob +class TrashableCleanupJob < ActiveJob::Base def perform(trashable, depth) trashable.cleanup(depth) end end ``` -This works with any class that mixes in `ActiveModel::GlobalIdentification`, which +This works with any class that mixes in `GlobalID::Identification`, which by default has been mixed into Active Model classes. diff --git a/guides/source/active_record_basics.md b/guides/source/active_record_basics.md index ecf3483d7e..bd074d0055 100644 --- a/guides/source/active_record_basics.md +++ b/guides/source/active_record_basics.md @@ -31,7 +31,7 @@ Object Relational Mapping system. in his book _Patterns of Enterprise Application Architecture_. In Active Record, objects carry both persistent data and behavior which operates on that data. Active Record takes the opinion that ensuring -data access logic is part of the object will educate users of that +data access logic as part of the object will educate users of that object on how to write to and read from the database. ### Object Relational Mapping diff --git a/guides/source/active_record_migrations.md b/guides/source/active_record_migrations.md index 229c6ee458..c8a31fe7b8 100644 --- a/guides/source/active_record_migrations.md +++ b/guides/source/active_record_migrations.md @@ -466,7 +466,7 @@ add_foreign_key :articles, :authors ``` This adds a new foreign key to the `author_id` column of the `articles` -table. The key references the `id` column of the `articles` table. If the +table. The key references the `id` column of the `authors` table. If the column names can not be derived from the table names, you can use the `:column` and `:primary_key` options. diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md index 6c94218ef6..a2681a80e9 100644 --- a/guides/source/active_record_postgresql.md +++ b/guides/source/active_record_postgresql.md @@ -103,11 +103,6 @@ profile.settings # => {"color"=>"blue", "resolution"=>"800x600"} profile.settings = {"color" => "yellow", "resolution" => "1280x1024"} profile.save! - -## you need to call _will_change! if you are editing the store in place -profile.settings["color"] = "green" -profile.settings_will_change! -profile.save! ``` ### JSON @@ -219,7 +214,7 @@ Currently there is no special support for enumerated types. They are mapped as normal text columns: ```ruby -# db/migrate/20131220144913_create_events.rb +# db/migrate/20131220144913_create_articles.rb execute <<-SQL CREATE TYPE article_status AS ENUM ('draft', 'published'); SQL @@ -281,7 +276,7 @@ end # Usage User.create settings: "01010011" user = User.first -user.settings # => "(Paris,Champs-Élysées)" +user.settings # => "01010011" user.settings = "0xAF" user.settings # => 10101111 user.save! diff --git a/guides/source/active_record_validations.md b/guides/source/active_record_validations.md index 4dc7203ba3..546c0608ee 100644 --- a/guides/source/active_record_validations.md +++ b/guides/source/active_record_validations.md @@ -361,6 +361,8 @@ class Product < ActiveRecord::Base end ``` +Alternatively, you can require that the specified attribute does _not_ match the regular expression by using the `:without` option. + The default error message is _"is invalid"_. ### `inclusion` @@ -425,7 +427,7 @@ class Essay < ActiveRecord::Base validates :content, length: { minimum: 300, maximum: 400, - tokenizer: lambda { |str| str.scan(/\w+/) }, + tokenizer: lambda { |str| str.split(/\s+/) }, too_short: "must have at least %{count} words", too_long: "must have at most %{count} words" } @@ -531,6 +533,7 @@ validates :boolean_field_name, presence: true validates :boolean_field_name, inclusion: { in: [true, false] } validates :boolean_field_name, exclusion: { in: [nil] } ``` + By using one of these validations, you will ensure the value will NOT be `nil` which would result in a `NULL` value in most cases. @@ -704,7 +707,7 @@ we don't want names and surnames to begin with lower case. ```ruby class Person < ActiveRecord::Base validates_each :name, :surname do |record, attr, value| - record.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/ + record.errors.add(attr, 'must start with upper case') if value =~ /\A[[:lower:]]/ end end ``` diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index de42f13145..616b813817 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -1011,7 +1011,7 @@ self.default_params = { }.freeze ``` -They can be also accessed and overridden at the instance level. +They can also be accessed and overridden at the instance level. ```ruby A.x = 1 @@ -1833,16 +1833,14 @@ attribute names: ```ruby def full_messages - full_messages = [] - - each do |attribute, messages| - ... - attr_name = attribute.to_s.gsub('.', '_').humanize - attr_name = @base.class.human_attribute_name(attribute, default: attr_name) - ... - end + map { |attribute, message| full_message(attribute, message) } +end - full_messages +def full_message + ... + attr_name = attribute.to_s.tr('.', '_').humanize + attr_name = @base.class.human_attribute_name(attribute, default: attr_name) + ... end ``` diff --git a/guides/source/active_support_instrumentation.md b/guides/source/active_support_instrumentation.md index 7033947468..9dfacce560 100644 --- a/guides/source/active_support_instrumentation.md +++ b/guides/source/active_support_instrumentation.md @@ -135,7 +135,9 @@ Action Controller | `:format` | html/js/json/xml etc | | `:method` | HTTP request verb | | `:path` | Request path | +| `:status` | HTTP status code | | `:view_runtime` | Amount spent in view in ms | +| `:db_runtime` | Amount spent executing database queries in ms | ```ruby { @@ -223,11 +225,11 @@ Active Record ### sql.active_record -| Key | Value | -| ------------ | --------------------- | -| `:sql` | SQL statement | -| `:name` | Name of the operation | -| `:object_id` | `self.object_id` | +| Key | Value | +| ---------------- | --------------------- | +| `:sql` | SQL statement | +| `:name` | Name of the operation | +| `:connection_id` | `self.object_id` | INFO. The adapters will add their own data as well. diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md index c19c8e0bec..ae0f19c02a 100644 --- a/guides/source/asset_pipeline.md +++ b/guides/source/asset_pipeline.md @@ -1347,8 +1347,8 @@ config.assets.digest = true Rails 4 no longer sets default config values for Sprockets in `test.rb`, so `test.rb` now requires Sprockets configuration. The old defaults in the test -environment are: `config.assets.compile = true`, `config.assets.compress = -false`, `config.assets.debug = false` and `config.assets.digest = false`. +environment are: `config.assets.compile = true`, `config.assets.compress = false`, +`config.assets.debug = false` and `config.assets.digest = false`. The following should also be added to `Gemfile`: diff --git a/guides/source/command_line.md b/guides/source/command_line.md index b9014724bd..e72bc81766 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -61,7 +61,7 @@ With no further work, `rails server` will run our new shiny Rails app: $ cd commandsapp $ bin/rails server => Booting WEBrick -=> Rails 4.2.0 application starting in development on http://0.0.0.0:3000 +=> Rails 4.2.0 application starting in development on http://localhost:3000 => Call with -d to detach => Ctrl-C to shutdown server [2013-08-07 02:00:01] INFO WEBrick 1.3.1 @@ -79,7 +79,7 @@ The server can be run on a different port using the `-p` option. The default dev $ bin/rails server -e production -p 4000 ``` -The `-b` option binds Rails to the specified IP, by default it is 0.0.0.0. You can run a server as a daemon by passing a `-d` option. +The `-b` option binds Rails to the specified IP, by default it is localhost. You can run a server as a daemon by passing a `-d` option. ### `rails generate` @@ -368,8 +368,7 @@ Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility 'mak You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing `rake --tasks`. Each task has a description, and should help you find the thing you need. -To get the full backtrace for running rake task you can pass the option -```--trace``` to command line, for example ```rake db:create --trace```. +To get the full backtrace for running rake task you can pass the option ```--trace``` to command line, for example ```rake db:create --trace```. ```bash $ bin/rake --tasks @@ -394,16 +393,11 @@ INFO: You can also use ```rake -T``` to get the list of tasks. ```bash $ bin/rake about About your application's environment +Rails version 4.2.0 Ruby version 1.9.3 (x86_64-linux) RubyGems version 1.3.6 Rack version 1.3 -Rails version 4.2.0 JavaScript Runtime Node.js (V8) -Active Record version 4.2.0 -Action Pack version 4.2.0 -Action View version 4.2.0 -Action Mailer version 4.2.0 -Active Support version 4.2.0 Middleware Rack::Sendfile, ActionDispatch::Static, Rack::Lock, #<ActiveSupport::Cache::Strategy::LocalCache::Middleware:0x007ffd131a7c88>, Rack::Runtime, Rack::MethodOverride, ActionDispatch::RequestId, Rails::Rack::Logger, ActionDispatch::ShowExceptions, ActionDispatch::DebugExceptions, ActionDispatch::RemoteIp, ActionDispatch::Reloader, ActionDispatch::Callbacks, ActiveRecord::Migration::CheckPending, ActiveRecord::ConnectionAdapters::ConnectionManagement, ActiveRecord::QueryCache, ActionDispatch::Cookies, ActionDispatch::Session::CookieStore, ActionDispatch::Flash, ActionDispatch::ParamsParser, Rack::Head, Rack::ConditionalGet, Rack::ETag Application root /home/foobar/commandsapp Environment development @@ -413,10 +407,7 @@ Database schema version 20110805173523 ### `assets` -You can precompile the assets in `app/assets` using `rake assets:precompile`, -and remove older compiled assets using `rake assets:clean`. The `assets:clean` -task allows for rolling deploys that may still be linking to an old asset while -the new assets are being built. +You can precompile the assets in `app/assets` using `rake assets:precompile`, and remove older compiled assets using `rake assets:clean`. The `assets:clean` task allows for rolling deploys that may still be linking to an old asset while the new assets are being built. If you want to clear `public/assets` completely, you can use `rake assets:clobber`. @@ -503,7 +494,7 @@ Rails comes with a test suite called Minitest. Rails owes its stability to the u ### `tmp` -The `Rails.root/tmp` directory is, like the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for files), process id files, and cached actions. +The `Rails.root/tmp` directory is, like the *nix /tmp directory, the holding place for temporary files like sessions (if you're using a file store for sessions), process id files, and cached actions. The `tmp:` namespaced tasks will help you clear and create the `Rails.root/tmp` directory: diff --git a/guides/source/configuring.md b/guides/source/configuring.md index be0478653b..7688962c01 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -153,7 +153,7 @@ pipeline is enabled. It is set to true by default. * `config.assets.manifest` defines the full path to be used for the asset precompiler's manifest file. Defaults to a file named `manifest-<random>.json` in the `config.assets.prefix` directory within the public folder. -* `config.assets.digest` enables the use of MD5 fingerprints in asset names. Set to `true` by default in `production.rb`. +* `config.assets.digest` enables the use of MD5 fingerprints in asset names. Set to `true` by default in `production.rb` and `development.rb`. * `config.assets.debug` disables the concatenation and compression of assets. Set to `true` by default in `development.rb`. @@ -214,7 +214,7 @@ Every Rails application comes with a standard set of middleware which it uses in * `ActionDispatch::Flash` sets up the `flash` keys. Only available if `config.action_controller.session_store` is set to a value. * `ActionDispatch::ParamsParser` parses out parameters from the request into `params`. * `Rack::MethodOverride` allows the method to be overridden if `params[:_method]` is set. This is the middleware which supports the PATCH, PUT, and DELETE HTTP method types. -* `ActionDispatch::Head` converts HEAD requests to GET requests and serves them as so. +* `Rack::Head` converts HEAD requests to GET requests and serves them as so. Besides these usual middleware, you can add your own by using the `config.middleware.use` method: @@ -225,13 +225,13 @@ config.middleware.use Magical::Unicorns This will put the `Magical::Unicorns` middleware on the end of the stack. You can use `insert_before` if you wish to add a middleware before another. ```ruby -config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns +config.middleware.insert_before Rack::Head, Magical::Unicorns ``` There's also `insert_after` which will insert a middleware after another: ```ruby -config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns +config.middleware.insert_after Rack::Head, Magical::Unicorns ``` Middlewares can also be completely swapped out and replaced with others: @@ -368,20 +368,21 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`. ```ruby config.action_dispatch.rescue_responses = { - 'ActionController::RoutingError' => :not_found, - 'AbstractController::ActionNotFound' => :not_found, - 'ActionController::MethodNotAllowed' => :method_not_allowed, - 'ActionController::UnknownHttpMethod' => :method_not_allowed, - 'ActionController::NotImplemented' => :not_implemented, - 'ActionController::UnknownFormat' => :not_acceptable, - 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity, - 'ActionDispatch::ParamsParser::ParseError' => :bad_request, - 'ActionController::BadRequest' => :bad_request, - 'ActionController::ParameterMissing' => :bad_request, - 'ActiveRecord::RecordNotFound' => :not_found, - 'ActiveRecord::StaleObjectError' => :conflict, - 'ActiveRecord::RecordInvalid' => :unprocessable_entity, - 'ActiveRecord::RecordNotSaved' => :unprocessable_entity + 'ActionController::RoutingError' => :not_found, + 'AbstractController::ActionNotFound' => :not_found, + 'ActionController::MethodNotAllowed' => :method_not_allowed, + 'ActionController::UnknownHttpMethod' => :method_not_allowed, + 'ActionController::NotImplemented' => :not_implemented, + 'ActionController::UnknownFormat' => :not_acceptable, + 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity, + 'ActionController::InvalidCrossOriginRequest' => :unprocessable_entity, + 'ActionDispatch::ParamsParser::ParseError' => :bad_request, + 'ActionController::BadRequest' => :bad_request, + 'ActionController::ParameterMissing' => :bad_request, + 'ActiveRecord::RecordNotFound' => :not_found, + 'ActiveRecord::StaleObjectError' => :conflict, + 'ActiveRecord::RecordInvalid' => :unprocessable_entity, + 'ActiveRecord::RecordNotSaved' => :unprocessable_entity } ``` diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md index 302c4ca9c0..4eb360cc7a 100644 --- a/guides/source/contributing_to_ruby_on_rails.md +++ b/guides/source/contributing_to_ruby_on_rails.md @@ -193,7 +193,7 @@ Now get busy and add/edit code. You're on your branch now, so you can write what * Update the (surrounding) documentation, examples elsewhere, and the guides: whatever is affected by your contribution. -TIP: Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability of Rails will generally not be accepted. +TIP: Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability of Rails will generally not be accepted (read more about [our rationales behind this decision](https://github.com/rails/rails/pull/13771#issuecomment-32746700)). #### Follow the Coding Conventions diff --git a/guides/source/credits.html.erb b/guides/source/credits.html.erb index 8767fbecce..61ea0b44ef 100644 --- a/guides/source/credits.html.erb +++ b/guides/source/credits.html.erb @@ -40,7 +40,7 @@ Oscar Del Ben is a software engineer at <a href="http://www.wildfireapp.com/">Wi <% end %> <%= author('Tore Darell', 'toretore') do %> - Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails and unobtrusive JavaScript. His home on the Internet is his blog <a href="http://tore.darell.no">Sneaky Abstractions</a>. + Tore Darell is an independent developer based in Menton, France who specialises in cruft-free web applications using Ruby, Rails and unobtrusive JavaScript. You can follow him on <a href="http://twitter.com/toretore">Twitter</a>. <% end %> <%= author('Jeff Dean', 'zilkey') do %> diff --git a/guides/source/documents.yaml b/guides/source/documents.yaml index 4c98d3e1d5..1b838201cc 100644 --- a/guides/source/documents.yaml +++ b/guides/source/documents.yaml @@ -171,7 +171,6 @@ name: Ruby on Rails 4.2 Release Notes url: 4_2_release_notes.html description: Release notes for Rails 4.2. - work_in_progress: true - name: Ruby on Rails 4.1 Release Notes url: 4_1_release_notes.html diff --git a/guides/source/engines.md b/guides/source/engines.md index 21ac941ac0..a1f2da18ed 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -32,7 +32,7 @@ directory structure, and are both generated using the `rails plugin new` generator. The difference is that an engine is considered a "full plugin" by Rails (as indicated by the `--full` option that's passed to the generator command). We'll actually be using the `--mountable` option here, which includes -all the features of `--full`, and then some. This guide will refer to these +all the features of `--full`, and then some. This guide will refer to these "full plugins" simply as "engines" throughout. An engine **can** be a plugin, and a plugin **can** be an engine. @@ -1036,31 +1036,42 @@ functionality, especially controllers. This means that if you were to make a typical `GET` to a controller in a controller's functional test like this: ```ruby -get :index +module Blorgh + class FooControllerTest < ActionController::TestCase + def test_index + get :index + ... + end + end +end ``` It may not function correctly. This is because the application doesn't know how to route these requests to the engine unless you explicitly tell it **how**. To -do this, you must also pass the `:use_route` option as a parameter on these -requests: +do this, you must set the `@routes` instance variable to the engine's route set +in your setup code: ```ruby -get :index, use_route: :blorgh +module Blorgh + class FooControllerTest < ActionController::TestCase + setup do + @routes = Engine.routes + end + + def test_index + get :index + ... + end + end +end ``` This tells the application that you still want to perform a `GET` request to the `index` action of this controller, but you want to use the engine's route to get there, rather than the application's one. -Another way to do this is to assign the `@routes` instance variable to `Engine.routes` in your test setup: - -```ruby -setup do - @routes = Engine.routes -end -``` - -This will also ensure url helpers for the engine will work as expected in your tests. +This also ensures that the engine's URL helpers will work as expected in your +tests. Improving engine functionality ------------------------------ @@ -1155,7 +1166,7 @@ end Using `Class#class_eval` is great for simple adjustments, but for more complex class modifications, you might want to consider using [`ActiveSupport::Concern`] -(http://edgeapi.rubyonrails.org/classes/ActiveSupport/Concern.html). +(http://api.rubyonrails.org/classes/ActiveSupport/Concern.html). ActiveSupport::Concern manages load order of interlinked dependent modules and classes at run time allowing you to significantly modularize your code. diff --git a/guides/source/form_helpers.md b/guides/source/form_helpers.md index 16fa23c129..cb45e38614 100644 --- a/guides/source/form_helpers.md +++ b/guides/source/form_helpers.md @@ -506,7 +506,7 @@ As the name implies, this only generates option tags. To generate a working sele <%= collection_select(:person, :city_id, City.all, :id, :name) %> ``` -As with other helpers, if you were to use the collection_select helper on a form builder scoped to the @person object, the syntax would be: +As with other helpers, if you were to use the `collection_select` helper on a form builder scoped to the `@person` object, the syntax would be: ```erb <%= f.collection_select(:city_id, City.all, :id, :name) %> diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 1769448531..dc63ae62b1 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -101,7 +101,7 @@ If you don't have Ruby installed have a look at install Ruby on your platform. Many popular UNIX-like OSes ship with an acceptable version of SQLite3. Windows -users and others can find installation instructions at [the SQLite3 website](https://www.sqlite.org). +users and others can find installation instructions at the [SQLite3 website](https://www.sqlite.org). Verify that it is correctly installed and in your PATH: ```bash @@ -165,7 +165,7 @@ of the files and folders that Rails created by default: |config/|Configure your application's routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html).| |config.ru|Rack configuration for Rack based servers used to start the application.| |db/|Contains your current database schema, as well as the database migrations.| -|Gemfile<br>Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see [the Bundler website](http://bundler.io).| +|Gemfile<br>Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see the [Bundler website](http://bundler.io).| |lib/|Extended modules for your application.| |log/|Application log files.| |public/|The only folder seen by the world as-is. Contains static files and compiled assets.| @@ -195,8 +195,8 @@ TIP: Compiling CoffeeScript and JavaScript asset compression requires you have a JavaScript runtime available on your system, in the absence of a runtime you will see an `execjs` error during asset compilation. Usually Mac OS X and Windows come with a JavaScript runtime installed. -Rails adds the `therubyracer` gem to the generated `Gemfile` in a -commented line for new apps and you can uncomment if you need it. +Rails adds the `therubyracer` gem to the generated `Gemfile` in a +commented line for new apps and you can uncomment if you need it. `therubyrhino` is the recommended runtime for JRuby users and is added by default to the `Gemfile` in apps generated under JRuby. You can investigate all the supported runtimes at [ExecJS](https://github.com/sstephenson/execjs#readme). @@ -338,8 +338,8 @@ You can create, read, update and destroy items for a resource and these operations are referred to as _CRUD_ operations. Rails provides a `resources` method which can be used to declare a standard REST -resource. Here's what `config/routes.rb` should look like after the -_article resource_ is declared. +resource. You need to add the _article resource_ to the +`config/routes.rb` as follows: ```ruby Rails.application.routes.draw do @@ -833,7 +833,7 @@ class ArticlesController < ApplicationController A couple of things to note. We use `Article.find` to find the article we're interested in, passing in `params[:id]` to get the `:id` parameter from the -request. We also use an instance variable (prefixed by `@`) to hold a +request. We also use an instance variable (prefixed with `@`) to hold a reference to the article object. We do this because Rails will pass all instance variables to the view. @@ -1279,7 +1279,7 @@ And here's how our app looks so far: Our `edit` page looks very similar to the `new` page; in fact, they both share the same code for displaying the form. Let's remove this duplication by using a view partial. By convention, partial files are -prefixed by an underscore. +prefixed with an underscore. TIP: You can read more about partials in the [Layouts and Rendering in Rails](layouts_and_rendering.html) guide. @@ -2049,7 +2049,7 @@ command-line utility: in your web browser to explore the API documentation. TIP: To be able to generate the Rails Guides locally with the `doc:guides` rake -task you need to install the RedCloth gem. Add it to your `Gemfile` and run +task you need to install the RedCloth and Nokogiri gems. Add it to your `Gemfile` and run `bundle install` and you're ready to go. Configuration Gotchas diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md index 8bc2678d8f..0dec0e139b 100644 --- a/guides/source/rails_on_rack.md +++ b/guides/source/rails_on_rack.md @@ -277,7 +277,7 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol **`ActionDispatch::Callbacks`** -* Runs the prepare callbacks before serving the request. +* Provides callbacks to be executed before and after dispatching the request. **`ActiveRecord::Migration::CheckPending`** @@ -307,7 +307,7 @@ Much of Action Controller's functionality is implemented as Middlewares. The fol * Parses out parameters from the request into `params`. -**`ActionDispatch::Head`** +**`Rack::Head`** * Converts HEAD requests to `GET` requests and serves them as so. diff --git a/guides/source/ruby_on_rails_guides_guidelines.md b/guides/source/ruby_on_rails_guides_guidelines.md index 6206b3c715..c0438f6341 100644 --- a/guides/source/ruby_on_rails_guides_guidelines.md +++ b/guides/source/ruby_on_rails_guides_guidelines.md @@ -54,6 +54,7 @@ API Documentation Guidelines The guides and the API should be coherent and consistent where appropriate. In particular, these sections of the [API Documentation Guidelines](api_documentation_guidelines.html) also apply to the guides: * [Wording](api_documentation_guidelines.html#wording) +* [English](api_documentation_guidelines.html#english) * [Example Code](api_documentation_guidelines.html#example-code) * [Filenames](api_documentation_guidelines.html#file-names) * [Fonts](api_documentation_guidelines.html#fonts) diff --git a/guides/source/security.md b/guides/source/security.md index 125dd82666..b1c5b22338 100644 --- a/guides/source/security.md +++ b/guides/source/security.md @@ -362,7 +362,7 @@ Refer to the Injection section for countermeasures against XSS. It is _recommend **CSRF** Cross-Site Request Forgery (CSRF), also known as Cross-Site Reference Forgery (XSRF), is a gigantic attack method, it allows the attacker to do everything the administrator or Intranet user may do. As you have already seen above how CSRF works, here are a few examples of what attackers can do in the Intranet or admin interface. -A real-world example is a [router reconfiguration by CSRF](http://www.h-online.com/security/Symantec-reports-first-active-attack-on-a-DSL-router--/news/102352). The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. The e-mail claimed there was an e-card waiting for them, but it also contained an image tag that resulted in a HTTP-GET request to reconfigure the user's router (which is a popular model in Mexico). The request changed the DNS-settings so that requests to a Mexico-based banking site would be mapped to the attacker's site. Everyone who accessed the banking site through that router saw the attacker's fake web site and had their credentials stolen. +A real-world example is a [router reconfiguration by CSRF](http://www.h-online.com/security/news/item/Symantec-reports-first-active-attack-on-a-DSL-router-735883.html). The attackers sent a malicious e-mail, with CSRF in it, to Mexican users. The e-mail claimed there was an e-card waiting for them, but it also contained an image tag that resulted in a HTTP-GET request to reconfigure the user's router (which is a popular model in Mexico). The request changed the DNS-settings so that requests to a Mexico-based banking site would be mapped to the attacker's site. Everyone who accessed the banking site through that router saw the attacker's fake web site and had their credentials stolen. Another example changed Google Adsense's e-mail address and password by. If the victim was logged into Google Adsense, the administration interface for Google advertisements campaigns, an attacker could change their credentials.
 diff --git a/guides/source/testing.md b/guides/source/testing.md index b784098fbb..b4c70dfa1d 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -82,7 +82,7 @@ Each fixture is given a name followed by an indented list of colon-separated key If you are working with [associations](/association_basics.html), you can simply define a reference node between two different fixtures. Here's an example with -a belongs_to/has_many association: +a `belongs_to`/`has_many` association: ```yaml # In fixtures/categories.yml @@ -728,7 +728,7 @@ class UserFlowsTest < ActionDispatch::IntegrationTest https!(false) get "/articles/all" assert_response :success - assert assigns(:products) + assert assigns(:articles) end end ``` @@ -785,14 +785,13 @@ end Rake Tasks for Running your Tests --------------------------------- -You don't need to set up and run your tests by hand on a test-by-test basis. -Rails comes with a number of commands to help in testing. -The table below lists all commands that come along in the default Rakefile -when you initiate a Rails project. +Rails comes with a number of built-in rake tasks to help with testing. The +table below lists the commands included in the default Rakefile when a Rails +project is created. | Tasks | Description | | ----------------------- | ----------- | -| `rake test` | Runs all unit, functional and integration tests. You can also simply run `rake` as Rails will run all the tests by default | +| `rake test` | Runs all tests in the `test` folder. You can also simply run `rake` as Rails will run all the tests by default | | `rake test:controllers` | Runs all the controller tests from `test/controllers` | | `rake test:functionals` | Runs all the functional tests from `test/controllers`, `test/mailers`, and `test/functional` | | `rake test:helpers` | Runs all the helper tests from `test/helpers` | @@ -801,11 +800,10 @@ when you initiate a Rails project. | `rake test:mailers` | Runs all the mailer tests from `test/mailers` | | `rake test:models` | Runs all the model tests from `test/models` | | `rake test:units` | Runs all the unit tests from `test/models`, `test/helpers`, and `test/unit` | -| `rake test:all` | Runs all tests quickly by merging all types and not resetting db | -| `rake test:all:db` | Runs all tests quickly by merging all types and resetting db | +| `rake test:db` | Runs all tests in the `test` folder and resets the db | -Brief Note About `Minitest` +A Brief Note About Minitest ----------------------------- Ruby ships with a vast Standard Library for all common use-cases including testing. Since version 1.9, Ruby provides `Minitest`, a framework for testing. All the basic assertions such as `assert_equal` discussed above are actually defined in `Minitest::Assertions`. The classes `ActiveSupport::TestCase`, `ActionController::TestCase`, `ActionMailer::TestCase`, `ActionView::TestCase` and `ActionDispatch::IntegrationTest` - which we have been inheriting in our test classes - include `Minitest::Assertions`, allowing us to use all of the basic assertions in our tests. @@ -902,11 +900,17 @@ end Testing Routes -------------- -Like everything else in your Rails application, it is recommended that you test your routes. An example test for a route in the default `show` action of `Articles` controller above should look like: +Like everything else in your Rails application, it is recommended that you test your routes. Below are example tests for the routes of default `show` and `create` action of `Articles` controller above and it should look like: ```ruby -test "should route to article" do - assert_routing '/articles/1', {controller: "articles", action: "show", id: "1"} +class ArticleRoutesTest < ActionController::TestCase + test "should route to article" do + assert_routing '/articles/1', { controller: "articles", action: "show", id: "1" } + end + + test "should route to create article" do + assert_routing({ method: 'post', path: '/articles' }, { controller: "articles", action: "create" }) + end end ``` @@ -1043,6 +1047,68 @@ end Moreover, since the test class extends from `ActionView::TestCase`, you have access to Rails' helper methods such as `link_to` or `pluralize`. +Testing Jobs +------------ + +Since your custom jobs can be queued at different levels inside your application, +you'll need to test both jobs themselves (their behavior when they get enqueued) +and that other entities correctly enqueue them. + +### A Basic Test Case + +By default, when you generate a job, an associated test will be generated as well +under the `test/jobs` directory. Here's an example test with a billing job: + +```ruby +require 'test_helper' + +class BillingJobTest < ActiveJob::TestCase + test 'that account is charged' do + BillingJob.perform_now(account, product) + assert account.reload.charged_for?(product) + end +end +``` + +This test is pretty simple and only asserts that the job get the work done +as expected. + +By default, `ActiveJob::TestCase` will set the queue adapter to `:test` so that +your jobs are performed inline. It will also ensure that all previously performed +and enqueued jobs are cleared before any test run so you can safely assume that +no jobs have already been executed in the scope of each test. + +### Custom Assertions And Testing Jobs Inside Other Components + +Active Job ships with a bunch of custom assertions that can be used to lessen +the verbosity of tests: + +| Assertion | Purpose | +| -------------------------------------- | ------- | +| `assert_enqueued_jobs(number)` | Asserts that the number of enqueued jobs matches the given number. | +| `assert_performed_jobs(number)` | Asserts that the number of performed jobs matches the given number. | +| `assert_no_enqueued_jobs { ... }` | Asserts that no jobs have been enqueued. | +| `assert_no_performed_jobs { ... }` | Asserts that no jobs have been performed. | +| `assert_enqueued_with([args]) { ... }` | Asserts that the job passed in the block has been enqueued with the given arguments. | +| `assert_performed_with([args]) { ... }`| Asserts that the job passed in the block has been performed with the given arguments. | + +It's a good practice to ensure that your jobs correctly get enqueued or performed +wherever you invoke them (e.g. inside your controllers). This is precisely where +the custom assertions provided by Active Job are pretty useful. For instance, +within a model: + +```ruby +require 'test_helper' + +class ProductTest < ActiveSupport::TestCase + test 'billing job scheduling' do + assert_enqueued_with(job: BillingJob) do + product.charge(account) + end + end +end +``` + Other Testing Approaches ------------------------ @@ -1054,3 +1120,4 @@ The built-in `minitest` based testing is not the only way to test Rails applicat * [MiniTest::Spec Rails](https://github.com/metaskills/minitest-spec-rails), use the MiniTest::Spec DSL within your rails tests. * [Shoulda](http://www.thoughtbot.com/projects/shoulda), an extension to `test/unit` with additional helpers, macros, and assertions. * [RSpec](http://relishapp.com/rspec), a behavior-driven development framework +* [Capybara](http://jnicklas.github.com/capybara/), Acceptance test framework for web applications diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 7cc176cdcc..4ce61c282d 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -50,22 +50,10 @@ Don't forget to review the difference, to see if there were any unexpected chang Upgrading from Rails 4.1 to Rails 4.2 ------------------------------------- -NOTE: This section is a work in progress, please help to improve this by sending -a [pull request](https://github.com/rails/rails/edit/master/guides/source/upgrading_ruby_on_rails.md). - ### Web Console First, add `gem 'web-console', '~> 2.0'` to the `:development` group in your Gemfile and run `bundle install` (it won't have been included when you upgraded Rails). Once it's been installed, you can simply drop a reference to the console helper (i.e., `<%= console %>`) into any view you want to enable it for. A console will also be provided on any error page you view in your development environment. -Additionally, you can tell Rails to automatically mount a VT100-compatible console on a predetermined path by setting the appropriate configuration flags in your development config: - -```ruby -# config/environments/development.rb - -config.web_console.automount = true -config.web_console.default_mount_path = '/terminal' # Optional, defaults to /console -``` - ### Responders `respond_with` and the class-level `respond_to` methods have been extracted to the `responders` gem. To use them, simply add `gem 'responders', '~> 2.0'` to your Gemfile. Calls to `respond_with` and `respond_to` (again, at the class level) will no longer work without having included the `responders` gem in your dependencies: @@ -145,6 +133,18 @@ assigning `nil` to a serialized attribute will save it to the database as `NULL` instead of passing the `nil` value through the coder (e.g. `"null"` when using the `JSON` coder). +### Production log level + +In Rails 5, the default log level for the production environment will be changed +to `:debug` (from `:info`). To preserve the current default, add the following +line to your `production.rb`: + +```ruby +# Set to `:info` to match the current default, or set to `:debug` to opt-into +# the future default. +config.log_level = :info +``` + ### `after_bundle` in Rails templates If you have a Rails template that adds all the files in version control, it @@ -177,11 +177,11 @@ after_bundle do end ``` -### Rails Html Sanitizer +### Rails HTML Sanitizer There's a new choice for sanitizing HTML fragments in your applications. The venerable html-scanner approach is now officially being deprecated in favor of -[`Rails Html Sanitizer`](https://github.com/rails/rails-html-sanitizer). +[`Rails HTML Sanitizer`](https://github.com/rails/rails-html-sanitizer). This means the methods `sanitize`, `sanitize_css`, `strip_tags` and `strip_links` are backed by a new implementation. @@ -200,15 +200,18 @@ Read the [gem's readme](https://github.com/rails/rails-html-sanitizer) for more The documentation for `PermitScrubber` and `TargetScrubber` explains how you can gain complete control over when and how elements should be stripped. -If your application needs to old behaviour include `rails-deprecated_sanitizer` in your Gemfile: +If your application needs to use the old sanitizer implementation, include `rails-deprecated_sanitizer` in your Gemfile: ```ruby gem 'rails-deprecated_sanitizer' ``` ### Rails DOM Testing +The [`TagAssertions` module](http://api.rubyonrails.org/classes/ActionDispatch/Assertions/TagAssertions.html) (containing methods such as `assert_tag`), [has been deprecated](https://github.com/rails/rails/blob/6061472b8c310158a2a2e8e9a6b81a1aef6b60fe/actionpack/lib/action_dispatch/testing/assertions/dom.rb) in favor of the `assert_select` methods from the `SelectorAssertions` module, which has been extracted into the [rails-dom-testing gem](https://github.com/rails/rails-dom-testing). + -TODO: Mention https://github.com/rails/rails/commit/4e97d7585a2f4788b9eed98c6cdaf4bb6f2cf5ce +### Masked Authenticity Tokens +In order to mitigate SSL attacks, `form_authenticity_token` is now masked so that it varies with each request. Thus, tokens are validated by unmasking and then decrypting. As a result, any strategies for verifying requests from non-rails forms that relied on a static session CSRF token have to take this into account. Upgrading from Rails 4.0 to Rails 4.1 ------------------------------------- @@ -233,7 +236,7 @@ will now trigger CSRF protection. Switch to xhr :get, :index, format: :js ``` -to explicitly test an XmlHttpRequest. +to explicitly test an `XmlHttpRequest`. If you really mean to load JavaScript from remote `<script>` tags, skip CSRF protection on that action. @@ -418,7 +421,7 @@ class ReadOnlyModel < ActiveRecord::Base end ``` -This behaviour was never intentionally supported. Due to a change in the internals +This behavior was never intentionally supported. Due to a change in the internals of `ActiveSupport::Callbacks`, this is no longer allowed in Rails 4.1. Using a `return` statement in an inline callback block causes a `LocalJumpError` to be raised when the callback is executed. @@ -588,7 +591,7 @@ response body, you should be using `render :plain` as most browsers will escape unsafe content in the response for you. We will be deprecating the use of `render :text` in a future version. So please -start using the more precise `:plain:`, `:html`, and `:body` options instead. +start using the more precise `:plain`, `:html`, and `:body` options instead. Using `render :text` may pose a security risk, as the content is sent as `text/html`. @@ -767,7 +770,7 @@ this gem such as `whitelist_attributes` or `mass_assignment_sanitizer` options. * Rails 4.0 has deprecated `ActiveRecord::TestCase` in favor of `ActiveSupport::TestCase`. * Rails 4.0 has deprecated the old-style hash based finder API. This means that - methods which previously accepted "finder options" no longer do. + methods which previously accepted "finder options" no longer do. For example, `Book.find(:all, conditions: { name: '1984' })` has been deprecated in favor of `Book.where(name: '1984')` * All dynamic methods except for `find_by_...` and `find_by_...!` are deprecated. Here's how you can handle the changes: @@ -792,7 +795,7 @@ Rails 4.0 extracted Active Resource to its own gem. If you still need the featur * Rails 4.0 has changed how errors attach with the `ActiveModel::Validations::ConfirmationValidator`. Now when confirmation validations fail, the error will be attached to `:#{attribute}_confirmation` instead of `attribute`. -* Rails 4.0 has changed `ActiveModel::Serializers::JSON.include_root_in_json` default value to `false`. Now, Active Model Serializers and Active Record objects have the same default behaviour. This means that you can comment or remove the following option in the `config/initializers/wrap_parameters.rb` file: +* Rails 4.0 has changed `ActiveModel::Serializers::JSON.include_root_in_json` default value to `false`. Now, Active Model Serializers and Active Record objects have the same default behavior. This means that you can comment or remove the following option in the `config/initializers/wrap_parameters.rb` file: ```ruby # Disable root element in JSON by default. @@ -918,7 +921,7 @@ The order in which helpers from more than one directory are loaded has changed i ### Active Record Observer and Action Controller Sweeper -Active Record Observer and Action Controller Sweeper have been extracted to the `rails-observers` gem. You will need to add the `rails-observers` gem if you require these features. +`ActiveRecord::Observer` and `ActionController::Caching::Sweeper` have been extracted to the `rails-observers` gem. You will need to add the `rails-observers` gem if you require these features. ### sprockets-rails diff --git a/rails.gemspec b/rails.gemspec index a304b16f57..9969748a09 100644 --- a/rails.gemspec +++ b/rails.gemspec @@ -16,7 +16,7 @@ Gem::Specification.new do |s| s.email = 'david@loudthinking.com' s.homepage = 'http://www.rubyonrails.org' - s.files = ['README.md'] + Dir['guides/**/*'] + s.files = ['README.md'] + Dir['guides/**/*'] - Dir['guides/output/**/*'] s.add_dependency 'activesupport', version s.add_dependency 'actionpack', version @@ -28,5 +28,5 @@ Gem::Specification.new do |s| s.add_dependency 'railties', version s.add_dependency 'bundler', '>= 1.3.0', '< 2.0' - s.add_dependency 'sprockets-rails', '~> 3.0.0.beta1' + s.add_dependency 'sprockets-rails' end diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md index 1e1afef26d..ff6dcac465 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -1,4 +1,34 @@ -* Remove --skip-action-view option from Rails::Generators::AppBase +* Generated migrations add the appropriate foreign key constraints to + references. + + *Derek Prior* + +* Deprecate different default for `log_level` in production. + + *Godfrey Chan*, *Matthew Draper* + +* Generated `.gitignore` excludes the whole `log/` directory, not only + `*.log` files. + + *ShunsukeAida* + +* `Rails::Paths::Path.unshift` now has the same interface as `Array.unshift`. + + *Igor Kapkov* + +* Make `rake test` run all tests in test folder. + + Deprecate `rake test:all` and replace `rake test:all:db` with `rake test:db` + + *David Geukers* + +* `secret_token` is now saved in `Rails.application.secrets.secret_token` + and it falls back to the value of `config.secret_token` when it is not + present in `config/secrets.yml`. + + *Benjamin Fleischer* + +* Remove `--skip-action-view` option from `Rails::Generators::AppBase`. Fixes #17023. @@ -89,13 +119,7 @@ *Rafael Mendonça França* -* Add a generic --skip-gems options to generator - - This option is useful if users want to remove some gems like jbuilder, - turbolinks, coffee-rails, etc that don't have specific options on the - generator. - - rails new my_app --skip-gems turbolinks coffee-rails +* Add `--skip-turbolinks` option to the app generator. *Rafael Mendonça França* diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index bc966e87c6..f8bd6096f2 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -88,6 +88,7 @@ module Rails def inherited(base) super Rails.app_class = base + add_lib_to_load_path!(find_root(base.called_from)) end def instance @@ -98,6 +99,10 @@ module Rails new(initial_variable_values, &block).run_load_hooks! end + def find_root(from) + find_root_with_flag "config.ru", from, Dir.pwd + end + # Makes the +new+ method public. # # Note that Rails::Application inherits from Rails::Engine, which @@ -129,8 +134,6 @@ module Rails # are these actually used? @initial_variable_values = initial_variable_values @block = block - - add_lib_to_load_path! end # Returns true if the application is initialized. @@ -175,7 +178,7 @@ module Rails key_generator = ActiveSupport::KeyGenerator.new(secrets.secret_key_base, iterations: 1000) ActiveSupport::CachingKeyGenerator.new(key_generator) else - ActiveSupport::LegacyKeyGenerator.new(config.secret_token) + ActiveSupport::LegacyKeyGenerator.new(secrets.secret_token) end end @@ -245,7 +248,7 @@ module Rails super.merge({ "action_dispatch.parameter_filter" => config.filter_parameters, "action_dispatch.redirect_filter" => config.filter_redirect, - "action_dispatch.secret_token" => config.secret_token, + "action_dispatch.secret_token" => secrets.secret_token, "action_dispatch.secret_key_base" => secrets.secret_key_base, "action_dispatch.show_exceptions" => config.action_dispatch.show_exceptions, "action_dispatch.show_detailed_exceptions" => config.consider_all_requests_local, @@ -313,8 +316,8 @@ module Rails # are changing config.root inside your application definition or having a custom # Rails application, you will need to add lib to $LOAD_PATH on your own in case # you need to load files in lib/ during the application configuration as well. - def add_lib_to_load_path! #:nodoc: - path = File.join config.root, 'lib' + def self.add_lib_to_load_path!(root) #:nodoc: + path = File.join root, 'lib' if File.exist?(path) && !$LOAD_PATH.include?(path) $LOAD_PATH.unshift(path) end @@ -358,7 +361,7 @@ module Rails end def config #:nodoc: - @config ||= Application::Configuration.new(find_root_with_flag("config.ru", Dir.pwd)) + @config ||= Application::Configuration.new(self.class.find_root(self.class.called_from)) end def config=(configuration) #:nodoc: @@ -378,6 +381,8 @@ module Rails # Fallback to config.secret_key_base if secrets.secret_key_base isn't set secrets.secret_key_base ||= config.secret_key_base + # Fallback to config.secret_token if secrets.secret_token isn't set + secrets.secret_token ||= config.secret_token secrets end @@ -507,8 +512,13 @@ module Rails end def validate_secret_key_config! #:nodoc: - if secrets.secret_key_base.blank? && config.secret_token.blank? - raise "Missing `secret_key_base` for '#{Rails.env}' environment, set this value in `config/secrets.yml`" + if secrets.secret_key_base.blank? + ActiveSupport::Deprecation.warn "You didn't set `secret_key_base`. " + + "Read the upgrade documentation to learn more about this new config option." + + if secrets.secret_token.blank? + raise "Missing `secret_token` and `secret_key_base` for '#{Rails.env}' environment, set these values in `config/secrets.yml`" + end end end end diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb index 0f4d932749..71d3febde4 100644 --- a/railties/lib/rails/application/bootstrap.rb +++ b/railties/lib/rails/application/bootstrap.rb @@ -1,5 +1,6 @@ require "active_support/notifications" require "active_support/dependencies" +require "active_support/deprecation" require "active_support/descendants_tracker" module Rails @@ -54,6 +55,18 @@ INFO logger end + if Rails.env.production? && !config.has_explicit_log_level? + ActiveSupport::Deprecation.warn \ + "You did not specify a `log_level` in `production.rb`. Currently, " \ + "the default value for `log_level` is `:info` for the production " \ + "environment and `:debug` in all other environments. In Rails 5 " \ + "the default value will be unified to `:debug` across all " \ + "environments. To preserve the current setting, add the following " \ + "line to your `production.rb`:\n" \ + "\n" \ + " config.log_level = :info\n\n" + end + Rails.logger.level = ActiveSupport::Logger.const_get(config.log_level.to_s.upcase) end diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index 786dcee007..268ef2c7aa 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -15,7 +15,6 @@ module Rails :time_zone, :reload_classes_only_on_change, :beginning_of_week, :filter_redirect, :x - attr_writer :log_level attr_reader :encoding def initialize(*) @@ -34,6 +33,7 @@ module Rails @session_options = {} @time_zone = "UTC" @beginning_of_week = :monday + @has_explicit_log_level = false @log_level = nil @middleware = app_middleware @generators = app_generators @@ -117,8 +117,17 @@ module Rails raise e, "Cannot load `Rails.application.database_configuration`:\n#{e.message}", e.backtrace end + def has_explicit_log_level? # :nodoc: + @has_explicit_log_level + end + + def log_level=(level) + @has_explicit_log_level = !!(level) + @log_level = level + end + def log_level - @log_level ||= :debug + @log_level ||= (Rails.env.production? ? :info : :debug) end def colorize_logging diff --git a/railties/lib/rails/code_statistics.rb b/railties/lib/rails/code_statistics.rb index 0ae6d2a455..27779857b7 100644 --- a/railties/lib/rails/code_statistics.rb +++ b/railties/lib/rails/code_statistics.rb @@ -6,6 +6,7 @@ class CodeStatistics #:nodoc: 'Helper tests', 'Model tests', 'Mailer tests', + 'Job tests', 'Integration tests', 'Functional tests (old)', 'Unit tests (old)'] diff --git a/railties/lib/rails/commands/commands_tasks.rb b/railties/lib/rails/commands/commands_tasks.rb index 6cfbc70c51..8bae08e44e 100644 --- a/railties/lib/rails/commands/commands_tasks.rb +++ b/railties/lib/rails/commands/commands_tasks.rb @@ -127,7 +127,7 @@ EOT require 'rails/generators' require_application_and_environment! Rails.application.load_generators - require "rails/commands/#{command}" + require_command!(command) end # Change to the application's path if there is no config.ru file in current directory. diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb index 1a2613a8d0..9014560611 100644 --- a/railties/lib/rails/commands/dbconsole.rb +++ b/railties/lib/rails/commands/dbconsole.rb @@ -44,7 +44,7 @@ module Rails find_cmd_and_exec(['mysql', 'mysql5'], *args) - when "postgresql", "postgres", "postgis" + when /^postgres|^postgis/ ENV['PGUSER'] = config["username"] if config["username"] ENV['PGHOST'] = config["host"] if config["host"] ENV['PGPORT'] = config["port"].to_s if config["port"] @@ -74,6 +74,21 @@ module Rails find_cmd_and_exec('sqlplus', logon) + when "sqlserver" + args = [] + + args += ["-D", "#{config['database']}"] if config['database'] + args += ["-U", "#{config['username']}"] if config['username'] + args += ["-P", "#{config['password']}"] if config['password'] + + if config['host'] + host_arg = "#{config['host']}" + host_arg << ":#{config['port']}" if config['port'] + args += ["-S", host_arg] + end + + find_cmd_and_exec("sqsh", *args) + else abort "Unknown command-line client for #{config['database']}. Submit a Rails patch to add support!" end diff --git a/railties/lib/rails/commands/destroy.rb b/railties/lib/rails/commands/destroy.rb index 5479da86a0..ce26cc3fde 100644 --- a/railties/lib/rails/commands/destroy.rb +++ b/railties/lib/rails/commands/destroy.rb @@ -1,5 +1,7 @@ require 'rails/generators' +#if no argument/-h/--help is passed to rails destroy command, then +#it generates the help associated. if [nil, "-h", "--help"].include?(ARGV.first) Rails::Generators.help 'destroy' exit diff --git a/railties/lib/rails/commands/generate.rb b/railties/lib/rails/commands/generate.rb index 351c59c645..926c36b967 100644 --- a/railties/lib/rails/commands/generate.rb +++ b/railties/lib/rails/commands/generate.rb @@ -1,5 +1,7 @@ require 'rails/generators' +#if no argument/-h/--help is passed to rails generate command, then +#it generates the help associated. if [nil, "-h", "--help"].include?(ARGV.first) Rails::Generators.help 'generate' exit diff --git a/railties/lib/rails/commands/update.rb b/railties/lib/rails/commands/update.rb deleted file mode 100644 index 59fae5c337..0000000000 --- a/railties/lib/rails/commands/update.rb +++ /dev/null @@ -1,9 +0,0 @@ -require File.expand_path(File.join(File.dirname(__FILE__), '..', 'generators')) - -if ARGV.size == 0 - Rails::Generators.help - exit -end - -name = ARGV.shift -Rails::Generators.invoke name, ARGV, behavior: :skip diff --git a/railties/lib/rails/configuration.rb b/railties/lib/rails/configuration.rb index f5d7dede66..f99cec04c5 100644 --- a/railties/lib/rails/configuration.rb +++ b/railties/lib/rails/configuration.rb @@ -18,11 +18,11 @@ module Rails # This will put the <tt>Magical::Unicorns</tt> middleware on the end of the stack. # You can use +insert_before+ if you wish to add a middleware before another: # - # config.middleware.insert_before ActionDispatch::Head, Magical::Unicorns + # config.middleware.insert_before Rack::Head, Magical::Unicorns # # There's also +insert_after+ which will insert a middleware after another: # - # config.middleware.insert_after ActionDispatch::Head, Magical::Unicorns + # config.middleware.insert_after Rack::Head, Magical::Unicorns # # Middlewares can also be completely swapped out and replaced with others: # diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index dc3da1eb41..4b7da32208 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -110,8 +110,8 @@ module Rails # # == Endpoint # - # An engine can be also a rack application. It can be useful if you have a rack application that - # you would like to wrap with +Engine+ and provide some of the +Engine+'s features. + # An engine can also be a rack application. It can be useful if you have a rack application that + # you would like to wrap with +Engine+ and provide with some of the +Engine+'s features. # # To do that, use the +endpoint+ method: # @@ -351,7 +351,7 @@ module Rails base.called_from = begin call_stack = if Kernel.respond_to?(:caller_locations) - caller_locations.map(&:path) + caller_locations.map(&:absolute_path) else # Remove the line number from backtraces making sure we don't leave anything behind caller.map { |p| p.sub(/:\d+.*/, '') } @@ -364,6 +364,10 @@ module Rails super end + def find_root(from) + find_root_with_flag "lib", from + end + def endpoint(endpoint = nil) @endpoint ||= nil @endpoint = endpoint if endpoint @@ -531,7 +535,7 @@ module Rails # Define the configuration object for the engine. def config - @config ||= Engine::Configuration.new(find_root_with_flag("lib")) + @config ||= Engine::Configuration.new(self.class.find_root(self.class.called_from)) end # Load data from db/seeds.rb file. It can be used in to load engines' @@ -658,8 +662,7 @@ module Rails paths["db/migrate"].existent.any? end - def find_root_with_flag(flag, default=nil) #:nodoc: - root_path = self.class.called_from + def self.find_root_with_flag(flag, root_path, default=nil) #:nodoc: while root_path && File.directory?(root_path) && !File.exist?("#{root_path}/#{flag}") parent = File.dirname(root_path) diff --git a/railties/lib/rails/gem_version.rb b/railties/lib/rails/gem_version.rb index 4411ec33ef..8abed99f2c 100644 --- a/railties/lib/rails/gem_version.rb +++ b/railties/lib/rails/gem_version.rb @@ -8,7 +8,7 @@ module Rails MAJOR = 4 MINOR = 2 TINY = 0 - PRE = "beta2" + PRE = "beta4" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index b2c9d12996..ffdb314612 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -85,10 +85,10 @@ module Rails # environment(nil, env: "development") do # "config.autoload_paths += %W(#{config.root}/extras)" # end - def environment(data=nil, options={}, &block) + def environment(data=nil, options={}) sentinel = /class [a-z_:]+ < Rails::Application/i env_file_sentinel = /Rails\.application\.configure do/ - data = block.call if !data && block_given? + data = yield if !data && block_given? in_root do if options[:env].nil? diff --git a/railties/lib/rails/generators/actions/create_migration.rb b/railties/lib/rails/generators/actions/create_migration.rb index 682092fdf2..cffdef6ec9 100644 --- a/railties/lib/rails/generators/actions/create_migration.rb +++ b/railties/lib/rails/generators/actions/create_migration.rb @@ -39,7 +39,7 @@ module Rails protected - def on_conflict_behavior(&block) + def on_conflict_behavior options = base.options.merge(config) if identical? say_status :identical, :blue, relative_existing_migration @@ -48,7 +48,7 @@ module Rails say_status :create, :green unless pretend? ::FileUtils.rm_rf(existing_migration) - block.call + yield end elsif options[:skip] say_status :skip, :yellow diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index 0d95bb48e0..0823b0cc46 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -41,9 +41,6 @@ module Rails class_option :skip_active_record, type: :boolean, aliases: '-O', default: false, desc: 'Skip Active Record files' - class_option :skip_gems, type: :array, default: [], - desc: 'Skip the provided gems files' - class_option :skip_sprockets, type: :boolean, aliases: '-S', default: false, desc: 'Skip Sprockets files' @@ -65,6 +62,9 @@ module Rails class_option :edge, type: :boolean, default: false, desc: "Setup the #{name} with Gemfile pointing to Rails repository" + class_option :skip_turbolinks, type: :boolean, default: false, + desc: 'Skip turbolinks gem' + class_option :skip_test_unit, type: :boolean, aliases: '-T', default: false, desc: 'Skip Test::Unit files' @@ -79,7 +79,7 @@ module Rails end def initialize(*args) - @gem_filter = lambda { |gem| !options[:skip_gems].include?(gem.name) } + @gem_filter = lambda { |gem| true } @extra_entries = [] super convert_database_option_for_jruby @@ -237,8 +237,6 @@ module Rails gems = [] if options.dev? || options.edge? - gems << GemfileEntry.github('sprockets-rails', 'rails/sprockets-rails', - 'Use edge version of sprockets-rails') gems << GemfileEntry.github('sass-rails', 'rails/sass-rails', 'Use SCSS for stylesheets') else @@ -265,11 +263,11 @@ module Rails end def coffee_gemfile_entry - comment = 'Use CoffeeScript for .js.coffee assets and views' + comment = 'Use CoffeeScript for .coffee assets and views' if options.dev? || options.edge? GemfileEntry.github 'coffee-rails', 'rails/coffee-rails', comment else - GemfileEntry.version 'coffee-rails', '~> 4.0.0', comment + GemfileEntry.version 'coffee-rails', '~> 4.1.0', comment end end @@ -278,17 +276,14 @@ module Rails [] else gems = [coffee_gemfile_entry, javascript_runtime_gemfile_entry] + gems << GemfileEntry.version("#{options[:javascript]}-rails", nil, + "Use #{options[:javascript]} as the JavaScript library") - if options[:javascript] == 'jquery' - gems << GemfileEntry.version('jquery-rails', '~> 4.0.0.beta2', - 'Use jQuery as the JavaScript library') - else - gems << GemfileEntry.version("#{options[:javascript]}-rails", nil, - "Use #{options[:javascript]} as the JavaScript library") + unless options[:skip_turbolinks] + gems << GemfileEntry.version("turbolinks", nil, + "Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks") end - gems << GemfileEntry.version("turbolinks", nil, - "Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks") gems end end @@ -339,7 +334,7 @@ module Rails end def spring_install? - !options[:skip_spring] && Process.respond_to?(:fork) + !options[:skip_spring] && Process.respond_to?(:fork) && !RUBY_PLATFORM.include?("cygwin") end def run_bundle diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb index 66b17bd10e..f9b3658ae7 100644 --- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb @@ -1,8 +1,29 @@ -require 'rails/generators/erb/controller/controller_generator' +require 'rails/generators/erb' module Erb # :nodoc: module Generators # :nodoc: - class MailerGenerator < ControllerGenerator # :nodoc: + class MailerGenerator < Base # :nodoc: + argument :actions, type: :array, default: [], banner: "method method" + + def copy_view_files + view_base_path = File.join("app/views", class_path, file_name) + empty_directory view_base_path + + formats.each do |format| + layout_path = File.join("app/views/layouts", filename_with_extensions("mailer", format)) + template filename_with_extensions(:layout, format), layout_path + end + + actions.each do |action| + @action = action + + formats.each do |format| + @path = File.join(view_base_path, filename_with_extensions(action, format)) + template filename_with_extensions(:view, format), @path + end + end + end + protected def formats diff --git a/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb b/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb new file mode 100644 index 0000000000..93110e74ad --- /dev/null +++ b/railties/lib/rails/generators/erb/mailer/templates/layout.html.erb @@ -0,0 +1,5 @@ +<html> + <body> + <%%= yield %> + </body> +</html> diff --git a/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb b/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb new file mode 100644 index 0000000000..6363733e6e --- /dev/null +++ b/railties/lib/rails/generators/erb/mailer/templates/layout.text.erb @@ -0,0 +1 @@ +<%%= yield %> diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile index 38d9c4ef7c..7027312aa9 100644 --- a/railties/lib/rails/generators/rails/app/templates/Gemfile +++ b/railties/lib/rails/generators/rails/app/templates/Gemfile @@ -12,8 +12,6 @@ source 'https://rubygems.org' <% end -%> <% end -%> -gem 'rails-dom-testing', github: 'rails/rails-dom-testing' - # Use ActiveModel has_secure_password # gem 'bcrypt', '~> 3.1.7' @@ -25,15 +23,16 @@ gem 'rails-dom-testing', github: 'rails/rails-dom-testing' group :development, :test do <% unless defined?(JRUBY_VERSION) -%> - # Call 'debugger' anywhere in the code to stop execution and get a debugger console <%- if RUBY_VERSION < '2.0.0' -%> + # Call 'debugger' anywhere in the code to stop execution and get a debugger console gem 'debugger' <%- else -%> + # Call 'byebug' anywhere in the code to stop execution and get a debugger console gem 'byebug' <%- end -%> # Access an IRB console on exception pages or by using <%%= console %> in views - gem 'web-console', '~> 2.0.0.beta4' + gem 'web-console', '~> 2.0' <%- if spring_install? %> # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring' @@ -41,7 +40,7 @@ group :development, :test do <% end -%> end -<% if RUBY_PLATFORM.match(/bccwin|cygwin|emx|mingw|mswin|wince/) -%> +<% if RUBY_PLATFORM.match(/bccwin|cygwin|emx|mingw|mswin|wince|java/) -%> # Windows does not include zoneinfo files, so bundle the tzinfo-data gem -gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw] +gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby] <% end -%> diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt index 07ea09cdbd..c1a77944e8 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt +++ b/railties/lib/rails/generators/rails/app/templates/app/assets/javascripts/application.js.tt @@ -2,7 +2,7 @@ // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, -// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. +// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. diff --git a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css index a443db3401..f9cd5b3483 100644 --- a/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css +++ b/railties/lib/rails/generators/rails/app/templates/app/assets/stylesheets/application.css @@ -3,7 +3,7 @@ * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, - * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. + * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the bottom of the * compiled file so the styles you add here take precedence over styles defined in any styles diff --git a/railties/lib/rails/generators/rails/app/templates/bin/rails b/railties/lib/rails/generators/rails/app/templates/bin/rails index 6a128b95e5..80ec8080ab 100644 --- a/railties/lib/rails/generators/rails/app/templates/bin/rails +++ b/railties/lib/rails/generators/rails/app/templates/bin/rails @@ -1,3 +1,3 @@ -APP_PATH = File.expand_path('../../config/application', __FILE__) +APP_PATH = File.expand_path('../../config/application', __FILE__) require_relative '../config/boot' require 'rails/commands' diff --git a/railties/lib/rails/generators/rails/app/templates/config.ru b/railties/lib/rails/generators/rails/app/templates/config.ru index 5bc2a619e8..bd83b25412 100644 --- a/railties/lib/rails/generators/rails/app/templates/config.ru +++ b/railties/lib/rails/generators/rails/app/templates/config.ru @@ -1,4 +1,4 @@ # This file is used by Rack-based servers to start the application. -require ::File.expand_path('../config/environment', __FILE__) +require ::File.expand_path('../config/environment', __FILE__) run Rails.application diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt index 92ff0de030..ddc04d446c 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/environments/production.rb.tt @@ -45,8 +45,9 @@ Rails.application.configure do # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true - # Decrease the log volume. - # config.log_level = :info + # Use the lowest log level to ensure availability of diagnostic information + # when problems arise. + config.log_level = :debug # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore index 8775e5e235..7c6f2098b8 100644 --- a/railties/lib/rails/generators/rails/app/templates/gitignore +++ b/railties/lib/rails/generators/rails/app/templates/gitignore @@ -14,5 +14,6 @@ <% end -%> # Ignore all logfiles and tempfiles. -/log/*.log +/log/* +!/log/.keep /tmp diff --git a/railties/lib/rails/generators/rails/controller/controller_generator.rb b/railties/lib/rails/generators/rails/controller/controller_generator.rb index a48cc13ed7..df615c88b5 100644 --- a/railties/lib/rails/generators/rails/controller/controller_generator.rb +++ b/railties/lib/rails/generators/rails/controller/controller_generator.rb @@ -12,7 +12,7 @@ module Rails def add_routes unless options[:skip_routes] - actions.reverse.each do |action| + actions.reverse_each do |action| route generate_routing_code(action) end end diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js b/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js index 5bc2e1c8b5..c28e5badc6 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js +++ b/railties/lib/rails/generators/rails/plugin/templates/rails/javascripts.js @@ -2,7 +2,7 @@ // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, -// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. +// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. diff --git a/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css b/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css index a443db3401..f9cd5b3483 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css +++ b/railties/lib/rails/generators/rails/plugin/templates/rails/stylesheets.css @@ -3,7 +3,7 @@ * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, - * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. + * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the bottom of the * compiled file so the styles you add here take precedence over styles defined in any styles diff --git a/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb b/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb index 28cdfecf81..d492e68357 100644 --- a/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb +++ b/railties/lib/rails/generators/rails/plugin/templates/test/test_helper.rb @@ -4,6 +4,9 @@ ENV["RAILS_ENV"] = "test" require File.expand_path("../../<%= options[:dummy_path] -%>/config/environment.rb", __FILE__) <% unless options[:skip_active_record] -%> ActiveRecord::Migrator.migrations_paths = [File.expand_path("../../<%= options[:dummy_path] -%>/db/migrate", __FILE__)] +<% if options[:mountable] -%> +ActiveRecord::Migrator.migrations_paths << File.expand_path('../../db/migrate', __FILE__) +<% end -%> <% end -%> require "rails/test_help" diff --git a/railties/lib/rails/generators/testing/behaviour.rb b/railties/lib/rails/generators/testing/behaviour.rb index e0600d0b59..fd2ea274e1 100644 --- a/railties/lib/rails/generators/testing/behaviour.rb +++ b/railties/lib/rails/generators/testing/behaviour.rb @@ -50,7 +50,7 @@ module Rails # class AppGeneratorTest < Rails::Generators::TestCase # tests AppGenerator # destination File.expand_path("../tmp", File.dirname(__FILE__)) - # teardown :cleanup_destination_root + # setup :prepare_destination # # test "database.yml is not created when skipping Active Record" do # run_generator %w(myapp --skip-active-record) diff --git a/railties/lib/rails/info.rb b/railties/lib/rails/info.rb index 357aebf584..94ede76932 100644 --- a/railties/lib/rails/info.rb +++ b/railties/lib/rails/info.rb @@ -1,6 +1,9 @@ require "cgi" module Rails + # This module helps build the runtime properties used to display in the + # Rails::InfoController responses. Including the active Rails version, Ruby + # version, Rack version, and so on. module Info mattr_accessor :properties class << (@@properties = []) diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb index 3eb66c07af..d11804af17 100644 --- a/railties/lib/rails/paths.rb +++ b/railties/lib/rails/paths.rb @@ -167,8 +167,8 @@ module Rails @paths.concat paths end - def unshift(path) - @paths.unshift path + def unshift(*paths) + @paths.unshift(*paths) end def to_ary diff --git a/railties/lib/rails/rack/log_tailer.rb b/railties/lib/rails/rack/log_tailer.rb index bc26421a9e..46517713c9 100644 --- a/railties/lib/rails/rack/log_tailer.rb +++ b/railties/lib/rails/rack/log_tailer.rb @@ -4,7 +4,7 @@ module Rails module Rack class LogTailer def initialize(app, log = nil) - ActiveSupport::Deprecation.warn "LogTailer is deprecated and will be removed on Rails 5" + ActiveSupport::Deprecation.warn('LogTailer is deprecated and will be removed on Rails 5.') @app = app diff --git a/railties/lib/rails/source_annotation_extractor.rb b/railties/lib/rails/source_annotation_extractor.rb index 201532d299..9b058a1848 100644 --- a/railties/lib/rails/source_annotation_extractor.rb +++ b/railties/lib/rails/source_annotation_extractor.rb @@ -80,9 +80,8 @@ class SourceAnnotationExtractor # Returns a hash that maps filenames under +dir+ (recursively) to arrays # with their annotations. Only files with annotations are included. Files - # with extension +.builder+, +.rb+, +.erb+, +.haml+, +.slim+, +.css+, - # +.scss+, +.js+, +.coffee+, +.rake+, +.sass+ and +.less+ - # are taken into account. + # with extension +.builder+, +.rb+, +.rake+, +.yml+, +.yaml+, +.ruby+, + # +.css+, +.js+ and +.erb+ are taken into account. def find_in(dir) results = {} diff --git a/railties/lib/rails/tasks/statistics.rake b/railties/lib/rails/tasks/statistics.rake index b94cd244be..4f09ded31d 100644 --- a/railties/lib/rails/tasks/statistics.rake +++ b/railties/lib/rails/tasks/statistics.rake @@ -14,10 +14,11 @@ STATS_DIRECTORIES = [ %w(Helper\ tests test/helpers), %w(Model\ tests test/models), %w(Mailer\ tests test/mailers), + %w(Job\ tests test/jobs), %w(Integration\ tests test/integration), %w(Functional\ tests\ (old) test/functional), %w(Unit\ tests \ (old) test/unit) -].collect do |name, dir| +].collect do |name, dir| [ name, "#{File.dirname(Rake.application.rakefile_location)}/#{dir}" ] end.select { |name, dir| File.directory?(dir) } diff --git a/railties/lib/rails/templates/rails/mailers/email.html.erb b/railties/lib/rails/templates/rails/mailers/email.html.erb index 1dc1d70f8d..0b08a01896 100644 --- a/railties/lib/rails/templates/rails/mailers/email.html.erb +++ b/railties/lib/rails/templates/rails/mailers/email.html.erb @@ -2,6 +2,10 @@ <html><head> <meta name="viewport" content="width=device-width" /> <style type="text/css"> + html, body, iframe { + height: 100%; + } + body { margin: 0; } @@ -38,7 +42,6 @@ iframe { border: 0; width: 100%; - height: 800px; } </style> </head> diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake index 957deb8a60..0d0cfa3c6b 100644 --- a/railties/lib/rails/test_unit/testing.rake +++ b/railties/lib/rails/test_unit/testing.rake @@ -3,7 +3,7 @@ require 'rails/test_unit/sub_test_task' task default: :test -desc 'Runs test:units, test:functionals, test:generators, test:integration, test:jobs together' +desc "Runs all tests in test folder" task :test do Rails::TestTask.test_creator(Rake.application.top_level_tasks).invoke_rake_task end @@ -13,17 +13,34 @@ namespace :test do # Placeholder task for other Railtie and plugins to enhance. See Active Record for an example. end - task :run => ['test:units', 'test:functionals', 'test:generators', 'test:integration', 'test:jobs'] + Rails::TestTask.new(:run) do |t| + t.pattern = "test/**/*_test.rb" + end + + desc "Run tests quickly, but also reset db" + task :db => %w[db:test:prepare test] - # Inspired by: http://ngauthier.com/2012/02/quick-tests-with-bash.html desc "Run tests quickly by merging all types and not resetting db" Rails::TestTask.new(:all) do |t| t.pattern = "test/**/*_test.rb" end + Rake::Task["test:all"].enhance do + Rake::Task["test:deprecate_all"].invoke + end + + task :deprecate_all do + ActiveSupport::Deprecation.warn "rake test:all is deprecated and will be removed in Rails 5. " \ + "Use rake test to run all tests in test directory." + end + namespace :all do desc "Run tests quickly, but also reset db" task :db => %w[db:test:prepare test:all] + + Rake::Task["test:all:db"].enhance do + Rake::Task["test:deprecate_all"].invoke + end end Rails::TestTask.new(single: "test:prepare") diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 0eddf644d9..1f97807f8c 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -59,6 +59,20 @@ module ApplicationTests end end + test "lib dir is on LOAD_PATH during config" do + app_file 'lib/my_logger.rb', <<-RUBY + require "logger" + class MyLogger < ::Logger + end + RUBY + add_to_top_of_config <<-RUBY + require 'my_logger' + config.logger = MyLogger.new STDOUT + RUBY + require "#{app_path}/config/environment" + assert_equal 'MyLogger', Rails.application.config.logger.class.name + end + test "a renders exception on pending migration" do add_to_config <<-RUBY config.active_record.migration_error = :page_load @@ -301,6 +315,51 @@ module ApplicationTests assert_equal 'some_value', verifier.verify(message) end + test "application message verifier can be used when the key_generator is ActiveSupport::LegacyKeyGenerator" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + require "#{app_path}/config/environment" + + + assert_equal app.env_config['action_dispatch.key_generator'], Rails.application.key_generator + assert_equal app.env_config['action_dispatch.key_generator'].class, ActiveSupport::LegacyKeyGenerator + message = app.message_verifier(:sensitive_value).generate("some_value") + assert_equal 'some_value', Rails.application.message_verifier(:sensitive_value).verify(message) + end + + test "warns when secrets.secret_key_base is blank and config.secret_token is set" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + require "#{app_path}/config/environment" + + assert_deprecated(/You didn't set `secret_key_base`./) do + app.env_config + end + end + + test "prefer secrets.secret_token over config.secret_token" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_token: 3b7cd727ee24e8444053437c36cc66c3 + YAML + require "#{app_path}/config/environment" + + assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token + end + test "application verifier can build different verifiers" do make_basic_app do |app| app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' @@ -341,6 +400,21 @@ module ApplicationTests assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_key_base end + test "config.secret_token over-writes a blank secrets.secret_token" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + secret_token: + YAML + require "#{app_path}/config/environment" + + assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.secrets.secret_token + assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token + end + test "custom secrets saved in config/secrets.yml are loaded in app secrets" do app_file 'config/secrets.yml', <<-YAML development: @@ -362,6 +436,51 @@ module ApplicationTests assert_nil app.secrets.not_defined end + test "config.secret_key_base over-writes a blank secrets.secret_key_base" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_key_base = "iaminallyoursecretkeybase" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + require "#{app_path}/config/environment" + + assert_equal "iaminallyoursecretkeybase", app.secrets.secret_key_base + end + + test "uses ActiveSupport::LegacyKeyGenerator as app.key_generator when secrets.secret_key_base is blank" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + require "#{app_path}/config/environment" + + assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token + assert_equal nil, app.secrets.secret_key_base + assert_equal app.key_generator.class, ActiveSupport::LegacyKeyGenerator + end + + test "uses ActiveSupport::LegacyKeyGenerator with config.secret_token as app.key_generator when secrets.secret_key_base is blank" do + app_file 'config/initializers/secret_token.rb', <<-RUBY + Rails.application.config.secret_token = "" + RUBY + app_file 'config/secrets.yml', <<-YAML + development: + secret_key_base: + YAML + require "#{app_path}/config/environment" + + assert_equal '', app.config.secret_token + assert_equal nil, app.secrets.secret_key_base + assert_raise ArgumentError, /\AA secret is required/ do + app.key_generator + end + end + test "protect from forgery is the default in a new app" do make_basic_app @@ -848,6 +967,36 @@ module ApplicationTests end end + test "Blank config.log_level is not deprecated for non-production environment" do + with_rails_env "development" do + assert_not_deprecated do + make_basic_app do |app| + app.config.log_level = nil + end + end + end + end + + test "Blank config.log_level is deprecated for the production environment" do + with_rails_env "production" do + assert_deprecated(/log_level/) do + make_basic_app do |app| + app.config.log_level = nil + end + end + end + end + + test "Not blank config.log_level is not deprecated for the production environment" do + with_rails_env "production" do + assert_not_deprecated do + make_basic_app do |app| + app.config.log_level = :info + end + end + end + end + test "config.log_level with custom logger" do make_basic_app do |app| app.config.logger = Logger.new(STDOUT) diff --git a/railties/test/application/middleware/cache_test.rb b/railties/test/application/middleware/cache_test.rb index b4db840e68..c951dabd6c 100644 --- a/railties/test/application/middleware/cache_test.rb +++ b/railties/test/application/middleware/cache_test.rb @@ -81,8 +81,8 @@ module ApplicationTests add_to_config "config.action_dispatch.rack_cache = true" get "/expires/expires_header" - assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"] - assert_equal "max-age=10, public", last_response.headers["Cache-Control"] + assert_equal "miss, store", last_response.headers["X-Rack-Cache"] + assert_equal "max-age=10, public", last_response.headers["Cache-Control"] body = last_response.body @@ -115,8 +115,8 @@ module ApplicationTests add_to_config "config.action_dispatch.rack_cache = true" get "/expires/expires_etag" - assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"] - assert_equal "public", last_response.headers["Cache-Control"] + assert_equal "miss, store", last_response.headers["X-Rack-Cache"] + assert_equal "public", last_response.headers["Cache-Control"] body = last_response.body etag = last_response.headers["ETag"] @@ -149,8 +149,8 @@ module ApplicationTests add_to_config "config.action_dispatch.rack_cache = true" get "/expires/expires_last_modified" - assert_equal "miss, ignore, store", last_response.headers["X-Rack-Cache"] - assert_equal "public", last_response.headers["Cache-Control"] + assert_equal "miss, store", last_response.headers["X-Rack-Cache"] + assert_equal "public", last_response.headers["Cache-Control"] body = last_response.body last = last_response.headers["Last-Modified"] diff --git a/railties/test/application/middleware/exceptions_test.rb b/railties/test/application/middleware/exceptions_test.rb index 42096cfec4..a7472b37f1 100644 --- a/railties/test/application/middleware/exceptions_test.rb +++ b/railties/test/application/middleware/exceptions_test.rb @@ -60,6 +60,21 @@ module ApplicationTests assert_equal "YOU FAILED BRO", last_response.body end + test "url generation error when action_dispatch.show_exceptions is set raises an exception" do + controller :foo, <<-RUBY + class FooController < ActionController::Base + def index + raise ActionController::UrlGenerationError + end + end + RUBY + + app.config.action_dispatch.show_exceptions = true + + get '/foo' + assert_equal 500, last_response.status + end + test "unspecified route when action_dispatch.show_exceptions is not set raises an exception" do app.config.action_dispatch.show_exceptions = false diff --git a/railties/test/application/middleware/session_test.rb b/railties/test/application/middleware/session_test.rb index 31a64c2f5a..eb7885e5b1 100644 --- a/railties/test/application/middleware/session_test.rb +++ b/railties/test/application/middleware/session_test.rb @@ -203,7 +203,7 @@ module ApplicationTests RUBY add_to_config <<-RUBY - config.secret_token = "3b7cd727ee24e8444053437c36cc66c4" + secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4" RUBY require "#{app_path}/config/environment" @@ -258,7 +258,7 @@ module ApplicationTests RUBY add_to_config <<-RUBY - config.secret_token = "3b7cd727ee24e8444053437c36cc66c4" + secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4" RUBY require "#{app_path}/config/environment" @@ -317,7 +317,7 @@ module ApplicationTests RUBY add_to_config <<-RUBY - config.secret_token = "3b7cd727ee24e8444053437c36cc66c4" + secrets.secret_token = "3b7cd727ee24e8444053437c36cc66c4" secrets.secret_key_base = nil RUBY @@ -334,7 +334,7 @@ module ApplicationTests get '/foo/read_signed_cookie' assert_equal '2', last_response.body - verifier = ActiveSupport::MessageVerifier.new(app.config.secret_token) + verifier = ActiveSupport::MessageVerifier.new(app.secrets.secret_token) get '/foo/read_raw_cookie' assert_equal 2, verifier.verify(last_response.body)['foo'] diff --git a/railties/test/application/multiple_applications_test.rb b/railties/test/application/multiple_applications_test.rb index 9ebf163671..cddc79cc85 100644 --- a/railties/test/application/multiple_applications_test.rb +++ b/railties/test/application/multiple_applications_test.rb @@ -8,6 +8,7 @@ module ApplicationTests build_app(initializers: true) boot_rails require "#{rails_root}/config/environment" + Rails.application.config.some_setting = 'something_or_other' end def teardown @@ -18,7 +19,7 @@ module ApplicationTests clone = Rails.application.clone assert_equal Rails.application.config, clone.config, "The cloned application should get a copy of the config" - assert_equal Rails.application.config.secret_key_base, clone.config.secret_key_base, "The base secret key on the config should be the same" + assert_equal Rails.application.config.some_setting, clone.config.some_setting, "The some_setting on the config should be the same" end def test_inheriting_multiple_times_from_application @@ -160,13 +161,14 @@ module ApplicationTests def test_inserting_configuration_into_application app = AppTemplate::Application.new(config: Rails.application.config) - new_config = Rails::Application::Configuration.new("root_of_application") - new_config.secret_key_base = "some_secret_key_dude" - app.config.secret_key_base = "a_different_secret_key" + app.config.some_setting = "a_different_setting" + assert_equal "a_different_setting", app.config.some_setting, "The configuration's some_setting should be set." - assert_equal "a_different_secret_key", app.config.secret_key_base, "The configuration's secret key should be set." + new_config = Rails::Application::Configuration.new("root_of_application") + new_config.some_setting = "some_setting_dude" app.config = new_config - assert_equal "some_secret_key_dude", app.config.secret_key_base, "The configuration's secret key should have changed." + + assert_equal "some_setting_dude", app.config.some_setting, "The configuration's some_setting should have changed." assert_equal "root_of_application", app.config.root, "The root should have changed to the new config's root." assert_equal new_config, app.config, "The application's config should have changed to the new config." end diff --git a/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb index 267469b6f5..0a5873bcbf 100644 --- a/railties/test/application/rake/dbs_test.rb +++ b/railties/test/application/rake/dbs_test.rb @@ -109,6 +109,16 @@ module ApplicationTests db_fixtures_load database_url_db_name end + test 'db:fixtures:load with namespaced fixture' do + require "#{app_path}/config/environment" + Dir.chdir(app_path) do + `rails generate model admin::book title:string; + bundle exec rake db:migrate db:fixtures:load` + require "#{app_path}/app/models/admin/book" + assert_equal 2, Admin::Book.count + end + end + def db_structure_dump_and_load(expected_database) Dir.chdir(app_path) do `rails generate model book title:string; @@ -165,15 +175,6 @@ module ApplicationTests db_test_load_structure end - test 'db:test deprecation' do - require "#{app_path}/config/environment" - Dir.chdir(app_path) do - output = `bundle exec rake db:migrate db:test:prepare 2>&1` - assert_equal "WARNING: db:test:prepare is deprecated. The Rails test helper now maintains " \ - "your test schema automatically, see the release notes for details.\n", output - end - end - test 'db:setup loads schema and seeds database' do begin @old_rails_env = ENV["RAILS_ENV"] diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index c724c867ec..c7132837b1 100644 --- a/railties/test/application/test_test.rb +++ b/railties/test/application/test_test.rb @@ -193,6 +193,98 @@ module ApplicationTests assert_successful_test_run('models/user_test.rb') end + # TODO: would be nice if we could detect the schema change automatically. + # For now, the user has to synchronize the schema manually. + # This test-case serves as a reminder for this use-case. + test "manually synchronize test schema after rollback" do + output = script('generate model user name:string') + version = output.match(/(\d+)_create_users\.rb/)[1] + + app_file 'test/models/user_test.rb', <<-RUBY + require 'test_helper' + + class UserTest < ActiveSupport::TestCase + test "user" do + assert_equal ["id", "name"], User.columns_hash.keys + end + end + RUBY + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: #{version}) do + create_table :users do |t| + t.string :name + end + end + RUBY + + assert_successful_test_run "models/user_test.rb" + + # Simulate `db:rollback` + edit of the migration file + `db:migrate` + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: #{version}) do + create_table :users do |t| + t.string :name + t.integer :age + end + end + RUBY + + assert_successful_test_run "models/user_test.rb" + + Dir.chdir(app_path) { `bin/rake db:test:prepare` } + + assert_unsuccessful_run "models/user_test.rb", <<-ASSERTION +Expected: ["id", "name"] + Actual: ["id", "name", "age"] + ASSERTION + end + + test "hooks for plugins" do + output = script('generate model user name:string') + version = output.match(/(\d+)_create_users\.rb/)[1] + + app_file 'lib/tasks/hooks.rake', <<-RUBY + task :before_hook do + has_user_table = ActiveRecord::Base.connection.table_exists?('users') + puts "before: " + has_user_table.to_s + end + + task :after_hook do + has_user_table = ActiveRecord::Base.connection.table_exists?('users') + puts "after: " + has_user_table.to_s + end + + Rake::Task["db:test:prepare"].enhance [:before_hook] do + Rake::Task[:after_hook].invoke + end + RUBY + app_file 'test/models/user_test.rb', <<-RUBY + require 'test_helper' + class UserTest < ActiveSupport::TestCase + test "user" do + User.create! name: "Jon" + end + end + RUBY + + # Simulate `db:migrate` + app_file 'db/schema.rb', <<-RUBY + ActiveRecord::Schema.define(version: #{version}) do + create_table :users do |t| + t.string :name + end + end + RUBY + + output = assert_successful_test_run "models/user_test.rb" + assert_includes output, "before: false\nafter: true" + + # running tests again won't trigger a schema update + output = assert_successful_test_run "models/user_test.rb" + assert_not_includes output, "before:" + assert_not_includes output, "after:" + end + private def assert_unsuccessful_run(name, message) result = run_test_file(name) @@ -208,7 +300,7 @@ module ApplicationTests end def run_test_file(name, options = {}) - ruby '-Itest', "#{app_path}/test/#{name}", options + ruby '-Itest', "#{app_path}/test/#{name}", options.deep_merge(env: {"RAILS_ENV" => "test"}) end def ruby(*args) diff --git a/railties/test/application/url_generation_test.rb b/railties/test/application/url_generation_test.rb index efbc853d7b..ef16ab56ed 100644 --- a/railties/test/application/url_generation_test.rb +++ b/railties/test/application/url_generation_test.rb @@ -15,7 +15,7 @@ module ApplicationTests require "action_view/railtie" class MyApp < Rails::Application - config.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4" + secrets.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4" config.session_store :cookie_store, key: "_myapp_session" config.active_support.deprecation = :log config.eager_load = false diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb index b492258efb..b7cbe04003 100644 --- a/railties/test/generators/app_generator_test.rb +++ b/railties/test/generators/app_generator_test.rb @@ -450,12 +450,11 @@ class AppGeneratorTest < Rails::Generators::TestCase end end - def test_generator_if_skip_gems_is_given - run_generator [destination_root, "--skip-gems", "turbolinks", "coffee-rails"] + def test_generator_if_skip_turbolinks_is_given + run_generator [destination_root, "--skip-turbolinks"] assert_file "Gemfile" do |content| assert_no_match(/turbolinks/, content) - assert_no_match(/coffee-rails/, content) end assert_file "app/views/layouts/application.html.erb" do |content| assert_no_match(/data-turbolinks-track/, content) @@ -491,7 +490,7 @@ class AppGeneratorTest < Rails::Generators::TestCase def test_psych_gem run_generator - gem_regex = /gem 'psych',\s+'~> 2.0', \s+platforms: :rbx/ + gem_regex = /gem 'psych',\s+'~> 2.0',\s+platforms: :rbx/ assert_file "Gemfile" do |content| if defined?(Rubinius) diff --git a/railties/test/generators/generated_attribute_test.rb b/railties/test/generators/generated_attribute_test.rb index c48bc20899..ee7c009305 100644 --- a/railties/test/generators/generated_attribute_test.rb +++ b/railties/test/generators/generated_attribute_test.rb @@ -141,4 +141,12 @@ class GeneratedAttributeTest < Rails::Generators::TestCase assert_equal "post_id", create_generated_attribute('references', 'post').column_name assert_equal "post_id", create_generated_attribute('belongs_to', 'post').column_name end + + def test_parse_required_attribute_with_index + att = Rails::Generators::GeneratedAttribute.parse("supplier:references{required}:index") + assert_equal "supplier", att.name + assert_equal :references, att.type + assert att.has_index? + assert att.required? + end end diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb index 25649881eb..bab15ce172 100644 --- a/railties/test/generators/mailer_generator_test.rb +++ b/railties/test/generators/mailer_generator_test.rb @@ -8,8 +8,18 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_mailer_skeleton_is_created run_generator assert_file "app/mailers/notifier.rb" do |mailer| - assert_match(/class Notifier < ActionMailer::Base/, mailer) + assert_match(/class Notifier < ApplicationMailer/, mailer) + assert_no_match(/default from: "from@example.com"/, mailer) + assert_no_match(/layout :mailer_notifier/, mailer) + end + end + + def test_application_mailer_skeleton_is_created + run_generator + assert_file "app/mailers/application_mailer.rb" do |mailer| + assert_match(/class ApplicationMailer < ActionMailer::Base/, mailer) assert_match(/default from: "from@example.com"/, mailer) + assert_match(/layout 'mailer'/, mailer) end end @@ -77,6 +87,10 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_match(%r(\sapp/views/notifier/bar\.text\.erb), view) assert_match(/<%= @greeting %>/, view) end + + assert_file "app/views/layouts/mailer.text.erb" do |view| + assert_match(/<%= yield %>/, view) + end end def test_invokes_default_html_template_engine @@ -90,11 +104,17 @@ class MailerGeneratorTest < Rails::Generators::TestCase assert_match(%r(\sapp/views/notifier/bar\.html\.erb), view) assert_match(/<%= @greeting %>/, view) end + + assert_file "app/views/layouts/mailer.html.erb" do |view| + assert_match(%r{<html>\n <body>\n <%= yield %>\n </body>\n</html>}, view) + end end def test_invokes_default_template_engine_even_with_no_action run_generator ["notifier"] assert_file "app/views/notifier" + assert_file "app/views/layouts/mailer.text.erb" + assert_file "app/views/layouts/mailer.html.erb" end def test_logs_if_the_template_engine_cannot_be_found @@ -105,7 +125,7 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_mailer_with_namedspaced_mailer run_generator ["Farm::Animal", "moos"] assert_file "app/mailers/farm/animal.rb" do |mailer| - assert_match(/class Farm::Animal < ActionMailer::Base/, mailer) + assert_match(/class Farm::Animal < ApplicationMailer/, mailer) assert_match(/en\.farm\.animal\.moos\.subject/, mailer) end assert_file "test/mailers/previews/farm/animal_preview.rb" do |preview| diff --git a/railties/test/generators/migration_generator_test.rb b/railties/test/generators/migration_generator_test.rb index 72f5fe29ca..c2c8e2abad 100644 --- a/railties/test/generators/migration_generator_test.rb +++ b/railties/test/generators/migration_generator_test.rb @@ -85,6 +85,18 @@ class MigrationGeneratorTest < Rails::Generators::TestCase end end + def test_remove_migration_with_references_removes_foreign_keys + migration = "remove_references_from_books" + run_generator [migration, "author:belongs_to", "distributor:references{polymorphic}"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :change, content do |change| + assert_match(/remove_foreign_key :books, :authors/, change) + assert_no_match(/remove_foreign_key :books, :distributors/, change) + end + end + end + def test_add_migration_with_attributes_and_indices migration = "add_title_with_index_and_body_to_posts" run_generator [migration, "title:string:index", "body:text", "user_id:integer:uniq"] @@ -171,6 +183,18 @@ class MigrationGeneratorTest < Rails::Generators::TestCase end end + def test_add_migration_with_references_adds_foreign_keys + migration = "add_references_to_books" + run_generator [migration, "author:belongs_to", "distributor:references{polymorphic}"] + + assert_migration "db/migrate/#{migration}.rb" do |content| + assert_method :change, content do |change| + assert_match(/add_foreign_key :books, :authors/, change) + assert_no_match(/add_foreign_key :books, :distributors/, change) + end + end + end + def test_create_join_table_migration migration = "add_media_join_table" run_generator [migration, "artist_id", "musics:uniq"] @@ -205,7 +229,7 @@ class MigrationGeneratorTest < Rails::Generators::TestCase end end end - + def test_properly_identifies_usage_file assert generator_class.send(:usage_path) end diff --git a/railties/test/generators/model_generator_test.rb b/railties/test/generators/model_generator_test.rb index c78597c81b..ac7a0acf6b 100644 --- a/railties/test/generators/model_generator_test.rb +++ b/railties/test/generators/model_generator_test.rb @@ -407,6 +407,27 @@ class ModelGeneratorTest < Rails::Generators::TestCase end end + def test_foreign_key_is_added_for_references + run_generator ["account", "supplier:belongs_to", "user:references"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_match(/add_foreign_key :accounts, :suppliers/, up) + assert_match(/add_foreign_key :accounts, :users/, up) + end + end + end + + def test_foreign_key_is_skipped_for_polymorphic_references + run_generator ["account", "supplier:belongs_to{polymorphic}"] + + assert_migration "db/migrate/create_accounts.rb" do |m| + assert_method :change, m do |up| + assert_no_match(/add_foreign_key :accounts, :suppliers/, up) + end + end + end + private def assert_generated_fixture(path, parsed_contents) fixture_file = File.new File.expand_path(path, destination_root) diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb index 7eeb084eab..6075805152 100644 --- a/railties/test/generators/namespaced_generators_test.rb +++ b/railties/test/generators/namespaced_generators_test.rb @@ -148,8 +148,8 @@ class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase run_generator assert_file "app/mailers/test_app/notifier.rb" do |mailer| assert_match(/module TestApp/, mailer) - assert_match(/class Notifier < ActionMailer::Base/, mailer) - assert_match(/default from: "from@example.com"/, mailer) + assert_match(/class Notifier < ApplicationMailer/, mailer) + assert_no_match(/default from: "from@example.com"/, mailer) end end diff --git a/railties/test/generators/plugin_generator_test.rb b/railties/test/generators/plugin_generator_test.rb index ed4e100a9b..4329c6e1a4 100644 --- a/railties/test/generators/plugin_generator_test.rb +++ b/railties/test/generators/plugin_generator_test.rb @@ -245,6 +245,10 @@ class PluginGeneratorTest < Rails::Generators::TestCase assert_match(/stylesheet_link_tag\s+['"]bukkits\/application['"]/, contents) assert_match(/javascript_include_tag\s+['"]bukkits\/application['"]/, contents) end + assert_file "test/test_helper.rb" do |content| + assert_match(/ActiveRecord::Migrator\.migrations_paths.+\.\.\/test\/dummy\/db\/migrate/, content) + assert_match(/ActiveRecord::Migrator\.migrations_paths.+<<.+\.\.\/db\/migrate/, content) + end end def test_creating_gemspec diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index 40469e31d7..9ad0ec0d34 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -143,6 +143,7 @@ module TestHelpers config.active_support.deprecation = :log config.active_support.test_order = :random config.action_controller.allow_forgery_protection = false + config.log_level = :info RUBY end @@ -162,6 +163,8 @@ module TestHelpers app.secrets.secret_key_base = "3b7cd727ee24e8444053437c36cc66c4" app.config.session_store :cookie_store, key: "_myapp_session" app.config.active_support.deprecation = :log + app.config.active_support.test_order = :random + app.config.log_level = :info yield app if block_given? app.initialize! @@ -231,6 +234,15 @@ module TestHelpers end end + def add_to_top_of_config(str) + environment = File.read("#{app_path}/config/application.rb") + if environment =~ /(Rails::Application\s*)/ + File.open("#{app_path}/config/application.rb", 'w') do |f| + f.puts $` + $1 + "\n#{str}\n" + $' + end + end + end + def add_to_config(str) environment = File.read("#{app_path}/config/application.rb") if environment =~ /(\n\s*end\s*end\s*)\Z/ diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb index 1976466229..6239af2066 100644 --- a/railties/test/railties/engine_test.rb +++ b/railties/test/railties/engine_test.rb @@ -523,7 +523,7 @@ YAML end end - test "engine is a rack app and can have his own middleware stack" do + test "engine is a rack app and can have its own middleware stack" do add_to_config("config.action_dispatch.show_exceptions = false") @plugin.write "lib/bukkits.rb", <<-RUBY diff --git a/tasks/release.rb b/tasks/release.rb index de05dfad99..729e0761ad 100644 --- a/tasks/release.rb +++ b/tasks/release.rb @@ -102,7 +102,7 @@ namespace :all do abort "[ABORTING] `git status` reports a dirty tree. Make sure all changes are committed" end - unless ENV['SKIP_TAG'] || `git tag | grep '^#{tag}$`.strip.empty? + unless ENV['SKIP_TAG'] || `git tag | grep '^#{tag}$'`.strip.empty? abort "[ABORTING] `git tag` shows that #{tag} already exists. Has this version already\n"\ " been released? Git tagging can be skipped by setting SKIP_TAG=1" end diff --git a/tools/README.md b/tools/README.md new file mode 100644 index 0000000000..25ab798bd5 --- /dev/null +++ b/tools/README.md @@ -0,0 +1,7 @@ +## Rails dev tools + +This is a collection of utilities used for Rails internal development. +They aren't used by Rails apps directly. + + * `console` drops you in irb and loads local Rails repos + * `profile` profiles `Kernel#require` to help reduce startup time diff --git a/tools/line_statistics b/tools/line_statistics index 5eb5cfdc3d..bfa921b095 100755..100644 --- a/tools/line_statistics +++ b/tools/line_statistics @@ -1,4 +1,5 @@ -#!/usr/bin/env ruby +# Class used to calculates LOC for a provided file list. +# # Example: # files = FileList["lib/active_record/**/*.rb"] # CodeTools::LineStatistics.new(files).print_loc diff --git a/tools/profile b/tools/profile index a35dd18b77..eb7fc7792b 100755 --- a/tools/profile +++ b/tools/profile @@ -1,4 +1,7 @@ #!/usr/bin/env ruby +# Profile require calls giving information about the time and the files that are called +# when loading the provided file. +# # Example: # tools/profile activesupport/lib/active_support.rb [ruby-prof mode] [ruby-prof printer] ENV['NO_RELOAD'] ||= '1' @@ -65,7 +68,7 @@ module CodeTools private def assert_ruby_file_exists(path) - fail Error.new("No such file") unless File.exists?(path) + fail Error.new("No such file") unless File.exist?(path) fail Error.new("#{path} is a directory") if File.directory?(path) ruby_extension = File.extname(path) == '.rb' ruby_executable = File.open(path, 'rb') {|f| f.readline } =~ [/\A#!.*ruby/] diff --git a/version.rb b/version.rb index 4411ec33ef..8abed99f2c 100644 --- a/version.rb +++ b/version.rb @@ -8,7 +8,7 @@ module Rails MAJOR = 4 MINOR = 2 TINY = 0 - PRE = "beta2" + PRE = "beta4" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end |