aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--actionpack/CHANGELOG.md8
-rw-r--r--actionpack/lib/action_controller/form_builder.rb2
-rw-r--r--actionpack/lib/action_dispatch/middleware/cookies.rb4
-rw-r--r--actionpack/lib/action_dispatch/middleware/static.rb19
-rw-r--r--actionpack/lib/action_dispatch/testing/integration.rb1
-rw-r--r--actionview/CHANGELOG.md3
-rw-r--r--actionview/lib/action_view/helpers/asset_url_helper.rb30
-rw-r--r--actionview/test/template/date_helper_test.rb2
-rw-r--r--activejob/test/integration/queuing_test.rb4
-rw-r--r--activejob/test/support/integration/adapters/que.rb24
-rw-r--r--activejob/test/support/integration/adapters/queue_classic.rb22
-rw-r--r--activejob/test/support/integration/adapters/sidekiq.rb59
-rw-r--r--activemodel/CHANGELOG.md11
-rw-r--r--activemodel/lib/active_model/dirty.rb23
-rw-r--r--activemodel/test/cases/dirty_test.rb13
-rw-r--r--activerecord/CHANGELOG.md23
-rw-r--r--activerecord/lib/active_record/associations/builder/association.rb2
-rw-r--r--activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb2
-rw-r--r--activerecord/lib/active_record/associations/has_many_through_association.rb10
-rw-r--r--activerecord/lib/active_record/base.rb9
-rw-r--r--activerecord/lib/active_record/enum.rb2
-rw-r--r--activerecord/lib/active_record/persistence.rb18
-rw-r--r--activerecord/lib/active_record/reflection.rb4
-rw-r--r--activerecord/test/cases/associations/belongs_to_associations_test.rb4
-rw-r--r--activerecord/test/cases/associations/has_many_associations_test.rb8
-rw-r--r--activerecord/test/cases/associations/has_many_through_associations_test.rb16
-rw-r--r--activerecord/test/cases/autosave_association_test.rb12
-rw-r--r--activerecord/test/cases/connection_management_test.rb2
-rw-r--r--activerecord/test/cases/connection_pool_test.rb4
-rw-r--r--activerecord/test/cases/fixtures_test.rb12
-rw-r--r--activerecord/test/cases/locking_test.rb10
-rw-r--r--activesupport/CHANGELOG.md14
-rw-r--r--activesupport/lib/active_support/core_ext/array/inquiry.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/array/wrap.rb9
-rw-r--r--activesupport/lib/active_support/core_ext/module/aliasing.rb3
-rw-r--r--activesupport/lib/active_support/core_ext/module/concerning.rb6
-rw-r--r--activesupport/lib/active_support/testing/isolation.rb8
-rw-r--r--activesupport/lib/active_support/time_with_zone.rb13
-rw-r--r--activesupport/lib/active_support/values/time_zone.rb72
-rw-r--r--activesupport/test/core_ext/time_with_zone_test.rb47
-rw-r--r--activesupport/test/time_zone_test.rb83
-rw-r--r--guides/bug_report_templates/generic_gem.rb15
-rw-r--r--guides/bug_report_templates/generic_master.rb26
-rw-r--r--guides/source/4_2_release_notes.md5
-rw-r--r--guides/source/active_job_basics.md9
-rw-r--r--guides/source/active_record_postgresql.md23
-rw-r--r--guides/source/active_record_querying.md4
-rw-r--r--guides/source/active_support_core_extensions.md8
-rw-r--r--guides/source/asset_pipeline.md2
-rw-r--r--guides/source/association_basics.md2
-rw-r--r--guides/source/command_line.md2
-rw-r--r--guides/source/configuring.md22
-rw-r--r--guides/source/contributing_to_ruby_on_rails.md57
-rw-r--r--guides/source/debugging_rails_applications.md11
-rw-r--r--guides/source/getting_started.md6
-rw-r--r--guides/source/i18n.md4
-rw-r--r--guides/source/layouts_and_rendering.md11
-rw-r--r--guides/source/upgrading_ruby_on_rails.md2
-rw-r--r--railties/CHANGELOG.md24
-rw-r--r--railties/lib/rails/application.rb2
-rw-r--r--railties/lib/rails/commands/commands_tasks.rb11
-rw-r--r--railties/lib/rails/commands/dbconsole.rb5
-rw-r--r--railties/lib/rails/generators/app_base.rb2
-rw-r--r--railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb2
-rw-r--r--railties/lib/rails/generators/rails/scaffold/templates/scaffold.css27
-rw-r--r--railties/lib/rails/templates/rails/welcome/index.html.erb13
-rw-r--r--railties/test/commands/dbconsole_test.rb6
-rw-r--r--railties/test/generators/app_generator_test.rb8
68 files changed, 697 insertions, 232 deletions
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index a5e551c78e..0a31e34d3d 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -35,11 +35,11 @@
*Kohei Suzuki*
-* Fix handling of empty X_FORWARDED_HOST header in raw_host_with_port
+* Fix handling of empty `X_FORWARDED_HOST` header in `raw_host_with_port`.
- Previously, an empty X_FORWARDED_HOST header would cause
- Actiondispatch::Http:URL.raw_host_with_port to return nil, causing
- Actiondispatch::Http:URL.host to raise a NoMethodError.
+ Previously, an empty `X_FORWARDED_HOST` header would cause
+ `Actiondispatch::Http:URL.raw_host_with_port` to return `nil`, causing
+ `Actiondispatch::Http:URL.host` to raise a `NoMethodError`.
*Adam Forsyth*
diff --git a/actionpack/lib/action_controller/form_builder.rb b/actionpack/lib/action_controller/form_builder.rb
index 485f1eb54d..f2656ca894 100644
--- a/actionpack/lib/action_controller/form_builder.rb
+++ b/actionpack/lib/action_controller/form_builder.rb
@@ -21,7 +21,7 @@ module ActionController
#
# <%= form_for(@instance) do |builder| %>
# <%= builder.special_field(:name) %>
- # <%= end %>
+ # <% end %>
module FormBuilder
extend ActiveSupport::Concern
diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb
index b7687ca100..b1f0f5fc28 100644
--- a/actionpack/lib/action_dispatch/middleware/cookies.rb
+++ b/actionpack/lib/action_dispatch/middleware/cookies.rb
@@ -482,8 +482,8 @@ module ActionDispatch
# UpgradeLegacySignedCookieJar is used instead of SignedCookieJar if
# 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.
+ # legacy cookies signed with the old dummy key generator and signs and
+ # re-saves them using the new key generator to provide a smooth upgrade path.
class UpgradeLegacySignedCookieJar < SignedCookieJar #:nodoc:
include VerifyAndUpgradeLegacySignedMessage
diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb
index 9a92b690c7..c47e5d5245 100644
--- a/actionpack/lib/action_dispatch/middleware/static.rb
+++ b/actionpack/lib/action_dispatch/middleware/static.rb
@@ -3,15 +3,15 @@ require 'active_support/core_ext/uri'
module ActionDispatch
# This middleware returns a file's contents from disk in the body response.
- # When initialized it can accept an optional 'Cache-Control' header which
+ # When initialized, it can accept an optional 'Cache-Control' header, which
# will be set when a response containing a file's contents is delivered.
#
# This middleware will render the file specified in `env["PATH_INFO"]`
- # where the base path is in the +root+ directory. For example if the +root+
- # is set to `public/` then a request with `env["PATH_INFO"]` of
- # `assets/application.js` will return a response with contents of a file
+ # where the base path is in the +root+ directory. For example, if the +root+
+ # is set to `public/`, then a request with `env["PATH_INFO"]` of
+ # `assets/application.js` will return a response with the contents of a file
# located at `public/assets/application.js` if the file exists. If the file
- # does not exist a 404 "File not Found" response will be returned.
+ # does not exist, a 404 "File not Found" response will be returned.
class FileHandler
def initialize(root, cache_control)
@root = root.chomp('/')
@@ -20,6 +20,13 @@ module ActionDispatch
@file_server = ::Rack::File.new(@root, headers)
end
+
+ # Takes a path to a file. If the file is found, has valid encoding, and has
+ # correct read permissions, the return value is a URI-escaped string
+ # representing the filename. Otherwise, false is returned.
+ #
+ # Used by the `Static` class to check the existence of a valid file
+ # in the server's `public/` directory. (See Static#call)
def match?(path)
path = URI.parser.unescape(path)
return false unless path.valid_encoding?
@@ -88,7 +95,7 @@ module ActionDispatch
end
# This middleware will attempt to return the contents of a file's body from
- # disk in the response. If a file is not found on disk, the request will be
+ # disk in the response. If a file is not found on disk, the request will be
# delegated to the application stack. This middleware is commonly initialized
# to serve assets from a server's `public/` directory.
#
diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb
index 9390e2937a..3800c61dab 100644
--- a/actionpack/lib/action_dispatch/testing/integration.rb
+++ b/actionpack/lib/action_dispatch/testing/integration.rb
@@ -2,6 +2,7 @@ require 'stringio'
require 'uri'
require 'active_support/core_ext/kernel/singleton_class'
require 'active_support/core_ext/object/try'
+require 'active_support/core_ext/string/strip'
require 'rack/test'
require 'minitest'
diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md
index 74dbff80da..78ce230b3a 100644
--- a/actionview/CHANGELOG.md
+++ b/actionview/CHANGELOG.md
@@ -14,8 +14,7 @@
*Adam Prescott*
* `translate` should accept nils as members of the `:default`
- parameter without raising a translation missing error. Fixes a
- regression introduced 362557e.
+ parameter without raising a translation missing error.
Fixes #19419
diff --git a/actionview/lib/action_view/helpers/asset_url_helper.rb b/actionview/lib/action_view/helpers/asset_url_helper.rb
index 29733442c1..ef4a6c98c0 100644
--- a/actionview/lib/action_view/helpers/asset_url_helper.rb
+++ b/actionview/lib/action_view/helpers/asset_url_helper.rb
@@ -248,6 +248,11 @@ module ActionView
# Computes the full URL to a JavaScript asset in the public javascripts directory.
# This will use +javascript_path+ internally, so most of their behaviors will be the same.
+ # Since +javascript_url+ is based on +asset_url+ method you can set :host options. If :host
+ # options is set, it overwrites global +config.action_controller.asset_host+ setting.
+ #
+ # javascript_url "js/xmlhr.js", host: "http://stage.example.com" # => http://stage.example.com/assets/dir/xmlhr.js
+ #
def javascript_url(source, options = {})
url_to_asset(source, {type: :javascript}.merge!(options))
end
@@ -270,6 +275,11 @@ module ActionView
# Computes the full URL to a stylesheet asset in the public stylesheets directory.
# This will use +stylesheet_path+ internally, so most of their behaviors will be the same.
+ # Since +stylesheet_url+ is based on +asset_url+ method you can set :host options. If :host
+ # options is set, it overwrites global +config.action_controller.asset_host+ setting.
+ #
+ # stylesheet_url "css/style.css", host: "http://stage.example.com" # => http://stage.example.com/css/style.css
+ #
def stylesheet_url(source, options = {})
url_to_asset(source, {type: :stylesheet}.merge!(options))
end
@@ -295,6 +305,11 @@ module ActionView
# Computes the full URL to an image asset.
# This will use +image_path+ internally, so most of their behaviors will be the same.
+ # Since +image_url+ is based on +asset_url+ method you can set :host options. If :host
+ # options is set, it overwrites global +config.action_controller.asset_host+ setting.
+ #
+ # image_url "edit.png", host: "http://stage.example.com" # => http://stage.example.com/edit.png
+ #
def image_url(source, options = {})
url_to_asset(source, {type: :image}.merge!(options))
end
@@ -316,6 +331,11 @@ module ActionView
# Computes the full URL to a video asset in the public videos directory.
# This will use +video_path+ internally, so most of their behaviors will be the same.
+ # Since +video_url+ is based on +asset_url+ method you can set :host options. If :host
+ # options is set, it overwrites global +config.action_controller.asset_host+ setting.
+ #
+ # video_url "hd.avi", host: "http://stage.example.com" # => http://stage.example.com/hd.avi
+ #
def video_url(source, options = {})
url_to_asset(source, {type: :video}.merge!(options))
end
@@ -337,6 +357,11 @@ module ActionView
# Computes the full URL to an audio asset in the public audios directory.
# This will use +audio_path+ internally, so most of their behaviors will be the same.
+ # Since +audio_url+ is based on +asset_url+ method you can set :host options. If :host
+ # options is set, it overwrites global +config.action_controller.asset_host+ setting.
+ #
+ # audio_url "horse.wav", host: "http://stage.example.com" # => http://stage.example.com/horse.wav
+ #
def audio_url(source, options = {})
url_to_asset(source, {type: :audio}.merge!(options))
end
@@ -357,6 +382,11 @@ module ActionView
# Computes the full URL to a font asset.
# This will use +font_path+ internally, so most of their behaviors will be the same.
+ # Since +font_url+ is based on +asset_url+ method you can set :host options. If :host
+ # options is set, it overwrites global +config.action_controller.asset_host+ setting.
+ #
+ # font_url "font.ttf", host: "http://stage.example.com" # => http://stage.example.com/font.ttf
+ #
def font_url(source, options = {})
url_to_asset(source, {type: :font}.merge!(options))
end
diff --git a/actionview/test/template/date_helper_test.rb b/actionview/test/template/date_helper_test.rb
index bfb073680e..a0e1f5f3bb 100644
--- a/actionview/test/template/date_helper_test.rb
+++ b/actionview/test/template/date_helper_test.rb
@@ -130,7 +130,7 @@ class DateHelperTest < ActionView::TestCase
def test_distance_in_words_with_mathn_required
# test we avoid Integer#/ (redefined by mathn)
- require 'mathn'
+ silence_warnings { require "mathn" }
from = Time.utc(2004, 6, 6, 21, 45, 0)
assert_distance_of_time_in_words(from)
end
diff --git a/activejob/test/integration/queuing_test.rb b/activejob/test/integration/queuing_test.rb
index af19a92118..09f5c329cc 100644
--- a/activejob/test/integration/queuing_test.rb
+++ b/activejob/test/integration/queuing_test.rb
@@ -26,8 +26,6 @@ class QueuingTest < ActiveSupport::TestCase
test 'should supply a wrapped class name to Sidekiq' do
skip unless adapter_is?(:sidekiq)
- require 'sidekiq/testing'
-
Sidekiq::Testing.fake! do
::HelloJob.perform_later
hash = ActiveJob::QueueAdapters::SidekiqAdapter::JobWrapper.jobs.first
@@ -48,7 +46,7 @@ class QueuingTest < ActiveSupport::TestCase
test 'should run job enqueued in the future at the specified time' do
begin
- TestJob.set(wait: 3.seconds).perform_later @id
+ TestJob.set(wait: 5.seconds).perform_later @id
wait_for_jobs_to_finish_for(2.seconds)
assert_not job_executed
wait_for_jobs_to_finish_for(10.seconds)
diff --git a/activejob/test/support/integration/adapters/que.rb b/activejob/test/support/integration/adapters/que.rb
index ba7657a42a..ff5235bdc8 100644
--- a/activejob/test/support/integration/adapters/que.rb
+++ b/activejob/test/support/integration/adapters/que.rb
@@ -2,6 +2,15 @@ module QueJobsManager
def setup
require 'sequel'
ActiveJob::Base.queue_adapter = :que
+ Que.mode = :off
+ Que.worker_count = 1
+ end
+
+ def clear_jobs
+ Que.clear!
+ end
+
+ def start_workers
que_url = ENV['QUE_DATABASE_URL'] || 'postgres:///active_jobs_que_int_test'
uri = URI.parse(que_url)
user = uri.user||ENV['USER']
@@ -11,24 +20,17 @@ module QueJobsManager
%x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'create database "#{db}"' -U #{user} -t template1}
Que.connection = Sequel.connect(que_url)
Que.migrate!
- Que.mode = :off
- Que.worker_count = 1
- rescue Sequel::DatabaseConnectionError
- puts "Cannot run integration tests for que. To be able to run integration tests for que you need to install and start postgresql.\n"
- exit
- end
-
- def clear_jobs
- Que.clear!
- end
- def start_workers
@thread = Thread.new do
loop do
Que::Job.work("integration_tests")
sleep 0.5
end
end
+
+ rescue Sequel::DatabaseConnectionError
+ puts "Cannot run integration tests for que. To be able to run integration tests for que you need to install and start postgresql.\n"
+ exit
end
def stop_workers
diff --git a/activejob/test/support/integration/adapters/queue_classic.rb b/activejob/test/support/integration/adapters/queue_classic.rb
index f522b2711f..29c04bf625 100644
--- a/activejob/test/support/integration/adapters/queue_classic.rb
+++ b/activejob/test/support/integration/adapters/queue_classic.rb
@@ -3,17 +3,7 @@ module QueueClassicJobsManager
ENV['QC_DATABASE_URL'] ||= 'postgres:///active_jobs_qc_int_test'
ENV['QC_RAILS_DATABASE'] = 'false'
ENV['QC_LISTEN_TIME'] = "0.5"
- uri = URI.parse(ENV['QC_DATABASE_URL'])
- user = uri.user||ENV['USER']
- pass = uri.password
- db = uri.path[1..-1]
- %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'drop database if exists "#{db}"' -U #{user} -t template1}
- %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'create database "#{db}"' -U #{user} -t template1}
ActiveJob::Base.queue_adapter = :queue_classic
- QC::Setup.create
- rescue PG::ConnectionBad
- puts "Cannot run integration tests for queue_classic. To be able to run integration tests for queue_classic you need to install and start postgresql.\n"
- exit
end
def clear_jobs
@@ -21,12 +11,24 @@ module QueueClassicJobsManager
end
def start_workers
+ uri = URI.parse(ENV['QC_DATABASE_URL'])
+ user = uri.user||ENV['USER']
+ pass = uri.password
+ db = uri.path[1..-1]
+ %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'drop database if exists "#{db}"' -U #{user} -t template1}
+ %x{#{"PGPASSWORD=\"#{pass}\"" if pass} psql -c 'create database "#{db}"' -U #{user} -t template1}
+ QC::Setup.create
+
QC.default_conn_adapter.disconnect
QC.default_conn_adapter = nil
@pid = fork do
worker = QC::Worker.new(q_name: 'integration_tests')
worker.start
end
+
+ rescue PG::ConnectionBad
+ puts "Cannot run integration tests for queue_classic. To be able to run integration tests for queue_classic you need to install and start postgresql.\n"
+ exit
end
def stop_workers
diff --git a/activejob/test/support/integration/adapters/sidekiq.rb b/activejob/test/support/integration/adapters/sidekiq.rb
index dd24b3abf2..4988cdb33f 100644
--- a/activejob/test/support/integration/adapters/sidekiq.rb
+++ b/activejob/test/support/integration/adapters/sidekiq.rb
@@ -1,5 +1,8 @@
require 'sidekiq/api'
+require 'sidekiq/testing'
+Sidekiq::Testing.disable!
+
module SidekiqJobsManager
def setup
@@ -16,28 +19,38 @@ module SidekiqJobsManager
end
def start_workers
- fork do
- logfile = Rails.root.join("log/sidekiq.log").to_s
- pidfile = Rails.root.join("tmp/sidekiq.pid").to_s
- ::Process.daemon(true, true)
- [$stdout, $stderr].each do |io|
- File.open(logfile, 'ab') do |f|
- io.reopen(f)
- end
- io.sync = true
- end
+ continue_read, continue_write = IO.pipe
+ death_read, death_write = IO.pipe
+
+ @pid = fork do
+ continue_read.close
+ death_write.close
+
+ # Celluloid & Sidekiq are not warning-clean :(
+ $VERBOSE = false
+
$stdin.reopen('/dev/null')
+ $stdout.sync = true
+ $stderr.sync = true
+
+ logfile = Rails.root.join("log/sidekiq.log").to_s
Sidekiq::Logging.initialize_logger(logfile)
- File.open(File.expand_path(pidfile), 'w') do |f|
- f.puts ::Process.pid
- end
self_read, self_write = IO.pipe
trap "TERM" do
self_write.puts("TERM")
end
+ Thread.new do
+ begin
+ death_read.read
+ rescue Exception
+ end
+ self_write.puts("TERM")
+ end
+
require 'celluloid'
+ Celluloid.logger = nil
require 'sidekiq/launcher'
sidekiq = Sidekiq::Launcher.new({queues: ["integration_tests"],
environment: "test",
@@ -48,23 +61,29 @@ module SidekiqJobsManager
Sidekiq::Scheduled.const_set :INITIAL_WAIT, 1
begin
sidekiq.run
+ continue_write.puts "started"
while readable_io = IO.select([self_read])
signal = readable_io.first[0].gets.strip
raise Interrupt if signal == "TERM"
end
rescue Interrupt
- sidekiq.stop
- exit(0)
end
+
+ sidekiq.stop
+ exit!
end
- sleep 1
+ continue_write.close
+ death_read.close
+ @worker_lifeline = death_write
+
+ raise "Failed to start worker" unless continue_read.gets == "started\n"
end
def stop_workers
- pidfile = Rails.root.join("tmp/sidekiq.pid").to_s
- Process.kill 'TERM', File.open(pidfile).read.to_i
- FileUtils.rm_f pidfile
- rescue
+ if @pid
+ Process.kill 'TERM', @pid
+ Process.wait @pid
+ end
end
def can_run?
diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md
index 32a2cb4517..4961d69d2a 100644
--- a/activemodel/CHANGELOG.md
+++ b/activemodel/CHANGELOG.md
@@ -1,3 +1,12 @@
+* Add `ActiveModel::Dirty#[attr_name]_previously_changed?` and
+ `ActiveModel::Dirty#[attr_name]_previous_change` to improve access
+ to recorded changes after the model has been saved.
+
+ It makes the dirty-attributes query methods consistent before and after
+ saving.
+
+ *Fernando Tapia Rico*
+
* Deprecate the `:tokenizer` option for `validates_length_of`, in favor of
plain Ruby.
@@ -13,7 +22,7 @@
*Wojciech Wnętrzak*
-* Allow symbol as values for `tokenize` of `LengthValidator`
+* Allow symbol as values for `tokenize` of `LengthValidator`.
*Kensuke Naito*
diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb
index c03e5fac79..c0fc507286 100644
--- a/activemodel/lib/active_model/dirty.rb
+++ b/activemodel/lib/active_model/dirty.rb
@@ -76,9 +76,11 @@ module ActiveModel
#
# Reset the changes:
#
- # person.previous_changes # => {"name" => ["Uncle Bob", "Bill"]}
+ # person.previous_changes # => {"name" => ["Uncle Bob", "Bill"]}
+ # person.name_previously_changed? # => true
+ # person.name_previous_change # => ["Uncle Bob", "Bill"]
# person.reload!
- # person.previous_changes # => {}
+ # person.previous_changes # => {}
#
# Rollback the changes:
#
@@ -115,6 +117,7 @@ module ActiveModel
included do
attribute_method_suffix '_changed?', '_change', '_will_change!', '_was'
+ attribute_method_suffix '_previously_changed?', '_previous_change'
attribute_method_affix prefix: 'restore_', suffix: '!'
end
@@ -179,6 +182,11 @@ module ActiveModel
attribute_changed?(attr) ? changed_attributes[attr] : __send__(attr)
end
+ # Handles <tt>*_previously_changed?</tt> for +method_missing+.
+ def attribute_previously_changed?(attr, options = {}) #:nodoc:
+ previous_changes_include?(attr)
+ end
+
# Restore all previous data of the provided attributes.
def restore_attributes(attributes = changed)
attributes.each { |attr| restore_attribute! attr }
@@ -192,6 +200,12 @@ module ActiveModel
end
alias attribute_changed_by_setter? changes_include?
+ # Returns +true+ if attr_name were changed before the model was saved,
+ # +false+ otherwise.
+ def previous_changes_include?(attr_name)
+ @previously_changed.include?(attr_name)
+ end
+
# Removes current changes and makes them accessible through +previous_changes+.
def changes_applied # :doc:
@previously_changed = changes
@@ -209,6 +223,11 @@ module ActiveModel
[changed_attributes[attr], __send__(attr)] if attribute_changed?(attr)
end
+ # Handles <tt>*_previous_change</tt> for +method_missing+.
+ def attribute_previous_change(attr)
+ @previously_changed[attr] if attribute_previously_changed?(attr)
+ end
+
# Handles <tt>*_will_change!</tt> for +method_missing+.
def attribute_will_change!(attr)
return if attribute_changed?(attr)
diff --git a/activemodel/test/cases/dirty_test.rb b/activemodel/test/cases/dirty_test.rb
index 66ed8a350a..d17a12ad12 100644
--- a/activemodel/test/cases/dirty_test.rb
+++ b/activemodel/test/cases/dirty_test.rb
@@ -137,6 +137,19 @@ class DirtyTest < ActiveModel::TestCase
assert_equal [nil, "Jericho Cane"], @model.previous_changes['name']
end
+ test "setting new attributes should not affect previous changes" do
+ @model.name = "Jericho Cane"
+ @model.save
+ @model.name = "DudeFella ManGuy"
+ assert_equal [nil, "Jericho Cane"], @model.name_previous_change
+ end
+
+ test "saving should preserve model's previous changed status" do
+ @model.name = "Jericho Cane"
+ @model.save
+ assert @model.name_previously_changed?
+ end
+
test "previous value is preserved when changed after save" do
assert_equal({}, @model.changed_attributes)
@model.name = "Paul"
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index bfa43bd55a..d30c8e345f 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -6,9 +6,18 @@
*Paul Mucur*
-* Add support for `Set` to `Relation#where`.
+* Rename `:class` to `:anonymous_class` in association options.
- *Yuki Nishijima*
+ Fixes #19659.
+
+ *Andrew White*
+
+* Autosave existing records on a has many through association when the parent
+ is new.
+
+ Fixes #19782.
+
+ *Sean Griffin*
* Fixed a bug where uniqueness validations would error on out of range values,
even if an validation should have prevented it from hitting the database.
@@ -33,20 +42,22 @@
*Mehmet Emin İNAÇ*
-* Reduce memory usage from loading types on pg.
+* Reduce memory usage from loading types on PostgreSQL.
Fixes #19578.
*Sean Griffin*
-* Add `config.active_record.warn_on_records_fetched_greater_than` option
+* Add `config.active_record.warn_on_records_fetched_greater_than` option.
When set to an integer, a warning will be logged whenever a result set
- larger than the specified size is returned by a query. Fixes #16463
+ larger than the specified size is returned by a query.
+
+ Fixes #16463.
*Jason Nochlin*
-* Ignore psqlrc when loading database structure.
+* Ignore `.psqlrc` when loading database structure.
*Jason Weathered*
diff --git a/activerecord/lib/active_record/associations/builder/association.rb b/activerecord/lib/active_record/associations/builder/association.rb
index 88406740d8..ba1b1814d1 100644
--- a/activerecord/lib/active_record/associations/builder/association.rb
+++ b/activerecord/lib/active_record/associations/builder/association.rb
@@ -16,7 +16,7 @@ module ActiveRecord::Associations::Builder
end
self.extensions = []
- VALID_OPTIONS = [:class_name, :class, :foreign_key, :validate] # :nodoc:
+ VALID_OPTIONS = [:class_name, :anonymous_class, :foreign_key, :validate] # :nodoc:
def self.build(model, name, scope, options, &block)
if model.dangerous_attribute_method?(name)
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 97b57a6a55..ffd9c9d6fc 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
@@ -78,7 +78,7 @@ module ActiveRecord::Associations::Builder
join_model.table_name_resolver = habtm
join_model.class_resolver = lhs_model
- join_model.add_left_association :left_side, class: lhs_model
+ join_model.add_left_association :left_side, anonymous_class: lhs_model
join_model.add_right_association association_name, belongs_to_options(options)
join_model
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 29e8a0edc1..cd79266952 100644
--- a/activerecord/lib/active_record/associations/has_many_through_association.rb
+++ b/activerecord/lib/active_record/associations/has_many_through_association.rb
@@ -38,12 +38,10 @@ module ActiveRecord
def insert_record(record, validate = true, raise = false)
ensure_not_nested
- if record.new_record?
- if raise
- record.save!(:validate => validate)
- else
- return unless record.save(:validate => validate)
- end
+ if raise
+ record.save!(:validate => validate)
+ else
+ return unless record.save(:validate => validate)
end
save_through_record(record)
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb
index 67490ecd97..9c5b7d937d 100644
--- a/activerecord/lib/active_record/base.rb
+++ b/activerecord/lib/active_record/base.rb
@@ -120,23 +120,22 @@ module ActiveRecord #:nodoc:
# All column values are automatically available through basic accessors on the Active Record
# object, but sometimes you want to specialize this behavior. This can be done by overwriting
# the default accessors (using the same name as the attribute) and calling
- # <tt>read_attribute(attr_name)</tt> and <tt>write_attribute(attr_name, value)</tt> to actually
- # change things.
+ # +super+ to actually change things.
#
# class Song < ActiveRecord::Base
# # Uses an integer of seconds to hold the length of the song
#
# def length=(minutes)
- # write_attribute(:length, minutes.to_i * 60)
+ # super(minutes.to_i * 60)
# end
#
# def length
- # read_attribute(:length) / 60
+ # super / 60
# end
# end
#
# You can alternatively use <tt>self[:attribute]=(value)</tt> and <tt>self[:attribute]</tt>
- # instead of <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
+ # or <tt>write_attribute(:attribute, value)</tt> and <tt>read_attribute(:attribute)</tt>.
#
# == Attribute query methods
#
diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb
index ea88983917..2b99899e42 100644
--- a/activerecord/lib/active_record/enum.rb
+++ b/activerecord/lib/active_record/enum.rb
@@ -32,7 +32,7 @@ module ActiveRecord
# Conversation.active
# Conversation.archived
#
- # Of course, you can also query them directly if the scopes doesn't fit your
+ # Of course, you can also query them directly if the scopes don't fit your
# needs:
#
# Conversation.where(status: [:active, :archived])
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index a1e1073792..ae1c326d95 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -477,11 +477,23 @@ module ActiveRecord
changes[column] = write_attribute(column, time)
end
- changes[self.class.locking_column] = increment_lock if locking_enabled?
-
clear_attribute_changes(changes.keys)
primary_key = self.class.primary_key
- self.class.unscoped.where(primary_key => self[primary_key]).update_all(changes) == 1
+ scope = self.class.unscoped.where(primary_key => _read_attribute(primary_key))
+
+ if locking_enabled?
+ locking_column = self.class.locking_column
+ scope = scope.where(locking_column => _read_attribute(locking_column))
+ changes[locking_column] = increment_lock
+ end
+
+ result = scope.update_all(changes) == 1
+
+ if !result && locking_enabled?
+ raise ActiveRecord::StaleObjectError.new(self, "touch")
+ end
+
+ result
else
true
end
diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb
index 4265afc0a5..1b0ae2c942 100644
--- a/activerecord/lib/active_record/reflection.rb
+++ b/activerecord/lib/active_record/reflection.rb
@@ -196,7 +196,7 @@ module ActiveRecord
@scope = scope
@options = options
@active_record = active_record
- @klass = options[:class]
+ @klass = options[:anonymous_class]
@plural_name = active_record.pluralize_table_names ?
name.to_s.pluralize : name.to_s
end
@@ -635,7 +635,7 @@ module ActiveRecord
def initialize(delegate_reflection)
@delegate_reflection = delegate_reflection
- @klass = delegate_reflection.options[:class]
+ @klass = delegate_reflection.options[:anonymous_class]
@source_reflection_name = delegate_reflection.options[:source]
end
diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb
index 95d00ab3a9..ba90c61d65 100644
--- a/activerecord/test/cases/associations/belongs_to_associations_test.rb
+++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb
@@ -124,9 +124,9 @@ class BelongsToAssociationsTest < ActiveRecord::TestCase
where("id = :inc", :inc => counter)
}
- has_many :comments, :class => comments
+ has_many :comments, :anonymous_class => comments
}
- belongs_to :post, :class => posts, :inverse_of => false
+ belongs_to :post, :anonymous_class => posts, :inverse_of => false
}
assert_equal 0, counter
diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb
index 171cfbde44..14cdf37f46 100644
--- a/activerecord/test/cases/associations/has_many_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_associations_test.rb
@@ -119,9 +119,9 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
developer_project = Class.new(ActiveRecord::Base) {
self.table_name = 'developers_projects'
- belongs_to :developer, :class => dev
+ belongs_to :developer, :anonymous_class => dev
}
- has_many :developer_projects, :class => developer_project, :foreign_key => 'developer_id'
+ has_many :developer_projects, :anonymous_class => developer_project, :foreign_key => 'developer_id'
}
dev = developer.first
named = Developer.find(dev.id)
@@ -140,13 +140,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase
comments = Class.new(ActiveRecord::Base) {
self.table_name = 'comments'
self.inheritance_column = 'not_there'
- belongs_to :post, :class => post
+ belongs_to :post, :anonymous_class => post
default_scope -> {
counter += 1
where("id = :inc", :inc => counter)
}
}
- has_many :comments, :class => comments, :foreign_key => 'post_id'
+ has_many :comments, :anonymous_class => comments, :foreign_key => 'post_id'
}
assert_equal 0, counter
post = posts.first
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 5f52c65412..9734ea2217 100644
--- a/activerecord/test/cases/associations/has_many_through_associations_test.rb
+++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb
@@ -84,11 +84,11 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
subscriber = make_model "Subscriber"
subscriber.primary_key = 'nick'
- subscription.belongs_to :book, class: book
- subscription.belongs_to :subscriber, class: subscriber
+ subscription.belongs_to :book, anonymous_class: book
+ subscription.belongs_to :subscriber, anonymous_class: subscriber
- book.has_many :subscriptions, class: subscription
- book.has_many :subscribers, through: :subscriptions, class: subscriber
+ book.has_many :subscriptions, anonymous_class: subscription
+ book.has_many :subscribers, through: :subscriptions, anonymous_class: subscriber
anonbook = book.first
namebook = Book.find anonbook.id
@@ -154,10 +154,10 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase
lesson_student = make_model 'LessonStudent'
lesson_student.table_name = 'lessons_students'
- lesson_student.belongs_to :lesson, :class => lesson
- lesson_student.belongs_to :student, :class => student
- lesson.has_many :lesson_students, :class => lesson_student
- lesson.has_many :students, :through => :lesson_students, :class => student
+ lesson_student.belongs_to :lesson, :anonymous_class => lesson
+ lesson_student.belongs_to :student, :anonymous_class => student
+ lesson.has_many :lesson_students, :anonymous_class => lesson_student
+ lesson.has_many :students, :through => :lesson_students, :anonymous_class => student
[lesson, lesson_student, student]
end
diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb
index 8f0d7bd037..80b5a0004d 100644
--- a/activerecord/test/cases/autosave_association_test.rb
+++ b/activerecord/test/cases/autosave_association_test.rb
@@ -43,7 +43,7 @@ class TestAutosaveAssociationsInGeneral < ActiveRecord::TestCase
reference = Class.new(ActiveRecord::Base) {
self.table_name = "references"
def self.name; 'Reference'; end
- belongs_to :person, autosave: true, class: person
+ belongs_to :person, autosave: true, anonymous_class: person
}
u = person.create!(first_name: 'cool')
@@ -1278,6 +1278,16 @@ module AutosaveAssociationOnACollectionAssociationTests
assert_equal new_names, @pirate.reload.send(@association_name).map(&:name)
end
+ def test_should_update_children_when_autosave_is_true_and_parent_is_new_but_child_is_not
+ parrot = Parrot.create!(name: "Polly")
+ parrot.name = "Squawky"
+ pirate = Pirate.new(parrots: [parrot], catchphrase: "Arrrr")
+
+ pirate.save!
+
+ assert_equal "Squawky", parrot.reload.name
+ end
+
def test_should_automatically_validate_the_associated_models
@pirate.send(@association_name).each { |child| child.name = '' }
diff --git a/activerecord/test/cases/connection_management_test.rb b/activerecord/test/cases/connection_management_test.rb
index f53c496ecd..bab624b78a 100644
--- a/activerecord/test/cases/connection_management_test.rb
+++ b/activerecord/test/cases/connection_management_test.rb
@@ -110,7 +110,7 @@ module ActiveRecord
assert ActiveRecord::Base.connection_handler.active_connections?
end
- test "proxy is polite to it's body and responds to it" do
+ test "proxy is polite to its body and responds to it" do
body = Class.new(String) { def to_path; "/path"; end }.new
app = lambda { |_| [200, {}, body] }
response_body = ConnectionManagement.new(app).call(@env)[2]
diff --git a/activerecord/test/cases/connection_pool_test.rb b/activerecord/test/cases/connection_pool_test.rb
index 8d15a76735..aa50efc979 100644
--- a/activerecord/test/cases/connection_pool_test.rb
+++ b/activerecord/test/cases/connection_pool_test.rb
@@ -204,13 +204,13 @@ module ActiveRecord
end
# The connection pool is "fair" if threads waiting for
- # connections receive them the order in which they began
+ # connections receive them in the order in which they began
# waiting. This ensures that we don't timeout one HTTP request
# even while well under capacity in a multi-threaded environment
# such as a Java servlet container.
#
# We don't need strict fairness: if two connections become
- # available at the same time, it's fine of two threads that were
+ # available at the same time, it's fine if two threads that were
# waiting acquire the connections out of order.
#
# Thus this test prepares waiting threads and then trickles in
diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb
index f8acdcb51e..97ba178b4d 100644
--- a/activerecord/test/cases/fixtures_test.rb
+++ b/activerecord/test/cases/fixtures_test.rb
@@ -279,10 +279,10 @@ class HasManyThroughFixture < ActiveSupport::TestCase
treasure = make_model "Treasure"
pt.table_name = "parrots_treasures"
- pt.belongs_to :parrot, :class => parrot
- pt.belongs_to :treasure, :class => treasure
+ pt.belongs_to :parrot, :anonymous_class => parrot
+ pt.belongs_to :treasure, :anonymous_class => treasure
- parrot.has_many :parrot_treasures, :class => pt
+ parrot.has_many :parrot_treasures, :anonymous_class => pt
parrot.has_many :treasures, :through => :parrot_treasures
parrots = File.join FIXTURES_ROOT, 'parrots'
@@ -297,10 +297,10 @@ class HasManyThroughFixture < ActiveSupport::TestCase
parrot = make_model "Parrot"
treasure = make_model "Treasure"
- pt.belongs_to :parrot, :class => parrot
- pt.belongs_to :treasure, :class => treasure
+ pt.belongs_to :parrot, :anonymous_class => parrot
+ pt.belongs_to :treasure, :anonymous_class => treasure
- parrot.has_many :parrot_treasures, :class => pt
+ parrot.has_many :parrot_treasures, :anonymous_class => pt
parrot.has_many :treasures, :through => :parrot_treasures
parrots = File.join FIXTURES_ROOT, 'parrots'
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index 9e4998a946..dbdcc84b7d 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -177,6 +177,16 @@ class OptimisticLockingTest < ActiveRecord::TestCase
assert_equal 1, p1.lock_version
end
+ def test_touch_stale_object
+ person = Person.create!(first_name: 'Mehmet Emin')
+ stale_person = Person.find(person.id)
+ person.update_attribute(:gender, 'M')
+
+ assert_raises(ActiveRecord::StaleObjectError) do
+ stale_person.touch
+ end
+ end
+
def test_lock_column_name_existing
t1 = LegacyThing.find(1)
t2 = LegacyThing.find(1)
diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md
index 3ad2392365..ac27dc640e 100644
--- a/activesupport/CHANGELOG.md
+++ b/activesupport/CHANGELOG.md
@@ -1,3 +1,14 @@
+* Encoding ActiveSupport::TimeWithZone to YAML now preserves the timezone information.
+
+ Fixes #9183.
+
+ *Andrew White*
+
+* Added `ActiveSupport::TimeZone#strptime` to allow parsing times as if
+ from a given timezone.
+
+ *Paul A Jungwirth*
+
* `ActiveSupport::Callbacks#skip_callback` now raises an `ArgumentError` if
an unrecognized callback is removed.
@@ -23,7 +34,8 @@
*George Claghorn*
-* Deprecate `alias_method_chain` in favour of `Module#prepend` introduced in Ruby 2.0
+* Deprecate `alias_method_chain` in favour of `Module#prepend` introduced in
+ Ruby 2.0.
*Kir Shatrov*
diff --git a/activesupport/lib/active_support/core_ext/array/inquiry.rb b/activesupport/lib/active_support/core_ext/array/inquiry.rb
index de623c466c..e8f44cc378 100644
--- a/activesupport/lib/active_support/core_ext/array/inquiry.rb
+++ b/activesupport/lib/active_support/core_ext/array/inquiry.rb
@@ -1,3 +1,5 @@
+require 'active_support/array_inquirer'
+
class Array
# Wraps the array in an +ArrayInquirer+ object, which gives a friendlier way
# to check its string-like contents.
diff --git a/activesupport/lib/active_support/core_ext/array/wrap.rb b/activesupport/lib/active_support/core_ext/array/wrap.rb
index 152eb02218..b611d34c27 100644
--- a/activesupport/lib/active_support/core_ext/array/wrap.rb
+++ b/activesupport/lib/active_support/core_ext/array/wrap.rb
@@ -3,7 +3,7 @@ class Array
#
# Specifically:
#
- # * If the argument is +nil+ an empty list is returned.
+ # * If the argument is +nil+ an empty array is returned.
# * Otherwise, if the argument responds to +to_ary+ it is invoked, and its result returned.
# * Otherwise, returns an array with the argument as its single element.
#
@@ -15,12 +15,13 @@ class Array
#
# * If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt>
# moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns
- # +nil+ right away.
+ # an array with the argument as its single element right away.
# * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt>
# raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value.
- # * It does not call +to_a+ on the argument, but returns an empty array if argument is +nil+.
+ # * It does not call +to_a+ on the argument, if the argument does not respond to +to_ary+
+ # it returns an array with the argument as its single element.
#
- # The second point is easily explained with some enumerables:
+ # The last point is easily explained with some enumerables:
#
# Array(foo: :bar) # => [[:foo, :bar]]
# Array.wrap(foo: :bar) # => [{:foo=>:bar}]
diff --git a/activesupport/lib/active_support/core_ext/module/aliasing.rb b/activesupport/lib/active_support/core_ext/module/aliasing.rb
index a4c40b25ff..b6934b9c54 100644
--- a/activesupport/lib/active_support/core_ext/module/aliasing.rb
+++ b/activesupport/lib/active_support/core_ext/module/aliasing.rb
@@ -1,4 +1,7 @@
class Module
+ # NOTE: This method is deprecated. Please use <tt>Module#prepend</tt> that
+ # comes with Ruby 2.0 or newer instead.
+ #
# Encapsulates the common pattern of:
#
# alias_method :foo_without_feature, :foo
diff --git a/activesupport/lib/active_support/core_ext/module/concerning.rb b/activesupport/lib/active_support/core_ext/module/concerning.rb
index 07a392404e..e26b594fc4 100644
--- a/activesupport/lib/active_support/core_ext/module/concerning.rb
+++ b/activesupport/lib/active_support/core_ext/module/concerning.rb
@@ -63,10 +63,10 @@ class Module
#
# == Mix-in noise exiled to its own file:
#
- # Once our chunk of behavior starts pushing the scroll-to-understand it's
+ # Once our chunk of behavior starts pushing the scroll-to-understand-it
# boundary, we give in and move it to a separate file. At this size, the
- # overhead feels in good proportion to the size of our extraction, despite
- # diluting our at-a-glance sense of how things really work.
+ # increased overhead can be a reasonable tradeoff even if it reduces our
+ # at-a-glance perception of how things work.
#
# class Todo
# # Other todo implementation
diff --git a/activesupport/lib/active_support/testing/isolation.rb b/activesupport/lib/active_support/testing/isolation.rb
index 247df7423b..1de0a19998 100644
--- a/activesupport/lib/active_support/testing/isolation.rb
+++ b/activesupport/lib/active_support/testing/isolation.rb
@@ -69,17 +69,17 @@ module ActiveSupport
else
Tempfile.open("isolation") do |tmpfile|
env = {
- ISOLATION_TEST: self.class.name,
- ISOLATION_OUTPUT: tmpfile.path
+ 'ISOLATION_TEST' => self.class.name,
+ 'ISOLATION_OUTPUT' => tmpfile.path
}
load_paths = $-I.map {|p| "-I\"#{File.expand_path(p)}\"" }.join(" ")
orig_args = ORIG_ARGV.join(" ")
test_opts = "-n#{self.class.name}##{self.name}"
- command = "#{Gem.ruby} #{load_paths} #{$0} #{orig_args} #{test_opts}"
+ command = "#{Gem.ruby} #{load_paths} #{$0} '#{orig_args}' #{test_opts}"
# IO.popen lets us pass env in a cross-platform way
- child = IO.popen([env, command])
+ child = IO.popen(env, command)
begin
Process.wait(child.pid)
diff --git a/activesupport/lib/active_support/time_with_zone.rb b/activesupport/lib/active_support/time_with_zone.rb
index c28de4e21c..b0d7f3299f 100644
--- a/activesupport/lib/active_support/time_with_zone.rb
+++ b/activesupport/lib/active_support/time_with_zone.rb
@@ -169,12 +169,13 @@ module ActiveSupport
end
end
- def encode_with(coder)
- if coder.respond_to?(:represent_object)
- coder.represent_object(nil, utc)
- else
- coder.represent_scalar(nil, utc.strftime("%Y-%m-%d %H:%M:%S.%9NZ"))
- end
+ def init_with(coder) #:nodoc:
+ initialize(coder['utc'], coder['zone'], coder['time'])
+ end
+
+ def encode_with(coder) #:nodoc:
+ coder.tag = '!ruby/object:ActiveSupport::TimeWithZone'
+ coder.map = { 'utc' => utc, 'zone' => time_zone, 'time' => time }
end
# Returns a string of the object's date and time in the format used by
diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb
index da39f0d245..2699a064d7 100644
--- a/activesupport/lib/active_support/values/time_zone.rb
+++ b/activesupport/lib/active_support/values/time_zone.rb
@@ -348,24 +348,31 @@ module ActiveSupport
#
# Time.zone.parse('Mar 2000') # => Wed, 01 Mar 2000 00:00:00 HST -10:00
def parse(str, now=now())
- parts = Date._parse(str, false)
- return if parts.empty?
-
- time = Time.new(
- parts.fetch(:year, now.year),
- parts.fetch(:mon, now.month),
- parts.fetch(:mday, parts[:year] || parts[:mon] ? 1 : now.day),
- parts.fetch(:hour, 0),
- parts.fetch(:min, 0),
- parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
- parts.fetch(:offset, 0)
- )
-
- if parts[:offset]
- TimeWithZone.new(time.utc, self)
- else
- TimeWithZone.new(nil, self, time)
- end
+ parts_to_time(Date._parse(str, false), now)
+ end
+
+ # Parses +str+ according to +format+ and returns an ActiveSupport::TimeWithZone.
+ #
+ # Assumes that +str+ is a time in the time zone +self+,
+ # unless +format+ includes an explicit time zone.
+ # (This is the same behavior as +parse+.)
+ # In either case, the returned TimeWithZone has the timezone of +self+.
+ #
+ # Time.zone = 'Hawaii' # => "Hawaii"
+ # Time.zone.strptime('1999-12-31 14:00:00', '%Y-%m-%d %H:%M:%S') # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ #
+ # If upper components are missing from the string, they are supplied from
+ # TimeZone#now:
+ #
+ # Time.zone.now # => Fri, 31 Dec 1999 14:00:00 HST -10:00
+ # Time.zone.strptime('22:30:00', '%H:%M:%S') # => Fri, 31 Dec 1999 22:30:00 HST -10:00
+ #
+ # However, if the date component is not provided, but any other upper
+ # components are supplied, then the day of the month defaults to 1:
+ #
+ # Time.zone.strptime('Mar 2000', '%b %Y') # => Wed, 01 Mar 2000 00:00:00 HST -10:00
+ def strptime(str, format, now=now())
+ parts_to_time(DateTime._strptime(str, format), now)
end
# Returns an ActiveSupport::TimeWithZone instance representing the current
@@ -421,7 +428,36 @@ module ActiveSupport
tzinfo.periods_for_local(time)
end
+ def init_with(coder) #:nodoc:
+ initialize(coder['name'])
+ end
+
+ def encode_with(coder) #:nodoc:
+ coder.tag ="!ruby/object:#{self.class}"
+ coder.map = { 'name' => tzinfo.name }
+ end
+
private
+ def parts_to_time(parts, now)
+ return if parts.empty?
+
+ time = Time.new(
+ parts.fetch(:year, now.year),
+ parts.fetch(:mon, now.month),
+ parts.fetch(:mday, parts[:year] || parts[:mon] ? 1 : now.day),
+ parts.fetch(:hour, 0),
+ parts.fetch(:min, 0),
+ parts.fetch(:sec, 0) + parts.fetch(:sec_fraction, 0),
+ parts.fetch(:offset, 0)
+ )
+
+ if parts[:offset]
+ TimeWithZone.new(time.utc, self)
+ else
+ TimeWithZone.new(nil, self, time)
+ end
+ end
+
def time_now
Time.now
end
diff --git a/activesupport/test/core_ext/time_with_zone_test.rb b/activesupport/test/core_ext/time_with_zone_test.rb
index 92c233d567..79d78c02cd 100644
--- a/activesupport/test/core_ext/time_with_zone_test.rb
+++ b/activesupport/test/core_ext/time_with_zone_test.rb
@@ -1,6 +1,7 @@
require 'abstract_unit'
require 'active_support/time'
require 'time_zone_test_helpers'
+require 'active_support/core_ext/string/strip'
class TimeWithZoneTest < ActiveSupport::TestCase
include TimeZoneTestHelpers
@@ -123,11 +124,53 @@ class TimeWithZoneTest < ActiveSupport::TestCase
end
def test_to_yaml
- assert_match(/^--- 2000-01-01 00:00:00(\.0+)?\s*Z\n/, @twz.to_yaml)
+ yaml = <<-EOF.strip_heredoc
+ --- !ruby/object:ActiveSupport::TimeWithZone
+ utc: 2000-01-01 00:00:00.000000000 Z
+ zone: !ruby/object:ActiveSupport::TimeZone
+ name: America/New_York
+ time: 1999-12-31 19:00:00.000000000 Z
+ EOF
+
+ assert_equal(yaml, @twz.to_yaml)
end
def test_ruby_to_yaml
- assert_match(/---\s*\n:twz: 2000-01-01 00:00:00(\.0+)?\s*Z\n/, {:twz => @twz}.to_yaml)
+ yaml = <<-EOF.strip_heredoc
+ ---
+ twz: !ruby/object:ActiveSupport::TimeWithZone
+ utc: 2000-01-01 00:00:00.000000000 Z
+ zone: !ruby/object:ActiveSupport::TimeZone
+ name: America/New_York
+ time: 1999-12-31 19:00:00.000000000 Z
+ EOF
+
+ assert_equal(yaml, { 'twz' => @twz }.to_yaml)
+ end
+
+ def test_yaml_load
+ yaml = <<-EOF.strip_heredoc
+ --- !ruby/object:ActiveSupport::TimeWithZone
+ utc: 2000-01-01 00:00:00.000000000 Z
+ zone: !ruby/object:ActiveSupport::TimeZone
+ name: America/New_York
+ time: 1999-12-31 19:00:00.000000000 Z
+ EOF
+
+ assert_equal(@twz, YAML.load(yaml))
+ end
+
+ def test_ruby_yaml_load
+ yaml = <<-EOF.strip_heredoc
+ ---
+ twz: !ruby/object:ActiveSupport::TimeWithZone
+ utc: 2000-01-01 00:00:00.000000000 Z
+ zone: !ruby/object:ActiveSupport::TimeZone
+ name: America/New_York
+ time: 1999-12-31 19:00:00.000000000 Z
+ EOF
+
+ assert_equal({ 'twz' => @twz }, YAML.load(yaml))
end
def test_httpdate
diff --git a/activesupport/test/time_zone_test.rb b/activesupport/test/time_zone_test.rb
index 7888b9919b..5e0474f449 100644
--- a/activesupport/test/time_zone_test.rb
+++ b/activesupport/test/time_zone_test.rb
@@ -311,6 +311,80 @@ class TimeZoneTest < ActiveSupport::TestCase
end
end
+ def test_strptime
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00', '%Y-%m-%d %H:%M:%S')
+ assert_equal Time.utc(1999,12,31,17), twz
+ assert_equal Time.utc(1999,12,31,12), twz.time
+ assert_equal Time.utc(1999,12,31,17), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_strptime_with_nondefault_time_zone
+ with_tz_default ActiveSupport::TimeZone['Pacific Time (US & Canada)'] do
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00', '%Y-%m-%d %H:%M:%S')
+ assert_equal Time.utc(1999,12,31,17), twz
+ assert_equal Time.utc(1999,12,31,12), twz.time
+ assert_equal Time.utc(1999,12,31,17), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+ end
+
+ def test_strptime_with_explicit_time_zone_as_abbrev
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00 PST', '%Y-%m-%d %H:%M:%S %Z')
+ assert_equal Time.utc(1999,12,31,20), twz
+ assert_equal Time.utc(1999,12,31,15), twz.time
+ assert_equal Time.utc(1999,12,31,20), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_strptime_with_explicit_time_zone_as_h_offset
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00 -08', '%Y-%m-%d %H:%M:%S %:::z')
+ assert_equal Time.utc(1999,12,31,20), twz
+ assert_equal Time.utc(1999,12,31,15), twz.time
+ assert_equal Time.utc(1999,12,31,20), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_strptime_with_explicit_time_zone_as_hm_offset
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00 -08:00', '%Y-%m-%d %H:%M:%S %:z')
+ assert_equal Time.utc(1999,12,31,20), twz
+ assert_equal Time.utc(1999,12,31,15), twz.time
+ assert_equal Time.utc(1999,12,31,20), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_strptime_with_explicit_time_zone_as_hms_offset
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00 -08:00:00', '%Y-%m-%d %H:%M:%S %::z')
+ assert_equal Time.utc(1999,12,31,20), twz
+ assert_equal Time.utc(1999,12,31,15), twz.time
+ assert_equal Time.utc(1999,12,31,20), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_strptime_with_almost_explicit_time_zone
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ twz = zone.strptime('1999-12-31 12:00:00 %Z', '%Y-%m-%d %H:%M:%S %%Z')
+ assert_equal Time.utc(1999,12,31,17), twz
+ assert_equal Time.utc(1999,12,31,12), twz.time
+ assert_equal Time.utc(1999,12,31,17), twz.utc
+ assert_equal zone, twz.time_zone
+ end
+
+ def test_strptime_with_day_omitted
+ with_env_tz 'US/Eastern' do
+ zone = ActiveSupport::TimeZone['Eastern Time (US & Canada)']
+ assert_equal Time.local(2000, 2, 1), zone.strptime('Feb', '%b', Time.local(2000, 1, 1))
+ assert_equal Time.local(2005, 2, 1), zone.strptime('Feb 2005', '%b %Y', Time.local(2000, 1, 1))
+ assert_equal Time.local(2005, 2, 2), zone.strptime('2 Feb 2005', '%e %b %Y', Time.local(2000, 1, 1))
+ end
+ end
+
def test_utc_offset_lazy_loaded_from_tzinfo_when_not_passed_in_to_initialize
tzinfo = TZInfo::Timezone.get('America/New_York')
zone = ActiveSupport::TimeZone.create(tzinfo.name, nil, tzinfo)
@@ -413,4 +487,13 @@ class TimeZoneTest < ActiveSupport::TestCase
assert ActiveSupport::TimeZone.us_zones.include?(ActiveSupport::TimeZone["Hawaii"])
assert !ActiveSupport::TimeZone.us_zones.include?(ActiveSupport::TimeZone["Kuala Lumpur"])
end
+
+ def test_to_yaml
+ assert_equal("--- !ruby/object:ActiveSupport::TimeZone\nname: Pacific/Honolulu\n", ActiveSupport::TimeZone["Hawaii"].to_yaml)
+ assert_equal("--- !ruby/object:ActiveSupport::TimeZone\nname: Europe/London\n", ActiveSupport::TimeZone["Europe/London"].to_yaml)
+ end
+
+ def test_yaml_load
+ assert_equal(ActiveSupport::TimeZone["Pacific/Honolulu"], YAML.load("--- !ruby/object:ActiveSupport::TimeZone\nname: Pacific/Honolulu\n"))
+ end
end
diff --git a/guides/bug_report_templates/generic_gem.rb b/guides/bug_report_templates/generic_gem.rb
new file mode 100644
index 0000000000..3e3f8593d4
--- /dev/null
+++ b/guides/bug_report_templates/generic_gem.rb
@@ -0,0 +1,15 @@
+# Activate the gems you are reporting the issue against.
+gem 'activesupport', '4.2.0'
+require 'active_support'
+require 'active_support/core_ext/object/blank'
+require 'minitest/autorun'
+
+# Ensure backward compatibility with Minitest 4
+Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
+
+class BugTest < Minitest::Test
+ def test_stuff
+ assert "zomg".present?
+ refute "".present?
+ end
+end
diff --git a/guides/bug_report_templates/generic_master.rb b/guides/bug_report_templates/generic_master.rb
new file mode 100644
index 0000000000..d930482d4e
--- /dev/null
+++ b/guides/bug_report_templates/generic_master.rb
@@ -0,0 +1,26 @@
+unless File.exist?('Gemfile')
+ File.write('Gemfile', <<-GEMFILE)
+ source 'https://rubygems.org'
+ gem 'rails', github: 'rails/rails'
+ gem 'arel', github: 'rails/arel'
+ GEMFILE
+
+ system 'bundle'
+end
+
+require 'bundler'
+Bundler.setup(:default)
+
+require 'active_support'
+require 'active_support/core_ext/object/blank'
+require 'minitest/autorun'
+
+# Ensure backward compatibility with Minitest 4
+Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
+
+class BugTest < Minitest::Test
+ def test_stuff
+ assert "zomg".present?
+ refute "".present?
+ end
+end
diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md
index 684bd286bc..d5b3766a5b 100644
--- a/guides/source/4_2_release_notes.md
+++ b/guides/source/4_2_release_notes.md
@@ -214,9 +214,8 @@ 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 will continue to work as before
-on your own machine.
+should have minimal impact on the standard development workflow as http://localhost:3000
+will continue to work as before on your own machine.
However, with this change you will no longer be able to access the Rails
server from a different machine, for example if your development environment
diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md
index 953c29719d..29d0c32b09 100644
--- a/guides/source/active_job_basics.md
+++ b/guides/source/active_job_basics.md
@@ -11,7 +11,7 @@ After reading this guide, you will know:
* How to create jobs.
* How to enqueue jobs.
* How to run jobs in the background.
-* How to send emails from your application async.
+* How to send emails from your application asynchronously.
--------------------------------------------------------------------------------
@@ -319,3 +319,10 @@ class GuestsCleanupJob < ActiveJob::Base
end
end
```
+
+
+Job Testing
+--------------
+
+You can find detailed instructions on how to test your jobs in the
+[testing guide](testing.html#testing-jobs).
diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md
index 4d9c1776f4..66a11e5785 100644
--- a/guides/source/active_record_postgresql.md
+++ b/guides/source/active_record_postgresql.md
@@ -245,6 +245,7 @@ article.save!
* [type definition](http://www.postgresql.org/docs/9.3/static/datatype-uuid.html)
* [generator functions](http://www.postgresql.org/docs/9.3/static/uuid-ossp.html)
+NOTE: you need to enable the `uuid-ossp` extension to use uuid.
```ruby
# db/migrate/20131220144913_create_revisions.rb
@@ -263,6 +264,28 @@ revision = Revision.first
revision.identifier # => "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"
```
+You can use `uuid` type to define references in migrations
+
+```ruby
+# db/migrate/20150418012400_create_blog.rb
+create_table :posts, id: :uuid
+
+create_table :comments, id: :uuid do |t|
+ # t.belongs_to :post, type: :uuid
+ t.references :post, type: :uuid
+end
+
+# app/models/post.rb
+class Post < ActiveRecord::Base
+ has_many :comments
+end
+
+# app/models/comment.rb
+class Comment < ActiveRecord::Base
+ belongs_to :post
+end
+```
+
### Bit String Types
* [type definition](http://www.postgresql.org/docs/9.3/static/datatype-bit.html)
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index de976acd01..2f10bc4e7c 100644
--- a/guides/source/active_record_querying.md
+++ b/guides/source/active_record_querying.md
@@ -317,7 +317,7 @@ end
The `find_each` method accepts most of the options allowed by the regular `find` method, except for `:order` and `:limit`, which are reserved for internal use by `find_each`.
-Two additional options, `:batch_size` and `:begin_at`, are available as well.
+Three additional options, `:batch_size`, `:begin_at` and `:end_at`, are available as well.
**`:batch_size`**
@@ -348,7 +348,7 @@ Another example would be if you wanted multiple workers handling the same proces
Similar to the `:begin_at` option, `:end_at` allows you to configure the last ID of the sequence whenever the highest ID is not the one you need.
This would be useful, for example, if you wanted to run a batch process, using a subset of records based on `:begin_at` and `:end_at`
-For example, to send newsletters only to users with the primary key starting from 2000 up to 10000 and to retrieve them in batches of 1000:
+For example, to send newsletters only to users with the primary key starting from 2000 up to 10000 and to retrieve them in batches of 5000:
```ruby
User.find_each(begin_at: 2000, end_at: 10000, batch_size: 5000) do |user|
diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md
index ff60f95a2c..2a643680f7 100644
--- a/guides/source/active_support_core_extensions.md
+++ b/guides/source/active_support_core_extensions.md
@@ -2188,7 +2188,7 @@ The method `without` returns a copy of an enumerable with the specified elements
removed:
```ruby
-people.without("Aaron", "Todd")
+["David", "Rafael", "Aaron", "Todd"].without("Aaron", "Todd") # => ["David", "Rafael"]
```
NOTE: Defined in `active_support/core_ext/enumerable.rb`.
@@ -2428,7 +2428,7 @@ The method `Array.wrap` wraps its argument in an array unless it is already an a
Specifically:
-* If the argument is `nil` an empty list is returned.
+* If the argument is `nil` an empty array is returned.
* Otherwise, if the argument responds to `to_ary` it is invoked, and if the value of `to_ary` is not `nil`, it is returned.
* Otherwise, an array with the argument as its single element is returned.
@@ -2440,9 +2440,9 @@ Array.wrap(0) # => [0]
This method is similar in purpose to `Kernel#Array`, but there are some differences:
-* If the argument responds to `to_ary` the method is invoked. `Kernel#Array` moves on to try `to_a` if the returned value is `nil`, but `Array.wrap` returns `nil` right away.
+* If the argument responds to `to_ary` the method is invoked. `Kernel#Array` moves on to try `to_a` if the returned value is `nil`, but `Array.wrap` returns an array with the argument as its single element right away.
* If the returned value from `to_ary` is neither `nil` nor an `Array` object, `Kernel#Array` raises an exception, while `Array.wrap` does not, it just returns the value.
-* It does not call `to_a` on the argument, though special-cases `nil` to return an empty array.
+* It does not call `to_a` on the argument, if the argument does not respond to +to_ary+ it returns an array with the argument as its single element.
The last point is particularly worth comparing for some enumerables:
diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md
index d9dfd85860..4a610e8458 100644
--- a/guides/source/asset_pipeline.md
+++ b/guides/source/asset_pipeline.md
@@ -643,7 +643,7 @@ above. By default Rails assumes assets have been precompiled and will be
served as static assets by your web server.
During the precompilation phase an MD5 is generated from the contents of the
-compiled files, and inserted into the filenames as they are written to disc.
+compiled files, and inserted into the filenames as they are written to disk.
These fingerprinted names are used by the Rails helpers in place of the manifest
name.
diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md
index abac54d22d..412cfd198a 100644
--- a/guides/source/association_basics.md
+++ b/guides/source/association_basics.md
@@ -1668,7 +1668,7 @@ You can use any of the standard [querying methods](active_record_querying.html)
* `order`
* `readonly`
* `select`
-* `uniq`
+* `distinct`
##### `where`
diff --git a/guides/source/command_line.md b/guides/source/command_line.md
index 8f9102611d..315d8c14b6 100644
--- a/guides/source/command_line.md
+++ b/guides/source/command_line.md
@@ -423,7 +423,7 @@ If you want to clear `public/assets` completely, you can use `rake assets:clobbe
The most common tasks of the `db:` Rake namespace are `migrate` and `create`, and it will pay off to try out all of the migration rake tasks (`up`, `down`, `redo`, `reset`). `rake db:version` is useful when troubleshooting, telling you the current version of the database.
-More information about migrations can be found in the [Migrations](migrations.html) guide.
+More information about migrations can be found in the [Migrations](active_record_migrations.html) guide.
### `notes`
diff --git a/guides/source/configuring.md b/guides/source/configuring.md
index 43ddcf0767..aa66376d5d 100644
--- a/guides/source/configuring.md
+++ b/guides/source/configuring.md
@@ -424,13 +424,23 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
end
```
-* `config.action_view.default_form_builder` tells Rails which form builder to use by default. The default is `ActionView::Helpers::FormBuilder`. If you want your form builder class to be loaded after initialization (so it's reloaded on each request in development), you can pass it as a `String`
+* `config.action_view.default_form_builder` tells Rails which form builder to
+ use by default. The default is `ActionView::Helpers::FormBuilder`. If you
+ want your form builder class to be loaded after initialization (so it's
+ reloaded on each request in development), you can pass it as a `String`.
* `config.action_view.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action View. Set to `nil` to disable logging.
* `config.action_view.erb_trim_mode` gives the trim mode to be used by ERB. It defaults to `'-'`, which turns on trimming of tail spaces and newline when using `<%= -%>` or `<%= =%>`. See the [Erubis documentation](http://www.kuwata-lab.com/erubis/users-guide.06.html#topics-trimspaces) for more information.
-* `config.action_view.embed_authenticity_token_in_remote_forms` allows you to set the default behavior for `authenticity_token` in forms with `:remote => true`. By default it's set to false, which means that remote forms will not include `authenticity_token`, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the `meta` tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass `:authenticity_token => true` as a form option or set this config setting to `true`
+* `config.action_view.embed_authenticity_token_in_remote_forms` allows you to
+ set the default behavior for `authenticity_token` in forms with `remote:
+ true`. By default it's set to false, which means that remote forms will not
+ include `authenticity_token`, which is helpful when you're fragment-caching
+ the form. Remote forms get the authenticity from the `meta` tag, so embedding
+ is unnecessary unless you support browsers without JavaScript. In such case
+ you can either pass `authenticity_token: true` as a form option or set this
+ config setting to `true`.
* `config.action_view.prefix_partial_path_with_controller_namespace` determines whether or not partials are looked up from a subdirectory in templates rendered from namespaced controllers. For example, consider a controller named `Admin::ArticlesController` which renders this template:
@@ -440,7 +450,8 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
The default setting is `true`, which uses the partial at `/admin/articles/_article.erb`. Setting the value to `false` would render `/articles/_article.erb`, which is the same behavior as rendering from a non-namespaced controller such as `ArticlesController`.
-* `config.action_view.raise_on_missing_translations` determines whether an error should be raised for missing translations
+* `config.action_view.raise_on_missing_translations` determines whether an
+ error should be raised for missing translations.
### Configuring Action Mailer
@@ -555,7 +566,7 @@ There are a few configuration options available in Active Support:
* `config.active_job.queue_name_prefix` allows you to set an optional, non-blank, queue name prefix for all jobs. By default it is blank and not used.
The following configuration would queue the given job on the `production_high_priority` queue when run in production:
-
+
```ruby
config.active_job.queue_name_prefix = Rails.env
```
@@ -1012,7 +1023,8 @@ Below is a comprehensive list of all the initializers found in Rails in the orde
* `active_record.set_dispatch_hooks` Resets all reloadable connections to the database if `config.cache_classes` is set to `false`.
-* `active_job.logger` Sets `ActiveJob::Base.logger` - if it's not already set - to `Rails.logger`
+* `active_job.logger` Sets `ActiveJob::Base.logger` - if it's not already set -
+ to `Rails.logger`.
* `active_job.set_configs` Sets up Active Job by using the settings in `config.active_job` by `send`'ing the method names as setters to `ActiveJob::Base` and passing the values through.
diff --git a/guides/source/contributing_to_ruby_on_rails.md b/guides/source/contributing_to_ruby_on_rails.md
index 618b6c3799..3d5f8906ca 100644
--- a/guides/source/contributing_to_ruby_on_rails.md
+++ b/guides/source/contributing_to_ruby_on_rails.md
@@ -32,15 +32,19 @@ Your issue report should contain a title and a clear description of the issue at
Then, don't get your hopes up! Unless you have a "Code Red, Mission Critical, the World is Coming to an End" kind of bug, you're creating this issue report in the hope that others with the same problem will be able to collaborate with you on solving it. Do not expect that the issue report will automatically see any activity or that others will jump to fix it. Creating an issue like this is mostly to help yourself start on the path of fixing the problem and for others to confirm it with an "I'm having this problem too" comment.
-### Create a Self-Contained gist for Active Record and Action Controller Issues
+### Create an Executable Test Case
-If you are filing a bug report, please use
-[Active Record template for gems](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_gem.rb) or
-[Action Controller template for gems](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_gem.rb)
-if the bug is found in a published gem, and
-[Active Record template for master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_master.rb) or
-[Action Controller template for master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_master.rb)
-if the bug happens in the master branch.
+Having a way to reproduce your issue will be very helpful for others to help confirm, investigate and ultimately fix your issue. You can do this by providing an executable test case. To make this process easier, we have prepared several bug report templates for you to use as a starting point:
+
+* Template for Active Record (models, database) issues: [gem](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_gem.rb) / [master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/active_record_master.rb)
+* Template for Action Pack (controllers, routing) issues: [gem](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_gem.rb) / [master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/action_controller_master.rb)
+* Generic template for other issues: [gem](https://github.com/rails/rails/blob/master/guides/bug_report_templates/generic_gem.rb) / [master](https://github.com/rails/rails/blob/master/guides/bug_report_templates/generic_master.rb)
+
+These templates include the boilerplate code to set up a test case against either a released version of Rails (`*_gem.rb`) or edge Rails (`*_master.rb`).
+
+Simply copy the content of the appropriate template into a `.rb` file and make the necessary changes to demonstrate the issue. You can execute it by running `ruby the_file.rb` in your terminal. If all goes well, you should see your test case failing.
+
+You can then share your executable test case as a [gist](https://gist.github.com), or simply paste the content into the issue description.
### Special Treatment for Security Issues
@@ -374,7 +378,8 @@ A CHANGELOG entry should summarize what was changed and should end with the auth
*Your Name*
```
-Your name can be added directly after the last word if you don't provide any code examples or don't need multiple paragraphs. Otherwise, it's best to make as a new paragraph.
+Your name can be added directly after the last word if there are no code
+examples or multiple paragraphs. Otherwise, it's best to make a new paragraph.
### Updating the Gemfile.lock
@@ -398,21 +403,27 @@ When you're happy with the code on your computer, you need to commit the changes
$ git commit -a
```
-At this point, your editor should be fired up and you can write a message for this commit. Well formatted and descriptive commit messages are extremely helpful for the others, especially when figuring out why given change was made, so please take the time to write it.
+This should fire up your editor to write a commit message. When you have
+finished, save and close to continue.
+
+A well-formatted and descriptive commit message is very helpful to others for
+understanding why the change was made, so please take the time to write it.
-Good commit message should be formatted according to the following example:
+A good commit message looks like this:
```
Short summary (ideally 50 characters or less)
-More detailed description, if necessary. It should be wrapped to 72
-characters. Try to be as descriptive as you can, even if you think that
-the commit content is obvious, it may not be obvious to others. You
-should add such description also if it's already present in bug tracker,
-it should not be necessary to visit a webpage to check the history.
+More detailed description, if necessary. It should be wrapped to
+72 characters. Try to be as descriptive as you can. Even if you
+think that the commit content is obvious, it may not be obvious
+to others. Add any description that is already present in the
+relevant issues; it should not be necessary to visit a webpage
+to check the history.
+
+The description section can have multiple paragraphs.
-Description can have multiple paragraphs and you can use code examples
-inside, just indent it with 4 spaces:
+Code examples can be embedded by indenting them with 4 spaces:
class ArticlesController
def index
@@ -422,13 +433,15 @@ inside, just indent it with 4 spaces:
You can also add bullet points:
-- you can use dashes or asterisks
+- make a bullet point by starting a line with either a dash (-)
+ or an asterisk (*)
-- also, try to indent next line of a point for readability, if it's too
- long to fit in 72 characters
+- wrap lines at 72 characters, and indent any additional lines
+ with 2 spaces for readability
```
-TIP. Please squash your commits into a single commit when appropriate. This simplifies future cherry picks, and also keeps the git log clean.
+TIP. Please squash your commits into a single commit when appropriate. This
+simplifies future cherry picks and keeps the git log clean.
### Update Your Branch
diff --git a/guides/source/debugging_rails_applications.md b/guides/source/debugging_rails_applications.md
index a9715fb837..c6863f68e6 100644
--- a/guides/source/debugging_rails_applications.md
+++ b/guides/source/debugging_rails_applications.md
@@ -129,9 +129,14 @@ TIP: By default, each log is created under `Rails.root/log/` and the log file is
### Log Levels
-When something is logged it's printed into the corresponding log if the log level of the message is equal or higher than the configured log level. If you want to know the current log level you can call the `Rails.logger.level` method.
-
-The available log levels are: `:debug`, `:info`, `:warn`, `:error`, `:fatal`, and `:unknown`, corresponding to the log level numbers from 0 up to 5 respectively. To change the default log level, use
+When something is logged, it's printed into the corresponding log if the log
+level of the message is equal or higher than the configured log level. If you
+want to know the current log level, you can call the `Rails.logger.level`
+method.
+
+The available log levels are: `:debug`, `:info`, `:warn`, `:error`, `:fatal`,
+and `:unknown`, corresponding to the log level numbers from 0 up to 5,
+respectively. To change the default log level, use
```ruby
config.log_level = :warn # In any environment initializer, or
diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md
index db4e81e32e..684a53e472 100644
--- a/guides/source/getting_started.md
+++ b/guides/source/getting_started.md
@@ -23,7 +23,7 @@ application from scratch. It does not assume that you have any prior experience
with Rails. However, to get the most out of it, you need to have some
prerequisites installed:
-* The [Ruby](https://www.ruby-lang.org/en/downloads) language version 1.9.3 or newer.
+* The [Ruby](https://www.ruby-lang.org/en/downloads) language version 2.2.2 or newer.
* The [RubyGems](https://rubygems.org) packaging system, which is installed with Ruby
versions 1.9 and later. To learn more about RubyGems, please read the [RubyGems Guides](http://guides.rubygems.org).
* A working installation of the [SQLite3 Database](https://www.sqlite.org).
@@ -50,7 +50,7 @@ code while accomplishing more than many other languages and frameworks.
Experienced Rails developers also report that it makes web application
development more fun.
-Rails is opinionated software. It makes the assumption that there is the "best"
+Rails is opinionated software. It makes the assumption that there is a "best"
way to do things, and it's designed to encourage that way - and in some cases to
discourage alternatives. If you learn "The Rails Way" you'll probably discover a
tremendous increase in productivity. If you persist in bringing old habits from
@@ -97,7 +97,7 @@ For more installation methods for most Operating Systems take a look at
```bash
$ ruby -v
-ruby 2.0.0p353
+ruby 2.2.2p95
```
Many popular UNIX-like OSes ship with an acceptable version of SQLite3.
diff --git a/guides/source/i18n.md b/guides/source/i18n.md
index 27f11ebbee..348c60a9d8 100644
--- a/guides/source/i18n.md
+++ b/guides/source/i18n.md
@@ -489,7 +489,9 @@ NOTE: The default locale loading mechanism in Rails does not load locale files i
Overview of the I18n API Features
---------------------------------
-You should have good understanding of using the i18n library now, knowing all necessary aspects of internationalizing a basic Rails application. In the following chapters, we'll cover it's features in more depth.
+You should have a good understanding of using the i18n library now and know how
+to internationalize a basic Rails application. In the following chapters, we'll
+cover its features in more depth.
These chapters will show examples using both the `I18n.translate` method as well as the [`translate` view helper method](http://api.rubyonrails.org/classes/ActionView/Helpers/TranslationHelper.html#method-i-translate) (noting the additional feature provide by the view helper method).
diff --git a/guides/source/layouts_and_rendering.md b/guides/source/layouts_and_rendering.md
index d1a01f87ab..737f392995 100644
--- a/guides/source/layouts_and_rendering.md
+++ b/guides/source/layouts_and_rendering.md
@@ -1073,9 +1073,14 @@ One way to use partials is to treat them as the equivalent of subroutines: as a
<%= render "shared/footer" %>
```
-Here, the `_ad_banner.html.erb` and `_footer.html.erb` partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.
-
-As you already could see from the previous sections of this guide, `yield` is a very powerful tool for cleaning up your layouts. Keep in mind that it's pure ruby, so you can use it almost everywhere. For example, we can use it to DRY form layout definition for several similar resources:
+Here, the `_ad_banner.html.erb` and `_footer.html.erb` partials could contain
+content that is shared by many pages in your application. You don't need to see
+the details of these sections when you're concentrating on a particular page.
+
+As seen in the previous sections of this guide, `yield` is a very powerful tool
+for cleaning up your layouts. Keep in mind that it's pure Ruby, so you can use
+it almost everywhere. For example, we can use it to DRY up form layout
+definitions for several similar resources:
* `users/index.html.erb`
diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md
index 74240c1d16..0aa2152d56 100644
--- a/guides/source/upgrading_ruby_on_rails.md
+++ b/guides/source/upgrading_ruby_on_rails.md
@@ -298,7 +298,7 @@ end
The migration DSL has been expanded to support foreign key definitions. If
you've been using the Foreigner gem, you might want to consider removing it.
Note that the foreign key support of Rails is a subset of Foreigner. This means
-that not every Foreigner definition can be fully replaced by it's Rails
+that not every Foreigner definition can be fully replaced by its Rails
migration DSL counterpart.
The migration procedure is as follows:
diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md
index da11f337ad..43eee9f442 100644
--- a/railties/CHANGELOG.md
+++ b/railties/CHANGELOG.md
@@ -1,8 +1,13 @@
-* Rename `railties/bin` to `railties/exe` to match the new Bundler executables convention.
+* Remove sqlite support from `rails dbconsole`.
+
+ *Andrew White*
+
+* Rename `railties/bin` to `railties/exe` to match the new Bundler executables
+ convention.
*Islam Wazery*
-* Print `bundle install` output in `rails new` as soon as it's available
+* Print `bundle install` output in `rails new` as soon as it's available.
Running `rails new` will now print the output of `bundle install` as
it is available, instead of waiting until all gems finish installing.
@@ -22,7 +27,7 @@
*arthurnn*
-* Add `rake initializers`
+* Add `rake initializers`.
This task prints out all defined initializers in the order they are invoked
by Rails. This is helpful for debugging issues related to the initialization
@@ -37,7 +42,7 @@
*Hyonjee Joo*
-* Add `config/initializers/active_record_belongs_to_required_by_default.rb`
+* Add `config/initializers/active_record_belongs_to_required_by_default.rb`.
Newly generated Rails apps have a new initializer called
`active_record_belongs_to_required_by_default.rb` which sets the value of
@@ -56,7 +61,7 @@
'No such middleware' errors when `insert_before` or `insert_after` are added
after the `delete` operation for the middleware being deleted.
- Fixes: #16433.
+ Fixes #16433.
*Guo Xiang Tan*
@@ -68,7 +73,7 @@
*Xavier Noria*
-* Force generated routes to be inserted into routes.rb
+* Force generated routes to be inserted into `config/routes.rb`.
*Andrew White*
@@ -82,11 +87,12 @@
*Melanie Gilman*
-* Add the `method_source` gem to the default Gemfile for apps
+* Add the `method_source` gem to the default Gemfile for apps.
*Sean Griffin*
-* Drop old test locations from `rake stats`
+* Drop old test locations from `rake stats`:
+
- test/functional
- test/unit
@@ -117,7 +123,7 @@
*Andrew Kozlov*
-* Add `config/initializers/callback_terminator.rb`
+* Add `config/initializers/callback_terminator.rb`.
Newly generated Rails apps have a new initializer called
`callback_terminator.rb` which sets the value of the configuration option
diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb
index 3e3ef72742..a65f8f2ad9 100644
--- a/railties/lib/rails/application.rb
+++ b/railties/lib/rails/application.rb
@@ -1,4 +1,5 @@
require 'fileutils'
+require 'yaml'
require 'active_support/core_ext/hash/keys'
require 'active_support/core_ext/object/blank'
require 'active_support/key_generator'
@@ -228,7 +229,6 @@ module Rails
yaml = Pathname.new("#{paths["config"].existent.first}/#{name}.yml")
if yaml.exist?
- require "yaml"
require "erb"
(YAML.load(ERB.new(yaml.read).result) || {})[Rails.env] || {}
else
diff --git a/railties/lib/rails/commands/commands_tasks.rb b/railties/lib/rails/commands/commands_tasks.rb
index d8d4080c3e..685d55eea8 100644
--- a/railties/lib/rails/commands/commands_tasks.rb
+++ b/railties/lib/rails/commands/commands_tasks.rb
@@ -151,6 +151,17 @@ EOT
puts HELP_MESSAGE
end
+ # Output an error message stating that the attempted command is not a valid rails command.
+ # Run the attempted command as a rake command with the --dry-run flag. If successful, suggest
+ # to the user that they possibly meant to run the given rails command as a rake command.
+ # Append the help message.
+ #
+ # Example:
+ # $ rails db:migrate
+ # Error: Command 'db:migrate' not recognized
+ # Did you mean: `$ rake db:migrate` ?
+ # (Help message output)
+ #
def write_error_message(command)
puts "Error: Command '#{command}' not recognized"
if %x{rake #{command} --dry-run 2>&1 } && $?.success?
diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb
index 5175e31f14..3b22b582cf 100644
--- a/railties/lib/rails/commands/dbconsole.rb
+++ b/railties/lib/rails/commands/dbconsole.rb
@@ -50,9 +50,6 @@ module Rails
ENV['PGPASSWORD'] = config["password"].to_s if config["password"] && options['include_password']
find_cmd_and_exec('psql', config["database"])
- when "sqlite"
- find_cmd_and_exec('sqlite', config["database"])
-
when "sqlite3"
args = []
@@ -89,7 +86,7 @@ module Rails
find_cmd_and_exec("sqsh", *args)
else
- abort "Unknown command-line client for #{config['database']}. Submit a Rails patch to add support!"
+ abort "Unknown command-line client for #{config['database']}."
end
end
diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb
index 10deeb0ba2..119a7cb829 100644
--- a/railties/lib/rails/generators/app_base.rb
+++ b/railties/lib/rails/generators/app_base.rb
@@ -336,7 +336,7 @@ module Rails
end
def spring_install?
- !options[:skip_spring] && Process.respond_to?(:fork) && !RUBY_PLATFORM.include?("cygwin")
+ !options[:skip_spring] && !options.dev? && Process.respond_to?(:fork) && !RUBY_PLATFORM.include?("cygwin")
end
def run_bundle
diff --git a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
index d9713b0238..d99b27cb2d 100644
--- a/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
+++ b/railties/lib/rails/generators/erb/scaffold/templates/_form.html.erb
@@ -17,6 +17,7 @@
<%%= f.label :password %><br>
<%%= f.password_field :password %>
</div>
+
<div class="field">
<%%= f.label :password_confirmation %><br>
<%%= f.password_field :password_confirmation %>
@@ -25,6 +26,7 @@
<%%= f.<%= attribute.field_type %> :<%= attribute.column_name %> %>
<% end -%>
</div>
+
<% end -%>
<div class="actions">
<%%= f.submit %>
diff --git a/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css b/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css
index 69af1e8307..b7818883d1 100644
--- a/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css
+++ b/railties/lib/rails/generators/rails/scaffold/templates/scaffold.css
@@ -1,8 +1,11 @@
-body { background-color: #fff; color: #333; }
+body {
+ background-color: #fff;
+ color: #333;
+}
body, p, ol, ul, td {
font-family: verdana, arial, helvetica, sans-serif;
- font-size: 13px;
+ font-size: 13px;
line-height: 18px;
margin: 33px;
}
@@ -13,9 +16,18 @@ pre {
font-size: 11px;
}
-a { color: #000; }
-a:visited { color: #666; }
-a:hover { color: #fff; background-color:#000; }
+a {
+ color: #000;
+}
+
+a:visited {
+ color: #666;
+}
+
+a:hover {
+ color: #fff;
+ background-color: #000;
+}
th {
padding-bottom: 5px;
@@ -27,7 +39,8 @@ td {
padding-right: 5px;
}
-div.field, div.actions {
+div.field,
+div.actions {
margin-bottom: 10px;
}
@@ -56,7 +69,7 @@ div.field, div.actions {
padding: 5px 5px 5px 15px;
font-size: 12px;
margin: -7px;
- margin-bottom: 0px;
+ margin-bottom: 0;
background-color: #c00;
color: #fff;
}
diff --git a/railties/lib/rails/templates/rails/welcome/index.html.erb b/railties/lib/rails/templates/rails/welcome/index.html.erb
index 6726c23fc9..acf04af416 100644
--- a/railties/lib/rails/templates/rails/welcome/index.html.erb
+++ b/railties/lib/rails/templates/rails/welcome/index.html.erb
@@ -18,7 +18,9 @@
color: #000;
}
- a {color: #03c}
+ a {
+ color: #03c;
+ }
a:hover {
background-color: #03c;
@@ -64,7 +66,10 @@
height: 64px;
}
- #header h1, #header h2 {margin: 0}
+ #header h1,
+ #header h2 {
+ margin: 0;
+ }
#header h2 {
color: #888;
@@ -104,7 +109,9 @@
color: #555;
}
- #about-content td.value {color: #000}
+ #about-content td.value {
+ color: #000;
+ }
#about-content ul {
padding: 0;
diff --git a/railties/test/commands/dbconsole_test.rb b/railties/test/commands/dbconsole_test.rb
index a3cd1eb0ed..2e8dd99f36 100644
--- a/railties/test/commands/dbconsole_test.rb
+++ b/railties/test/commands/dbconsole_test.rb
@@ -158,12 +158,6 @@ class Rails::DBConsoleTest < ActiveSupport::TestCase
assert_equal 'q1w2e3', ENV['PGPASSWORD']
end
- def test_sqlite
- start(adapter: 'sqlite', database: 'db')
- assert !aborted
- assert_equal ['sqlite', 'db'], dbconsole.find_cmd_and_exec_args
- end
-
def test_sqlite3
start(adapter: 'sqlite3', database: 'db.sqlite3')
assert !aborted
diff --git a/railties/test/generators/app_generator_test.rb b/railties/test/generators/app_generator_test.rb
index 282e8cc4f9..2bfa05a0b8 100644
--- a/railties/test/generators/app_generator_test.rb
+++ b/railties/test/generators/app_generator_test.rb
@@ -560,6 +560,14 @@ class AppGeneratorTest < Rails::Generators::TestCase
end
end
+ def test_spring_with_dev_option
+ run_generator [destination_root, "--dev"]
+
+ assert_file "Gemfile" do |content|
+ assert_no_match(/spring/, content)
+ end
+ end
+
def test_generator_if_skip_turbolinks_is_given
run_generator [destination_root, "--skip-turbolinks"]