From d75f4dcb0efe7f9986ca69dbe7379075ebda00dd Mon Sep 17 00:00:00 2001 From: Zuhao Wan Date: Sat, 28 Jun 2014 17:57:27 +0800 Subject: Cleanup loaded features and constants after dependency tests. --- activesupport/test/dependencies_test.rb | 216 +++++++++++++++++--------------- 1 file changed, 116 insertions(+), 100 deletions(-) diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index a013aadd67..5262754076 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' @@ -51,8 +56,7 @@ class DependenciesTest < ActiveSupport::TestCase require_dependency 'dependencies/service_two' assert_equal 2, ActiveSupport::Dependencies.loaded.size 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 @@ -60,7 +64,7 @@ class DependenciesTest < ActiveSupport::TestCase require_dependency 'dependencies/service_one' assert_equal 1, ActiveSupport::Dependencies.loaded.size ensure - Object.send(:remove_const, :ServiceOne) if Object.const_defined?(:ServiceOne) + remove_constants(:ServiceOne) end def test_missing_dependency_raises_missing_source_file @@ -89,7 +93,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 @@ -97,7 +100,6 @@ 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 @@ -174,43 +176,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 @@ -218,8 +226,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 @@ -227,16 +236,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 @@ -248,15 +256,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 @@ -271,14 +277,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 @@ -286,14 +290,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 @@ -302,14 +304,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 @@ -318,7 +318,6 @@ class DependenciesTest < ActiveSupport::TestCase end ensure remove_constants(:LoadedConstant) - $".replace(original_features) $:.replace(original_path) end @@ -326,14 +325,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 @@ -342,7 +338,6 @@ class DependenciesTest < ActiveSupport::TestCase end ensure remove_constants(:LoadedConstant) - $".replace(original_features) $:.replace(original_path) end @@ -350,16 +345,13 @@ 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 end @@ -373,6 +365,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 @@ -462,9 +456,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 @@ -522,6 +516,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 @@ -530,6 +526,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 @@ -541,6 +539,8 @@ 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 @@ -553,6 +553,8 @@ class DependenciesTest < ActiveSupport::TestCase 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 @@ -562,17 +564,20 @@ class DependenciesTest < ActiveSupport::TestCase assert_equal service_one_first, c.get("ServiceOne") ActiveSupport::Dependencies.clear assert ! 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 @@ -584,19 +589,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 @@ -605,15 +611,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 @@ -623,6 +629,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 @@ -638,9 +646,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 @@ -649,6 +656,8 @@ class DependenciesTest < ActiveSupport::TestCase assert ActiveSupport::Dependencies.autoloaded?("HTML::SomeClass") end + ensure + remove_constants(:HTML) end def test_unloadable @@ -679,7 +688,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 @@ -690,7 +699,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 @@ -704,7 +713,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 @@ -721,9 +730,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 @@ -742,7 +749,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 @@ -760,7 +767,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 @@ -778,26 +785,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 @@ -808,15 +816,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' @@ -827,15 +837,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 @@ -846,9 +858,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 @@ -859,9 +873,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 @@ -872,9 +885,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 @@ -884,11 +896,12 @@ class DependenciesTest < ActiveSupport::TestCase assert_raise(NameError) { assert_equal 123, ::RaisesNameError::FooBarBaz } end end + ensure + remove_constants(:RaisesNameError) end 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 @@ -903,19 +916,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 @@ -925,7 +939,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 @@ -934,11 +950,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" @@ -947,8 +966,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 @@ -960,23 +979,27 @@ 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 @@ -990,11 +1013,4 @@ class DependenciesTest < ActiveSupport::TestCase ensure ActiveSupport::Dependencies.hook! end - -private - def remove_constants(*constants) - constants.each do |constant| - Object.send(:remove_const, constant) if Object.const_defined?(constant) - end - end end -- cgit v1.2.3 From cc405496ce85ee0073268baefdb2be5d4b062f91 Mon Sep 17 00:00:00 2001 From: Ben Woosley Date: Tue, 18 Jun 2013 15:10:48 -0700 Subject: =?UTF-8?q?Fix=20that=20a=20collection=20proxy=20could=20be=20cach?= =?UTF-8?q?ed=20before=20the=20save=20of=20the=20owner,=20resulting=20in?= =?UTF-8?q?=20an=20invalid=20proxy=20lacking=20the=20owner=E2=80=99s=20id.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Absent this fix calls like: owner.association.update_all to behave unexpectedly because they try to act on association objects where owner_id is null. more evidence here: https://gist.github.com/Empact/5865555 ``` Active Record 3.2.13 -- create_table(:firms, {:force=>true}) -> 0.1371s -- create_table(:clients, {:force=>true}) -> 0.0005s 1 clients. 1 expected. 1 clients updated. 1 expected. ``` ``` Active Record 4.0.0 -- create_table(:firms, {:force=>true}) -> 0.1606s -- create_table(:clients, {:force=>true}) -> 0.0004s 1 clients. 1 expected. 0 clients updated. 1 expected. ``` --- activerecord/CHANGELOG.md | 6 ++++++ .../lib/active_record/associations/collection_association.rb | 8 +++++++- .../test/cases/associations/has_many_associations_test.rb | 7 +++++++ 3 files changed, 20 insertions(+), 1 deletion(-) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 210151a2ad..92e1575484 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,9 @@ +* 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* + * Honor overridden `rack.test` in Rack environment for the connection management middleware. diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 1836ff0910..c5dff7ee1a 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 diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index e34b993029..c72d9342a9 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -387,6 +387,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" -- cgit v1.2.3 From 3cc25864e34fb5b22b1ecacaaf91825841a5eebd Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Mon, 6 Oct 2014 12:33:07 +0800 Subject: Allow authentication header to not have to specify 'token=' key. Fixes: https://github.com/rails/rails/issues/17108. --- .../action_controller/metal/http_authentication.rb | 11 +++++++++-- .../controller/http_token_authentication_test.rb | 23 ++++++++++++++++++++-- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb index 25c123edf7..167df2f935 100644 --- a/actionpack/lib/action_controller/metal/http_authentication.rb +++ b/actionpack/lib/action_controller/metal/http_authentication.rb @@ -397,6 +397,7 @@ module ActionController # # RewriteRule ^(.*)$ dispatch.fcgi [E=X-HTTP_AUTHORIZATION:%{HTTP:Authorization},QSA,L] module Token + TOKEN_KEY = 'token=' TOKEN_REGEX = /^Token / AUTHN_PAIR_DELIMITERS = /(?:,|;|\t+)/ extend self @@ -471,7 +472,13 @@ module ActionController # pairs by the standardized `:`, `;`, or `\t` delimiters defined in # `AUTHN_PAIR_DELIMITERS`. def raw_params(auth) - auth.sub(TOKEN_REGEX, '').split(/\s*#{AUTHN_PAIR_DELIMITERS}\s*/) + _raw_params = auth.sub(TOKEN_REGEX, '').split(/\s*#{AUTHN_PAIR_DELIMITERS}\s*/) + + if !(_raw_params.first =~ %r{\A#{TOKEN_KEY}}) + _raw_params[0] = "#{TOKEN_KEY}#{_raw_params.first}" + end + + _raw_params end # Encodes the given token and options into an Authorization header value. @@ -481,7 +488,7 @@ module ActionController # # Returns String. def encode_credentials(token, options = {}) - values = ["token=#{token.to_s.inspect}"] + options.map do |key, value| + values = ["#{TOKEN_KEY}#{token.to_s.inspect}"] + options.map do |key, value| "#{key}=#{value.to_s.inspect}" end "Token #{values * ", "}" diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb index 8c6c8a0aa7..a758df2ec6 100644 --- a/actionpack/test/controller/http_token_authentication_test.rb +++ b/actionpack/test/controller/http_token_authentication_test.rb @@ -162,17 +162,36 @@ class HttpTokenAuthenticationTest < ActionController::TestCase assert_equal(expected, actual) end + test "token_and_options returns right token when token key is not specified in header" do + token = "rcHu+HzSFw89Ypyhn/896A=" + + actual = ActionController::HttpAuthentication::Token.token_and_options( + sample_request_without_token_key(token) + ).first + + expected = token + assert_equal(expected, actual) + end + private def sample_request(token, options = {nonce: "def"}) authorization = options.inject([%{Token token="#{token}"}]) do |arr, (k, v)| arr << "#{k}=\"#{v}\"" end.join(", ") - @sample_request ||= OpenStruct.new authorization: authorization + mock_authorization_request(authorization) end def malformed_request - @malformed_request ||= OpenStruct.new authorization: %{Token token=} + mock_authorization_request(%{Token token=}) + end + + def sample_request_without_token_key(token) + mock_authorization_request(%{Token #{token}}) + end + + def mock_authorization_request(authorization) + OpenStruct.new(authorization: authorization) end def encode_credentials(token, options = {}) -- cgit v1.2.3 From 0f3cefa445c6b43711b29f38257adcedede74baa Mon Sep 17 00:00:00 2001 From: Byron Bischoff Date: Wed, 22 Oct 2014 11:39:47 -0700 Subject: =?UTF-8?q?copy=20reflection=5Fscopes=E2=80=99s=20unscoped=20value?= =?UTF-8?q?=20when=20building=20scope=20for=20preloading,=20fixes=20#11036?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../lib/active_record/associations/preloader/association.rb | 4 ++++ .../test/cases/associations/has_many_associations_test.rb | 8 ++++++++ 2 files changed, 12 insertions(+) diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index c0639742be..2300435f91 100644 --- a/activerecord/lib/active_record/associations/preloader/association.rb +++ b/activerecord/lib/active_record/associations/preloader/association.rb @@ -136,6 +136,10 @@ module ActiveRecord preload_values = preload_scope.values preload_binds = preload_scope.bind_values + if values[:unscope] + scope.unscope! values[:unscope] + end + scope.where_values = Array(values[:where]) + Array(preload_values[:where]) scope.references_values = Array(values[:references]) + Array(preload_values[:references]) scope.bind_values = (reflection_binds + preload_binds) diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index e34b993029..fdbe411f86 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1895,6 +1895,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) -- cgit v1.2.3 From 28eb085cdf989395957cbc50c7e1bb981e70ff9b Mon Sep 17 00:00:00 2001 From: Vipul A M Date: Sat, 1 Nov 2014 16:45:31 +0530 Subject: - Remove unused duplicated method `add_column_position` from AbstractMysqlAdapter --- .../active_record/connection_adapters/abstract_mysql_adapter.rb | 8 -------- 1 file changed, 8 deletions(-) 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 7f04e35042..5f512758e9 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -585,14 +585,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') -- cgit v1.2.3 From 98626e27c1bd4f55915dbf94a24868785638094d Mon Sep 17 00:00:00 2001 From: Ryan Selk Date: Sat, 1 Nov 2014 17:58:26 +0100 Subject: Add a section about job testing [ci skip] * Cover lower level job testing (assertions about the execution of the job itself). * Add a table with the custom assertions provided by Active Job's `TestHelper` module. * Add an example testing job queuing inside a model --- guides/source/testing.md | 62 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/guides/source/testing.md b/guides/source/testing.md index b784098fbb..ca88d0caf8 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -1043,6 +1043,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 ------------------------ -- cgit v1.2.3 From db5f1a46f26ed2b8359d3dde3398dd1a8ca443d4 Mon Sep 17 00:00:00 2001 From: Benjamin Fleischer Date: Mon, 27 Oct 2014 12:04:37 -0500 Subject: `secret_token` is now saved in `Rails.application.secrets.secret_token` - `secrets.secret_token` is now used in all places `config.secret_token` was - `secrets.secret_token`, when not present in `config/secrets.yml`, now falls back to the value of `config.secret_token` - when `secrets.secret_token` is set, it over-writes `config.secret_token` so they are the same (for backwards-compatibility) - Update docs to reference app.secrets in all places - Remove references to `config.secret_token`, `config.secret_key_base` - Warn that missing secret_key_base is deprecated - Add tests for secret_token, key_generator, and message_verifier - the legacy key generator is used with the message verifier when secrets.secret_key_base is blank and secret_token is set - app.key_generator raises when neither secrets.secret_key_base nor secret_token are set - app.env_config raises when neither secrets.secret_key_base nor secret_token are set - Add changelog Run focused tests via ruby -w -Itest test/application/configuration_test.rb -n '/secret_|key_/' --- .../lib/action_dispatch/middleware/cookies.rb | 8 +- .../bug_report_templates/action_controller_gem.rb | 4 +- .../action_controller_master.rb | 4 +- railties/CHANGELOG.md | 6 + railties/lib/rails/application.rb | 20 ++- railties/test/application/configuration_test.rb | 137 +++++++++++++++++++++ .../test/application/middleware/session_test.rb | 8 +- .../test/application/multiple_applications_test.rb | 14 ++- railties/test/application/url_generation_test.rb | 2 +- 9 files changed, 180 insertions(+), 23 deletions(-) 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/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/railties/CHANGELOG.md b/railties/CHANGELOG.md index 2960eccb3f..7b50ffbd76 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -1,3 +1,9 @@ +* `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. diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index bc966e87c6..78b8a90432 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -175,7 +175,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 +245,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, @@ -378,6 +378,13 @@ module Rails # Fallback to config.secret_key_base if secrets.secret_key_base isn't set secrets.secret_key_base ||= config.secret_key_base + # Sync secrets.secret_token with config.secret_token, preferring secrets.secret_token + # note that unset config's default to "", secrets default to nil + if secrets.secret_token.blank? && config.secret_token.present? + secrets.secret_token = config.secret_token + elsif secrets.secret_token.present? + config.secret_token = secrets.secret_token + end secrets end @@ -507,8 +514,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/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 0eddf644d9..98355e273a 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -301,6 +301,53 @@ 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 "uses secrets.secret_token when secrets.secret_key_base and config.secret_token are 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: + secret_token: 3b7cd727ee24e8444053437c36cc66c3 + YAML + require "#{app_path}/config/environment" + + assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token + assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.config.secret_token + end + test "application verifier can build different verifiers" do make_basic_app do |app| app.secrets.secret_key_base = 'b3c631c314c0bbca50c1b2843150fe33' @@ -341,6 +388,51 @@ 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 "secret_token is copied from secrets to config when set" 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: + secret_token: 3b7cd727ee24e8444053437c36cc66c3 + YAML + require "#{app_path}/config/environment" + + assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token + assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.config.secret_token + end + + test "secret_token is copied from secrets to config when different" 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: 3b7cd727ee24e8444053437c36cc66c3 + YAML + require "#{app_path}/config/environment" + + assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token + assert_equal '3b7cd727ee24e8444053437c36cc66c3', 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 +454,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 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/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 -- cgit v1.2.3 From 2e085f67d4132ac8e01dae5a4428014f51fd4829 Mon Sep 17 00:00:00 2001 From: Peter West Date: Mon, 3 Nov 2014 16:34:44 +0000 Subject: Delegate comparison operator to value --- activesupport/lib/active_support/duration.rb | 2 ++ activesupport/test/core_ext/duration_test.rb | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb index 584fc1e1c5..fde2d0bf79 100644 --- a/activesupport/lib/active_support/duration.rb +++ b/activesupport/lib/active_support/duration.rb @@ -103,6 +103,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/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb index 5a2af7f943..5a7b624ae1 100644 --- a/activesupport/test/core_ext/duration_test.rb +++ b/activesupport/test/core_ext/duration_test.rb @@ -200,4 +200,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 -- cgit v1.2.3 From c7f2ee2213b929b2db99da1db801980b38f0e15c Mon Sep 17 00:00:00 2001 From: Genadi Samokovarov Date: Sat, 1 Nov 2014 23:14:42 +0200 Subject: Move DebugExceptions#traces_from_wrapper to ExceptionWrapper ActionDispatch::ExceptionWrapper seems to be the more natural place for this method to live in. --- .../action_dispatch/middleware/debug_exceptions.rb | 30 +--------------------- .../middleware/exception_wrapper.rb | 22 ++++++++++++++++ 2 files changed, 23 insertions(+), 29 deletions(-) diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb index ff72592b94..798c087d64 100644 --- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb @@ -35,7 +35,7 @@ module ActionDispatch if env['action_dispatch.show_detailed_exceptions'] request = Request.new(env) - traces = traces_from_wrapper(wrapper) + traces = wrapper.traces trace_to_show = 'Application Trace' if traces[trace_to_show].empty? @@ -106,33 +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 - - appplication_trace_with_ids = [] - framework_trace_with_ids = [] - full_trace_with_ids = [] - - if full_trace - full_trace.each_with_index do |trace, idx| - id_trace = { - id: idx, - trace: trace - } - appplication_trace_with_ids << id_trace if application_trace.include? trace - framework_trace_with_ids << id_trace if framework_trace.include? trace - full_trace_with_ids << id_trace - end - end - { - "Application Trace" => appplication_trace_with_ids, - "Framework Trace" => framework_trace_with_ids, - "Full Trace" => full_trace_with_ids - } - end end end diff --git a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb index a6285848b5..e0140b0692 100644 --- a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb +++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb @@ -57,6 +57,28 @@ module ActionDispatch clean_backtrace(:all) end + def traces + appplication_trace_with_ids = [] + framework_trace_with_ids = [] + full_trace_with_ids = [] + + if full_trace + full_trace.each_with_index do |trace, idx| + trace_with_id = { id: idx, trace: trace } + + appplication_trace_with_ids << trace_with_id if application_trace.include?(trace) + framework_trace_with_ids << trace_with_id if framework_trace.include?(trace) + full_trace_with_ids << trace_with_id + end + 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 -- cgit v1.2.3 From 8355b48c37157dabf31baeb5f0af9ad403a6141b Mon Sep 17 00:00:00 2001 From: Jason Perrin Date: Mon, 3 Nov 2014 19:14:14 -0700 Subject: Correct test description for large integer test --- activerecord/test/cases/type/integer_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/test/cases/type/integer_test.rb b/activerecord/test/cases/type/integer_test.rb index 53d6a3a6aa..5942f77e18 100644 --- a/activerecord/test/cases/type/integer_test.rb +++ b/activerecord/test/cases/type/integer_test.rb @@ -68,7 +68,7 @@ module ActiveRecord end end - test "very large numbers are in range" do + test "very large numbers are out of range" do assert_raises(::RangeError) do Integer.new.type_cast_from_user("9999999999999999999999999999999") end -- cgit v1.2.3 From 9007b789e197ad0445a03b591f982a44b92f715d Mon Sep 17 00:00:00 2001 From: Ted O'Meara Date: Thu, 30 Oct 2014 14:01:38 -0400 Subject: Added SchemaDumper support for tables with jsonb columns. --- activerecord/CHANGELOG.md | 4 ++++ .../connection_adapters/postgresql_adapter.rb | 1 + activerecord/test/cases/adapters/postgresql/json_test.rb | 8 ++++++++ activerecord/test/cases/schema_dumper_test.rb | 7 ------- activerecord/test/schema/postgresql_specific_schema.rb | 15 ++++----------- 5 files changed, 17 insertions(+), 18 deletions(-) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index f7ca41908d..1961ba93c6 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,7 @@ +* 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. diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index e472741660..9941f74766 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -104,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" }, diff --git a/activerecord/test/cases/adapters/postgresql/json_test.rb b/activerecord/test/cases/adapters/postgresql/json_test.rb index 86ba849445..7a9fdd45e8 100644 --- a/activerecord/test/cases/adapters/postgresql/json_test.rb +++ b/activerecord/test/cases/adapters/postgresql/json_test.rb @@ -3,8 +3,11 @@ 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 +67,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/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index 2241c41f36..6303393c22 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -271,13 +271,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/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, -- cgit v1.2.3 From 00d14936b039e841c5c0068cd8cccf0ec6b234d6 Mon Sep 17 00:00:00 2001 From: Prathamesh Sonpatki Date: Wed, 5 Nov 2014 00:42:04 +0530 Subject: Mention that articles resource should be added by user in getting started guide [ci skip] --- guides/source/getting_started.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 1769448531..92f8ef5b08 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -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 -- cgit v1.2.3 From 0d5a384498296f005395d02943bd18e688aba436 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 4 Nov 2014 14:14:03 -0800 Subject: add a test for #17106 --- railties/test/application/configuration_test.rb | 13 +++++++++++++ railties/test/isolation/abstract_unit.rb | 9 +++++++++ 2 files changed, 22 insertions(+) diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 0eddf644d9..2b9f1d9cc1 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -59,6 +59,19 @@ 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 + equire 'my_logger' + config.logger = MyLogger.new STDOUT + RUBY + require "#{app_path}/config/environment" + end + test "a renders exception on pending migration" do add_to_config <<-RUBY config.active_record.migration_error = :page_load diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index 40469e31d7..bf2992005b 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -231,6 +231,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/ -- cgit v1.2.3 From 4bcb0942241fe10d734b9777a61e0e0026cf0d5d Mon Sep 17 00:00:00 2001 From: Paul Annesley Date: Tue, 4 Nov 2014 13:58:09 -0800 Subject: activerecord: rake db:create shows underlying error message. --- activerecord/lib/active_record/tasks/mysql_database_tasks.rb | 1 + 1 file changed, 1 insertion(+) 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 -- cgit v1.2.3 From 9dbcac78113808da23dfe1e3e7b0cc6a390e03be Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 4 Nov 2014 14:54:52 -0800 Subject: add lib to $LOAD_PATH on application inhertence. fixes #17106 --- railties/lib/rails/application.rb | 13 ++++++++----- railties/lib/rails/engine.rb | 9 ++++++--- railties/test/application/configuration_test.rb | 3 ++- 3 files changed, 16 insertions(+), 9 deletions(-) diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index bc966e87c6..18d9cb72d6 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. @@ -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: diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index dc3da1eb41..d985518fd9 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -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/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 2b9f1d9cc1..2b6eb3624a 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -66,10 +66,11 @@ module ApplicationTests end RUBY add_to_top_of_config <<-RUBY - equire 'my_logger' + 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 -- cgit v1.2.3 From 4ea3e65c18c46de951b2eb78adce9230bb0869ff Mon Sep 17 00:00:00 2001 From: eileencodes Date: Mon, 3 Nov 2014 08:38:04 -0500 Subject: [ci skip] Fixup spelling and grammar in 4.2 guides Capitalize CSS, SQL Change spelling of favour to favor - updated for consistency, the rest of the document uses "favor". Grammar / spelling pass --- guides/source/4_2_release_notes.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index d9f49aac55..17894b2752 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -49,13 +49,13 @@ 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 it'll serialize it using GlobalID, and deserialize +it 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. +`find_by` methods 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 @@ -88,7 +88,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 @@ -196,9 +196,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. @@ -471,7 +471,7 @@ 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 @@ -479,7 +479,7 @@ Please refer to the [Changelog][action-pack] for detailed changes. ([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 + 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 @@ -537,7 +537,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 @@ -596,7 +596,7 @@ Please refer to the [Changelog][active-record] for detailed changes. ([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 + 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 @@ -648,7 +648,7 @@ Please refer to the [Changelog][active-record] for detailed changes. ([Commit](https://github.com/rails/rails/commit/e2f232aba15937a4b9d14bd91e0392c6d55be58d)) * `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), -- cgit v1.2.3 From d027e2759d1aa5235d562bc1063d3f957473c763 Mon Sep 17 00:00:00 2001 From: "yuuji.yaginuma" Date: Wed, 5 Nov 2014 15:21:10 +0900 Subject: [ci skip] fix `config.assets.digest` default value --- guides/source/configuring.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/configuring.md b/guides/source/configuring.md index 58c3f217eb..2957232186 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-.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`. -- cgit v1.2.3 From e130a0e7b476553c538075239554247e4196dd05 Mon Sep 17 00:00:00 2001 From: Prathamesh Sonpatki Date: Wed, 5 Nov 2014 14:27:07 +0530 Subject: Fix broken string_ext_test due to change in timezone - Russian time was changed to UTC+3 from UTC+4 recently. This broke the string_to_ext test. --- activesupport/test/core_ext/string_ext_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 35095f2b2d..b97aa56aef 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -418,7 +418,7 @@ class StringConversionsTest < ActiveSupport::TestCase 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 -- cgit v1.2.3 From e0109460526b9595007905475437ccbf77739e7f Mon Sep 17 00:00:00 2001 From: Prathamesh Sonpatki Date: Wed, 5 Nov 2014 12:01:06 +0530 Subject: Removed the unused require of proxy_object and test related to it - Reference : https://github.com/rails/rails/pull/17493#issuecomment-61739359 - Duration stopped inheriting from ProxyObject in https://github.com/rails/rails/pull/16574 --- activesupport/lib/active_support/duration.rb | 1 - activesupport/test/core_ext/duration_test.rb | 1 - 2 files changed, 2 deletions(-) diff --git a/activesupport/lib/active_support/duration.rb b/activesupport/lib/active_support/duration.rb index 584fc1e1c5..baa83223d2 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' diff --git a/activesupport/test/core_ext/duration_test.rb b/activesupport/test/core_ext/duration_test.rb index 5a2af7f943..a5d254e115 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 -- cgit v1.2.3 From c1116e954c89428b2611e3a595e257e83c47a633 Mon Sep 17 00:00:00 2001 From: Prathamesh Sonpatki Date: Wed, 5 Nov 2014 15:22:48 +0530 Subject: Remove skip-gems from 4-2 release notes - This option was removed in https://github.com/rails/rails/commit/bf17c8a531bc80. - [ci skip] --- guides/source/4_2_release_notes.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 17894b2752..94a3c728fe 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -358,10 +358,6 @@ 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)) - * Introduced a `bin/setup` script to enable automated setup code when bootstrapping an application. ([Pull Request](https://github.com/rails/rails/pull/15189)) -- cgit v1.2.3 From 768b4ea24de0080a29e5467cda0142f5de62c660 Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Wed, 5 Nov 2014 11:27:41 +0100 Subject: tests, add note about the usage of a specific timezone. Closes #17448. --- activesupport/test/core_ext/string_ext_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index b97aa56aef..119e62369d 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -414,7 +414,7 @@ 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) -- cgit v1.2.3 From 5da73d9181a4300f5ddbaca828d526d595c33355 Mon Sep 17 00:00:00 2001 From: Carlos Antonio da Silva Date: Wed, 5 Nov 2014 08:36:08 -0200 Subject: Add skip-turbolinks entry to 4.2 release notes and improve changelog [ci skip] --- guides/source/4_2_release_notes.md | 4 ++++ railties/CHANGELOG.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 94a3c728fe..3a9be62865 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -358,6 +358,10 @@ Please refer to the [Changelog][railties] for detailed changes. ([Pull Request](https://github.com/rails/rails/pull/16129)) +* 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. ([Pull Request](https://github.com/rails/rails/pull/15189)) diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md index 2960eccb3f..0d91b19ed2 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -89,7 +89,7 @@ *Rafael Mendonça França* -* Add a generic --skip-turbolinks options to generator. +* Add `--skip-turbolinks` option to the app generator. *Rafael Mendonça França* -- cgit v1.2.3 From e81c6efc0e05b1ad61bb573fa05cd3a70c32b08b Mon Sep 17 00:00:00 2001 From: Arun Agrawal Date: Wed, 5 Nov 2014 13:54:50 +0100 Subject: Update `bin/rake about` [ci skip] As we are no more displaying frameworks --- guides/source/command_line.md | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/guides/source/command_line.md b/guides/source/command_line.md index b9014724bd..e065d56168 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -394,16 +394,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, #, 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 -- cgit v1.2.3 From 9511801a6de3ad48a0bd9a8ab57e02e2186e154d Mon Sep 17 00:00:00 2001 From: Arun Agrawal Date: Wed, 5 Nov 2014 14:17:37 +0100 Subject: Add test/jobs files in `rake stats` --- railties/lib/rails/code_statistics.rb | 1 + railties/lib/rails/tasks/statistics.rake | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) 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/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) } -- cgit v1.2.3 From 76f5a9afb35e52bbdc392d6fc35422e22be987c2 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Wed, 5 Nov 2014 23:38:02 +0800 Subject: Remove session to allow `with_routing` to be called twice. Fixes: https://github.com/rails/rails/issues/16814 --- .../lib/action_dispatch/testing/integration.rb | 4 +++ actionpack/test/abstract_unit.rb | 1 + actionpack/test/controller/integration_test.rb | 36 ++++++++++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index c300a4ea0d..fb816aa875 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -326,6 +326,10 @@ 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| 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/integration_test.rb b/actionpack/test/controller/integration_test.rb index d91a1657b3..27b30536b0 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -814,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 -- cgit v1.2.3 From 8fee923888192a658d8823b31e77ed0683dfd665 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Wed, 5 Nov 2014 10:59:50 -0700 Subject: Improve performance of AR object instantiation We introduced a performance hit by adding an additional iteration through a model's attributes on creation. We don't actually need the values from `Result` to be a hash, we can separate the columns and values and zip them up ourself during the iteration that we have to do. --- .../lib/active_record/attribute_set/builder.rb | 21 +++++++++++++--- activerecord/lib/active_record/inheritance.rb | 12 ++++++---- activerecord/lib/active_record/persistence.rb | 28 +++++++++++++++++++--- activerecord/lib/active_record/querying.rb | 2 +- activerecord/lib/active_record/result.rb | 9 +++++++ 5 files changed, 61 insertions(+), 11 deletions(-) diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb index d4a787f2fe..92640f1579 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -8,18 +8,33 @@ module ActiveRecord end def build_from_database(values = {}, additional_types = {}) - attributes = build_attributes_from_values(values, additional_types) + build_from_database_pairs(values.keys, values.values, additional_types) + end + + def build_from_database_pairs(columns = [], values = [], additional_types = {}) + attributes = build_attributes_from_values(columns, values, additional_types) add_uninitialized_attributes(attributes) AttributeSet.new(attributes) end private - def build_attributes_from_values(values, additional_types) - values.each_with_object({}) do |(name, value), hash| + def build_attributes_from_values(columns, values, additional_types) + # We are performing manual iteration here as this method is a performance + # hotspot + hash = {} + index = 0 + length = columns.length + + while index < length + name = columns[index] + value = values[index] type = additional_types.fetch(name, types[name]) hash[name] = Attribute.from_database(name, value, type) + index += 1 end + + hash end def add_uninitialized_attributes(attributes) diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb index f58145ab05..4aad3217cb 100644 --- a/activerecord/lib/active_record/inheritance.rb +++ b/activerecord/lib/active_record/inheritance.rb @@ -165,15 +165,19 @@ module ActiveRecord # record instance. For single-table inheritance, we check the record # for a +type+ column and return the corresponding class. def discriminate_class_for_record(record) - if using_single_table_inheritance?(record) - find_sti_class(record[inheritance_column]) + discriminate_class_for_value(record[inheritance_column]) + end + + def discriminate_class_for_value(value) + if using_single_table_inheritance?(value) + find_sti_class(value) else super end end - def using_single_table_inheritance?(record) - record[inheritance_column].present? && columns_hash.include?(inheritance_column) + def using_single_table_inheritance?(value) + value.present? && columns_hash.include?(inheritance_column) end def find_sti_class(type_name) diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index 755ff2b2f1..9d2c9d3b9c 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -65,19 +65,41 @@ module ActiveRecord # how this "single-table" inheritance mapping is implemented. def instantiate(attributes, column_types = {}) klass = discriminate_class_for_record(attributes) - attributes = klass.attributes_builder.build_from_database(attributes, column_types) - klass.allocate.init_with('attributes' => attributes, 'new_record' => false) + klass.instantiate_pairs(attributes.keys, attributes.values, column_types) + end + + def instantiate_pairs(columns, values, column_types = {}) # :nodoc: + attributes = attributes_builder.build_from_database_pairs(columns, values, column_types) + allocate.init_with('attributes' => attributes, 'new_record' => false) + end + + def instantiate_result_set(result_set, column_types = {}) # :nodoc: + inheritance_column_index = inheritance_column && result_set.columns.find_index(inheritance_column) + + result_set.each_pair.map do |columns, values| + inheritance_value = inheritance_column_index && values[inheritance_column_index] + klass = discriminate_class_for_value(inheritance_value) + klass.instantiate_pairs(columns, values, column_types) + end end private # Called by +instantiate+ to decide which class to use for a new # record instance. # - # See +ActiveRecord::Inheritance#discriminate_class_for_record+ for + # See +ActiveRecord::Inheritance#discriminate_class_for_value+ for # the single-table inheritance discriminator. + def discriminate_class_for_value(*) + self + end + def discriminate_class_for_record(record) self end + + def inheritance_column + nil + end end # Returns true if this object hasn't been saved yet -- that is, a record diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb index e8de4db3a7..9d4df81b07 100644 --- a/activerecord/lib/active_record/querying.rb +++ b/activerecord/lib/active_record/querying.rb @@ -47,7 +47,7 @@ module ActiveRecord } message_bus.instrument('instantiation.active_record', payload) do - result_set.map { |record| instantiate(record, column_types) } + instantiate_result_set(result_set, column_types) end end diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb index 3a3e65ef32..c84ad586e2 100644 --- a/activerecord/lib/active_record/result.rb +++ b/activerecord/lib/active_record/result.rb @@ -54,6 +54,15 @@ module ActiveRecord end end + def each_pair + return to_enum(__method__) unless block_given? + + columns = @columns.map { |c| c.dup.freeze } + @rows.each do |row| + yield columns, row + end + end + def to_hash hash_rows end -- cgit v1.2.3 From 75099a933d0bf5e037037f78fbb305520955b064 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Wed, 5 Nov 2014 13:34:44 -0700 Subject: Remove unneccesary default parameters --- activerecord/lib/active_record/attribute_set/builder.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb index 92640f1579..0a62c68bfb 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -11,7 +11,7 @@ module ActiveRecord build_from_database_pairs(values.keys, values.values, additional_types) end - def build_from_database_pairs(columns = [], values = [], additional_types = {}) + def build_from_database_pairs(columns, values, additional_types) attributes = build_attributes_from_values(columns, values, additional_types) add_uninitialized_attributes(attributes) AttributeSet.new(attributes) -- cgit v1.2.3 From c12fbae9322ff0afb8556bee13f3c78f68b114e0 Mon Sep 17 00:00:00 2001 From: Robert Evans Date: Wed, 5 Nov 2014 20:36:45 -0800 Subject: Removed documentation that still mentioned using respond_with in place of respond_to. respond_with was moved into the responders gem and deprecated inside rails, so there is no need to mention it within rails itself. --- .../lib/action_controller/metal/mime_responds.rb | 20 ++++---------------- actionpack/lib/action_controller/metal/renderers.rb | 3 +-- 2 files changed, 5 insertions(+), 18 deletions(-) diff --git a/actionpack/lib/action_controller/metal/mime_responds.rb b/actionpack/lib/action_controller/metal/mime_responds.rb index 591f881a53..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 :tablet, @@ -214,8 +202,8 @@ module ActionController #:nodoc: # format.html.phone # this gets rendered # end # - # Be sure to check the documentation of +respond_with+ and - # ActionController::MimeResponds.respond_to for more examples. + # Be sure to check the documentation of ActionController::MimeResponds.respond_to + # for more examples. def respond_to(*mimes) raise ArgumentError, "respond_to takes either types or a block, never both" if mimes.any? && block_given? @@ -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/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 - # ActionController::MimeResponds::ClassMethods.respond_to and - # ActionController::MimeResponds#respond_with + # ActionController::MimeResponds::ClassMethods.respond_to def self.add(key, &block) define_method(_render_with_renderer_method_name(key), &block) RENDERERS << key.to_sym -- cgit v1.2.3 From cc663f8f6c658c43898ed561b9533f885c73622e Mon Sep 17 00:00:00 2001 From: Paul Morganthall Date: Thu, 6 Nov 2014 00:48:16 -0500 Subject: Remove redundancy I love this guide! and "visually see" is redundant. remove "visually", then the sentence reads: > Action Mailer previews provide a way to see how emails look --- guides/source/4_1_release_notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 -- cgit v1.2.3 From ae755bc5179977b0ab105537c65e7831e47341d2 Mon Sep 17 00:00:00 2001 From: Prathamesh Sonpatki Date: Thu, 6 Nov 2014 12:25:38 +0530 Subject: Replace Html with HTML [ci skip] - Everywhere else we using HTML Sanitizer except this place. --- guides/source/upgrading_ruby_on_rails.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index aac2aef615..25759a0c77 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -181,7 +181,7 @@ end 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. @@ -207,7 +207,7 @@ 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). +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). ### Masked Authenticity Tokens -- cgit v1.2.3 From 54a9653a04f43917eab0b323ef4ba5b1fc6c05f4 Mon Sep 17 00:00:00 2001 From: Rishi Jain Date: Thu, 6 Nov 2014 06:34:56 +0530 Subject: added example of squish!, remove, test case for multiple occurrence of pattern removal added example for string#remove and test case for remove of multiple occurence of pattern removed extra whitespaces --- activesupport/lib/active_support/core_ext/string/filters.rb | 9 +++++++++ activesupport/test/core_ext/string_ext_test.rb | 6 ++++++ 2 files changed, 15 insertions(+) diff --git a/activesupport/lib/active_support/core_ext/string/filters.rb b/activesupport/lib/active_support/core_ext/string/filters.rb index 499b9b26bc..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/, '') @@ -21,11 +24,17 @@ class String end # 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 patterns. + # str = "foo bar test" + # str.remove!(" test") # => "foo bar" + # str # => "foo bar" def remove!(*patterns) patterns.each do |pattern| gsub! pattern, "" diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index 119e62369d..e32c178951 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -266,6 +266,12 @@ class StringInflectionsTest < ActiveSupport::TestCase 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") -- cgit v1.2.3 From 5dd3c3b2a0269eaa7cddfaed3136dc53dbf333e1 Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Thu, 6 Nov 2014 12:16:11 +0100 Subject: docs, synchronize 4.2. release notes. [ci skip] /cc @chancancode --- activesupport/CHANGELOG.md | 6 +++--- guides/source/4_2_release_notes.md | 15 +++++++++++---- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index b2b3cf4bd4..468b990f39 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -2,12 +2,12 @@ *Pavel Pravosud* -* TimeWithZone#strftime now delegates every directive to Time#strftime except for '%Z', +* `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. +* Corrected `Inflector#underscore` handling of multiple successive acroynms. *James Le Cuirot* @@ -160,7 +160,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/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 3a9be62865..8553cffa9d 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -300,6 +300,9 @@ 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)) @@ -575,6 +578,10 @@ Please refer to the [Changelog][active-record] for detailed changes. ### Deprecations +* 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)) + * Deprecated swallowing of errors inside `after_commit` and `after_rollback`. ([Pull Request](https://github.com/rails/rails/pull/16537)) @@ -753,15 +760,15 @@ Please refer to the [Changelog][active-support] for detailed changes. ### Notable changes -* `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)) - * Introduced new configuration option `active_support.test_order` for specifying the order test cases are executed. This option currently defaults 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)) -- cgit v1.2.3 From 33302fdd14d6e82293d1d8ea151af1197e7d74e2 Mon Sep 17 00:00:00 2001 From: Vipul A M Date: Thu, 6 Nov 2014 19:19:21 +0530 Subject: Fix grouped expression warning - `warning: (...) interpreted as grouped expression` --- activesupport/test/core_ext/range_ext_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 -- cgit v1.2.3 From de83f28dc1385eb037c70b6c631fc3aeade9fceb Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Thu, 6 Nov 2014 15:31:18 +0100 Subject: tests, use SchemaDumpingHelper to dump a specific table. This makes debugging the generated schema output much easier. As a side effect it also shaves off 2.5 seconds of test runtime. --- .../test/cases/adapters/postgresql/uuid_test.rb | 24 +++++++++++----------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb index 376dc2490e..c3705e7dac 100644 --- a/activerecord/test/cases/adapters/postgresql/uuid_test.rb +++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb @@ -3,6 +3,7 @@ require "cases/helper" require 'active_record/base' require 'active_record/connection_adapters/postgresql_adapter' +require 'support/schema_dumping_helper' module PostgresqlUUIDHelper def connection @@ -112,6 +113,8 @@ end class PostgresqlLargeKeysTest < ActiveRecord::TestCase include PostgresqlUUIDHelper + include SchemaDumpingHelper + def setup connection.create_table('big_serials', id: :bigserial) do |t| t.string 'name' @@ -119,10 +122,8 @@ class PostgresqlLargeKeysTest < ActiveRecord::TestCase end def test_omg - schema = StringIO.new - ActiveRecord::SchemaDumper.dump(connection, schema) - assert_match "create_table \"big_serials\", id: :bigserial, force: true", - schema.string + schema = dump_table_schema "big_serials" + assert_match "create_table \"big_serials\", id: :bigserial, force: true", schema end def teardown @@ -132,6 +133,7 @@ end class PostgresqlUUIDGenerationTest < ActiveRecord::TestCase include PostgresqlUUIDHelper + include SchemaDumpingHelper class UUID < ActiveRecord::Base self.table_name = 'pg_uuids' @@ -191,17 +193,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 -- cgit v1.2.3 From 300c96ce158a6ebd3a83b057a8cdf2d29de0fe9d Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Thu, 6 Nov 2014 15:38:03 +0100 Subject: tests, remove unneeded requires. --- activerecord/test/cases/adapters/postgresql/enum_test.rb | 2 -- activerecord/test/cases/adapters/postgresql/hstore_test.rb | 3 --- activerecord/test/cases/adapters/postgresql/json_test.rb | 3 --- activerecord/test/cases/adapters/postgresql/uuid_test.rb | 3 --- 4 files changed, 11 deletions(-) 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/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb index 1296eb72c0..f14ffe5ddc 100644 --- a/activerecord/test/cases/adapters/postgresql/hstore_test.rb +++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb @@ -1,8 +1,5 @@ # 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 diff --git a/activerecord/test/cases/adapters/postgresql/json_test.rb b/activerecord/test/cases/adapters/postgresql/json_test.rb index 7a9fdd45e8..340ca29c0e 100644 --- a/activerecord/test/cases/adapters/postgresql/json_test.rb +++ b/activerecord/test/cases/adapters/postgresql/json_test.rb @@ -1,8 +1,5 @@ # encoding: utf-8 - require "cases/helper" -require 'active_record/base' -require 'active_record/connection_adapters/postgresql_adapter' require 'support/schema_dumping_helper' module PostgresqlJSONSharedTestCases diff --git a/activerecord/test/cases/adapters/postgresql/uuid_test.rb b/activerecord/test/cases/adapters/postgresql/uuid_test.rb index c3705e7dac..5753da1173 100644 --- a/activerecord/test/cases/adapters/postgresql/uuid_test.rb +++ b/activerecord/test/cases/adapters/postgresql/uuid_test.rb @@ -1,8 +1,5 @@ # encoding: utf-8 - require "cases/helper" -require 'active_record/base' -require 'active_record/connection_adapters/postgresql_adapter' require 'support/schema_dumping_helper' module PostgresqlUUIDHelper -- cgit v1.2.3 From c0357d789b4323da64f1f9f82fa720ec9bac17cf Mon Sep 17 00:00:00 2001 From: Rishi Jain Date: Fri, 7 Nov 2014 00:09:52 +0530 Subject: added example of hash#except, and removed extra whitespaces [ci skip] --- activesupport/lib/active_support/core_ext/hash/compact.rb | 6 +++--- activesupport/lib/active_support/core_ext/hash/except.rb | 10 ++++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) 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 -- cgit v1.2.3 From eb05774531ffef41f3919dabb5b5a3a4ea723a04 Mon Sep 17 00:00:00 2001 From: Daniele Di Bernardo Date: Thu, 6 Nov 2014 19:56:20 +0100 Subject: [Enh] Changed the visibility of the ActiveModel::Dirty#clear_attribute_changes method In Rails 4.2 it is impossible to define a custom default value for a model's attribute without making it appear as _changed?, especially when the model is first initialized. Making this method publicly visible will allow such a behaviour, without the need to use private APIs. --- activemodel/lib/active_model/dirty.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activemodel/lib/active_model/dirty.rb b/activemodel/lib/active_model/dirty.rb index ae185694ca..4e389c8692 100644 --- a/activemodel/lib/active_model/dirty.rb +++ b/activemodel/lib/active_model/dirty.rb @@ -255,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 -- cgit v1.2.3 From d424ded6fd4b923802e9dab62b463a6f3439417f Mon Sep 17 00:00:00 2001 From: Franky W Date: Thu, 6 Nov 2014 09:07:29 -0800 Subject: Print out a meaningful error when ActiveRecord::ReadOnlyRecord is raised Currently, there is no messages which get printed out. Convoluted system may have hooks that create other objects in which case we only fail with no messages. This commit changes this information allowing you to know which object is the one that actually raised the error. --- activerecord/lib/active_record/persistence.rb | 4 ++-- activerecord/test/cases/readonly_test.rb | 9 ++++++--- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index 9d2c9d3b9c..06c8bceb30 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -188,7 +188,7 @@ module ActiveRecord # and destroy 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 @@ -519,7 +519,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/test/cases/readonly_test.rb b/activerecord/test/cases/readonly_test.rb index 2afd25c989..37d277eaa1 100644 --- a/activerecord/test/cases/readonly_test.rb +++ b/activerecord/test/cases/readonly_test.rb @@ -22,9 +22,12 @@ 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 -- cgit v1.2.3 From 066faa09e2636e75ddaa9b51e65a3a09c35ed732 Mon Sep 17 00:00:00 2001 From: "yuuji.yaginuma" Date: Fri, 7 Nov 2014 17:34:15 +0900 Subject: [ci skip] modify default host in command line guide --- guides/source/command_line.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/guides/source/command_line.md b/guides/source/command_line.md index e065d56168..d113632bea 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` -- cgit v1.2.3 From 58f3cf9bcb64ad2ee4997e89f4d7646f4c7bdbe7 Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Fri, 7 Nov 2014 09:58:15 +0100 Subject: docs, the abstract data type `:timestamp` was removed. See #15184 [ci skip] --- .../active_record/connection_adapters/abstract/schema_definitions.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 f8b6daea5a..dd4c4ae9fc 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -124,8 +124,8 @@ module ActiveRecord # which is one of the following: # :primary_key, :string, :text, # :integer, :float, :decimal, - # :datetime, :timestamp, :time, - # :date, :binary, :boolean. + # :datetime, :time, :date, + # :binary, :boolean. # # 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 -- cgit v1.2.3 From 35f502e9b6edf857b2388e86f429e9a88dd35a3d Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Fri, 7 Nov 2014 10:12:01 +0100 Subject: remove the last traces of OpenBase from our codebase. [ci skip] --- activerecord/test/config.example.yml | 6 ------ 1 file changed, 6 deletions(-) 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 -- cgit v1.2.3 From 48e3edf9ad724426a3694ca6b589da0d5e0de1ee Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Fri, 7 Nov 2014 10:45:34 +0100 Subject: pg tests, only execute what's necessary. --- .../test/cases/adapters/postgresql/bytea_test.rb | 2 +- .../test/cases/adapters/postgresql/hstore_test.rb | 51 +++++++++++----------- 2 files changed, 26 insertions(+), 27 deletions(-) diff --git a/activerecord/test/cases/adapters/postgresql/bytea_test.rb b/activerecord/test/cases/adapters/postgresql/bytea_test.rb index 7872f91943..ec4aebf03a 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,6 +24,7 @@ class PostgresqlByteaTest < ActiveRecord::TestCase end def test_column + assert @column.is_a?(ActiveRecord::ConnectionAdapters::PostgreSQLColumn) assert_equal :binary, @column.type end diff --git a/activerecord/test/cases/adapters/postgresql/hstore_test.rb b/activerecord/test/cases/adapters/postgresql/hstore_test.rb index f14ffe5ddc..6a9c6483fe 100644 --- a/activerecord/test/cases/adapters/postgresql/hstore_test.rb +++ b/activerecord/test/cases/adapters/postgresql/hstore_test.rb @@ -1,38 +1,38 @@ # encoding: utf-8 require "cases/helper" -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" @@ -312,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) @@ -343,4 +341,5 @@ class PostgresqlHstoreTest < ActiveRecord::TestCase x.reload assert_equal(hash, x.tags) end + end end -- cgit v1.2.3 From 92534179096b9b4838bbaee343bba1127095f5e6 Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Fri, 7 Nov 2014 10:55:45 +0100 Subject: pg tests, get rid of `sql_types_test.rb`. --- .../test/cases/adapters/postgresql/bytea_test.rb | 7 +++++++ .../test/cases/adapters/postgresql/datatype_test.rb | 7 +++++++ .../test/cases/adapters/postgresql/sql_types_test.rb | 18 ------------------ 3 files changed, 14 insertions(+), 18 deletions(-) delete mode 100644 activerecord/test/cases/adapters/postgresql/sql_types_test.rb diff --git a/activerecord/test/cases/adapters/postgresql/bytea_test.rb b/activerecord/test/cases/adapters/postgresql/bytea_test.rb index ec4aebf03a..aeebec034d 100644 --- a/activerecord/test/cases/adapters/postgresql/bytea_test.rb +++ b/activerecord/test/cases/adapters/postgresql/bytea_test.rb @@ -28,6 +28,13 @@ class PostgresqlByteaTest < ActiveRecord::TestCase 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/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/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 -- cgit v1.2.3 From 5bdaf31628fdfd4000a2cd3a430dbce8127b863e Mon Sep 17 00:00:00 2001 From: Jimmy Petersen Date: Fri, 7 Nov 2014 11:30:52 +0100 Subject: Guides: Corrected name for assigns key [ci skip] - Integration test example is now using 'articles' name for both path and assigns key. --- guides/source/testing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 8ad1eed72c..4197e31d3c 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -728,7 +728,7 @@ class UserFlowsTest < ActionDispatch::IntegrationTest https!(false) get "/articles/all" assert_response :success - assert assigns(:products) + assert assigns(:articles) end end ``` -- cgit v1.2.3 From c2fc9848b1495768a4c550e4cc532882146902c9 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Fri, 7 Nov 2014 16:23:15 -0800 Subject: default scopes should break the cache on has_many. if you specify a default scope on a model, it will break caching. We cannot predict what will happen inside the scope, so play it safe for now. fixes #17495 --- .../associations/collection_association.rb | 3 ++- .../associations/has_many_associations_test.rb | 26 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index bdfd569be2..4411e5ae62 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -409,7 +409,8 @@ module ActiveRecord def get_records if reflection.scope_chain.any?(&:any?) || scope.eager_loading? || - klass.current_scope + klass.current_scope || + klass.default_scopes.any? return scope.to_a end diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index fdbe411f86..1617e883ba 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -76,6 +76,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') -- cgit v1.2.3 From b38c9eb631f8505412f7eab93b11cdf69fd85c26 Mon Sep 17 00:00:00 2001 From: yui-knk Date: Sat, 8 Nov 2014 11:22:42 +0900 Subject: [ci skip] Fix line break on command line guide --- guides/source/command_line.md | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/guides/source/command_line.md b/guides/source/command_line.md index d113632bea..a536f00df9 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -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 @@ -408,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`. -- cgit v1.2.3 From 9bd43868502f5e8a67649ffb5e766853a05714c5 Mon Sep 17 00:00:00 2001 From: alfa-jpn Date: Sat, 8 Nov 2014 17:03:54 +0900 Subject: default scopes should break the cache on singulur_association. fixes #17495 --- .../associations/singular_association.rb | 3 ++- .../associations/belongs_to_associations_test.rb | 29 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/associations/singular_association.rb b/activerecord/lib/active_record/associations/singular_association.rb index c360ef1b2c..c44242a0f0 100644 --- a/activerecord/lib/active_record/associations/singular_association.rb +++ b/activerecord/lib/active_record/associations/singular_association.rb @@ -41,7 +41,8 @@ module ActiveRecord def get_records if reflection.scope_chain.any?(&:any?) || scope.eager_loading? || - klass.current_scope + klass.current_scope || + klass.default_scopes.any? return scope.limit(1).to_a end diff --git a/activerecord/test/cases/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index 25555bd75c..bcd0cf82d5 100644 --- a/activerecord/test/cases/associations/belongs_to_associations_test.rb +++ b/activerecord/test/cases/associations/belongs_to_associations_test.rb @@ -57,6 +57,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 } -- cgit v1.2.3 From 001e600619c7ec5d7535e47c5900bcad259de3f8 Mon Sep 17 00:00:00 2001 From: Zachary Scott Date: Sat, 8 Nov 2014 16:40:13 -0800 Subject: Documenting Rails::Info module [ci skip] --- railties/lib/rails/info.rb | 3 +++ 1 file changed, 3 insertions(+) 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 = []) -- cgit v1.2.3 From 9cf3596da50fb1c157ce1995754c1b7e810b9611 Mon Sep 17 00:00:00 2001 From: yui-knk Date: Sun, 9 Nov 2014 11:53:51 +0900 Subject: Fix comment of SourceAnnotationExtractor#find_in Commit(810af6f) changed which extensions are taken into account, so make to match comment of find_in. And sort extensions to follow the added order. --- railties/lib/rails/source_annotation_extractor.rb | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) 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 = {} -- cgit v1.2.3 From ec13bf0a9909300e3b4e9e41d30c7662b5d9550a Mon Sep 17 00:00:00 2001 From: yui-knk Date: Sun, 9 Nov 2014 23:38:56 +0900 Subject: [ci skip] Fix typo in command_line.md --- guides/source/command_line.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/command_line.md b/guides/source/command_line.md index a536f00df9..e72bc81766 100644 --- a/guides/source/command_line.md +++ b/guides/source/command_line.md @@ -494,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: -- cgit v1.2.3 From f0d0c0fa1b12276c961ac66a0f3a34ddb3786a69 Mon Sep 17 00:00:00 2001 From: betesh Date: Wed, 24 Sep 2014 12:06:15 -0400 Subject: Time includes DateAndTime::Zones acts_like(:time) --- activesupport/lib/active_support/core_ext/time/zones.rb | 1 + 1 file changed, 1 insertion(+) 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 -- cgit v1.2.3 From f43f56e16e99dae083cf1400a48c236d1af265d4 Mon Sep 17 00:00:00 2001 From: Sammy Larbi Date: Wed, 8 Oct 2014 15:58:11 -0500 Subject: Ensure HABTM relationships produce valid class names (Fixes #17119) --- activerecord/lib/active_record/associations.rb | 2 +- .../associations/builder/has_and_belongs_to_many.rb | 2 +- .../associations/has_and_belongs_to_many_associations_test.rb | 11 ++++++++++- activerecord/test/fixtures/computers.yml | 5 +++++ activerecord/test/fixtures/developers.yml | 1 + activerecord/test/models/developer.rb | 2 ++ activerecord/test/schema/schema.rb | 5 +++++ 7 files changed, 25 insertions(+), 3 deletions(-) diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index 8911506694..d2bcdc55bf 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -1700,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/builder/has_and_belongs_to_many.rb b/activerecord/lib/active_record/associations/builder/has_and_belongs_to_many.rb index 815e8eb97f..357b28ac94 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] 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..9a57683ee3 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' @@ -80,7 +81,7 @@ 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 +884,12 @@ 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 end 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/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/schema/schema.rb b/activerecord/test/schema/schema.rb index 539a0d2a49..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 -- cgit v1.2.3 From 30af171af13293aa37bee612ae7b976d3ede0439 Mon Sep 17 00:00:00 2001 From: Rishi Jain Date: Mon, 10 Nov 2014 08:11:49 +0530 Subject: added description for rails generators, and fixed sentence formation for active_support/notifications [ci skip] --- activesupport/lib/active_support/notifications.rb | 2 +- railties/lib/rails/commands/destroy.rb | 2 ++ railties/lib/rails/commands/generate.rb | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) 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/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 -- cgit v1.2.3 From 52c3a16fa07cde643af3c2200e4b87bcb470eb12 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Sun, 9 Nov 2014 20:38:40 -0700 Subject: Revert the behavior of booleans in string columns to that of 4.1 Why are people assigning booleans to string columns? >_> We unintentionally changed the behavior on Sqlite3 and PostgreSQL. Boolean values should cast to the database's representation of true and false. This is 't' and 'f' by default, and "1" and "0" on Mysql. The implementation to make the connection adapter specific behavior is hacky at best, and should be re-visted once we decide how we actually want to separate the concerns related to things that should change based on the database adapter. That said, this isn't something I'd expect to change based on my database adapter. We're storing a string, so the way the database represents a boolean should be irrelevant. It also seems strange for us to give booleans special behavior at all in string columns. Why is `to_s` not sufficient? It's inconsistent and confusing. Perhaps we should consider deprecating in the future. Fixes #17571 --- .../connection_adapters/abstract_mysql_adapter.rb | 24 +++++++++++++++++++++- activerecord/lib/active_record/type/string.rb | 8 ++++---- activerecord/test/cases/type/string_test.rb | 4 ++-- 3 files changed, 29 insertions(+), 7 deletions(-) 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 5f512758e9..26015528e5 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -648,6 +648,8 @@ module ActiveRecord def initialize_type_map(m) # :nodoc: super + 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) m.register_type %r(text)i, Type::Text.new(limit: 2**16 - 1) @@ -672,7 +674,7 @@ module ActiveRecord 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) + MysqlString.new(limit: limit) end end @@ -847,6 +849,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/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/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 -- cgit v1.2.3 From aa6637d140c2ebd28bbd23fc250af033a065dbe8 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Mon, 10 Nov 2014 00:30:08 -0800 Subject: Pass the route name explicitly Follow up to 212057b9. Since that commit, we need to pass the `route_name` explicitly. This is one of the left-over cases that was not handled in that commit, which was causing `use_route` to be ignored in functional tests. --- actionpack/lib/action_controller/test_case.rb | 3 ++- actionpack/test/controller/test_case_test.rb | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 41d33d4396..aa475dc4c4 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -710,7 +710,8 @@ module ActionController :relative_url_root => nil, :_recall => @request.path_parameters) - url, query_string = @routes.path_for(options).split("?", 2) + route_name = options.delete :use_route + 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/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb index 9d7abd5e94..957c0a5288 100644 --- a/actionpack/test/controller/test_case_test.rb +++ b/actionpack/test/controller/test_case_test.rb @@ -499,6 +499,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 + + 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 -- cgit v1.2.3 From 6625000b73f520abf6e0afbd5a6dde8d6b06b7cc Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Mon, 10 Nov 2014 00:47:25 -0800 Subject: Remove useless `only_path: true` in path helpers We added a deprecation warning for these cases in aa1fadd, so these are now causing deprecation warnings in the test output. AFAICT, in these two cases, the option is not integral to the purpose of the test, so they can be safely removed --- actionpack/test/controller/url_for_test.rb | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index 969129d9ba..c05cde87e4 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 @@ -291,7 +290,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 -- cgit v1.2.3 From 2a843b3538bbc88286b83562fe1bb517e01576f6 Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Mon, 10 Nov 2014 14:56:07 +0100 Subject: docs, minor changes in Active Job documentation. [ci skip] --- activejob/README.md | 9 ++++----- activejob/lib/active_job/base.rb | 2 +- 2 files changed, 5 insertions(+), 6 deletions(-) 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/lib/active_job/base.rb b/activejob/lib/active_job/base.rb index 0c4a29090e..fd49b3fda5 100644 --- a/activejob/lib/active_job/base.rb +++ b/activejob/lib/active_job/base.rb @@ -32,7 +32,7 @@ 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 enqueue a job to be performed as soon the queueing system is free: # -- cgit v1.2.3 From c7deaa860131c66e231478e9d3193ab9fc4895cf Mon Sep 17 00:00:00 2001 From: Sammy Larbi Date: Mon, 10 Nov 2014 08:33:44 -0600 Subject: Fixes a bug found when running individual tests against #17217 after merging --- activerecord/test/cases/validations/uniqueness_validation_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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) -- cgit v1.2.3 From 5e4a99821dd9a710fe3ab434881cfdae15bd0838 Mon Sep 17 00:00:00 2001 From: Andrey Deryabin Date: Mon, 10 Nov 2014 22:55:40 +0300 Subject: tiny code improvement in sqlite3 adapter: - remove unused method `supports_add_column?` - change additional restriction method to `valid_alter_table_type?` - fix code style --- .../lib/active_record/connection_adapters/sqlite3_adapter.rb | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb index 1b5e3bdbac..b18cb353f1 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb @@ -179,10 +179,6 @@ module ActiveRecord true end - def supports_add_column? - true - end - def supports_views? true end @@ -451,12 +447,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| -- cgit v1.2.3 From 76e7305ea16b41a3674f4213ab7faa8c65196d75 Mon Sep 17 00:00:00 2001 From: Cody Cutrer Date: Mon, 10 Nov 2014 12:06:58 -0700 Subject: add a Table#name accessor like TableDefinition#name --- activerecord/CHANGELOG.md | 4 +++ .../abstract/schema_definitions.rb | 36 ++++++++++++---------- .../test/cases/migration/change_table_test.rb | 6 ++++ 3 files changed, 29 insertions(+), 17 deletions(-) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 2c66ddb983..1307427e6c 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,7 @@ +* 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. 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 dd4c4ae9fc..5c4c214385 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -414,8 +414,10 @@ module ActiveRecord class Table include TimestampDefaultDeprecation + attr_reader :name + def initialize(table_name, base) - @table_name = table_name + @name = table_name @base = base end @@ -425,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 @@ -443,19 +445,19 @@ 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 @@ -463,7 +465,7 @@ module ActiveRecord # t.timestamps 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. @@ -472,7 +474,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 @@ -480,7 +482,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. @@ -488,7 +490,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. @@ -502,21 +504,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 :polymorphic option is provided. @@ -531,7 +533,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 @@ -546,7 +548,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 @@ -558,8 +560,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/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 -- cgit v1.2.3 From fd1364e021155d04318571ec08d50e2c740199db Mon Sep 17 00:00:00 2001 From: Andrey Deryabin Date: Tue, 11 Nov 2014 01:33:29 +0300 Subject: remove never called method `limited_update_conditions` --- .../active_record/connection_adapters/abstract/database_statements.rb | 4 ---- .../lib/active_record/connection_adapters/abstract_mysql_adapter.rb | 4 ---- 2 files changed, 8 deletions(-) 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 1a3ed28d66..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 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 26015528e5..167453657d 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -631,10 +631,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 -- cgit v1.2.3 From 0ed6ebcf9095c65330d3950cfb6b75ba7ea78853 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 10 Nov 2014 14:17:01 -0800 Subject: dependencies.rb: keep the decorated #load and #require private [closes #17553] --- activesupport/CHANGELOG.md | 6 +++++ activesupport/lib/active_support/dependencies.rb | 31 ++++++++++++++---------- activesupport/test/dependencies_test.rb | 12 +++++++++ 3 files changed, 36 insertions(+), 13 deletions(-) diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index 468b990f39..ed30c7de70 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,3 +1,9 @@ +* The decorated `load` and `require` methods are now kept private. + + Fixes #17553. + + *Xavier Noria* + * `String#remove` and `String#remove!` accept multiple arguments. *Pavel Pravosud* diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index a89c769e34..65a370dd30 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -205,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) @@ -241,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. # @@ -269,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. diff --git a/activesupport/test/dependencies_test.rb b/activesupport/test/dependencies_test.rb index 67e31fc1e1..96e9bd1e65 100644 --- a/activesupport/test/dependencies_test.rb +++ b/activesupport/test/dependencies_test.rb @@ -1037,6 +1037,18 @@ class DependenciesTest < ActiveSupport::TestCase 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) -- cgit v1.2.3 From 1d1239d32856b32b19c04edd17d0dd0d47611586 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Mon, 10 Nov 2014 21:18:57 -0200 Subject: No need to sync config.secret_token and secrets.secret_token Just prefer secrets over config --- railties/lib/rails/application.rb | 9 ++----- railties/test/application/configuration_test.rb | 36 ++----------------------- 2 files changed, 4 insertions(+), 41 deletions(-) diff --git a/railties/lib/rails/application.rb b/railties/lib/rails/application.rb index ae60337af2..f8bd6096f2 100644 --- a/railties/lib/rails/application.rb +++ b/railties/lib/rails/application.rb @@ -381,13 +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 - # Sync secrets.secret_token with config.secret_token, preferring secrets.secret_token - # note that unset config's default to "", secrets default to nil - if secrets.secret_token.blank? && config.secret_token.present? - secrets.secret_token = config.secret_token - elsif secrets.secret_token.present? - config.secret_token = secrets.secret_token - end + # Fallback to config.secret_token if secrets.secret_token isn't set + secrets.secret_token ||= config.secret_token secrets end diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 55a3456cfc..922f387987 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -347,19 +347,17 @@ module ApplicationTests end end - test "uses secrets.secret_token when secrets.secret_key_base and config.secret_token are blank" do + 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_key_base: secret_token: 3b7cd727ee24e8444053437c36cc66c3 YAML require "#{app_path}/config/environment" assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token - assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.config.secret_token end test "application verifier can build different verifiers" do @@ -404,7 +402,7 @@ module ApplicationTests 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" + Rails.application.config.secret_token = "b3c631c314c0bbca50c1b2843150fe33" RUBY app_file 'config/secrets.yml', <<-YAML development: @@ -417,36 +415,6 @@ module ApplicationTests assert_equal 'b3c631c314c0bbca50c1b2843150fe33', app.config.secret_token end - test "secret_token is copied from secrets to config when set" 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: - secret_token: 3b7cd727ee24e8444053437c36cc66c3 - YAML - require "#{app_path}/config/environment" - - assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token - assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.config.secret_token - end - - test "secret_token is copied from secrets to config when different" 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: 3b7cd727ee24e8444053437c36cc66c3 - YAML - require "#{app_path}/config/environment" - - assert_equal '3b7cd727ee24e8444053437c36cc66c3', app.secrets.secret_token - assert_equal '3b7cd727ee24e8444053437c36cc66c3', 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: -- cgit v1.2.3 From bda93b2bb272c34e46a5454d4658a0139b135e93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Mon, 10 Nov 2014 21:19:37 -0200 Subject: :scissors: --- railties/test/application/configuration_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 922f387987..391139d7f8 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -326,7 +326,7 @@ module ApplicationTests 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'], 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) -- cgit v1.2.3 From d4ce2bb06d6479a99657617294a4fe7fd6cafa73 Mon Sep 17 00:00:00 2001 From: claudiob Date: Sat, 8 Nov 2014 10:58:44 -0800 Subject: Remove unnecessary double space Replaces the following in two places: ```diff -require ::File.expand_path('../config/environment', __FILE__) +require ::File.expand_path('../config/environment', __FILE__) ``` --- railties/lib/rails/generators/rails/app/templates/bin/rails | 2 +- railties/lib/rails/generators/rails/app/templates/config.ru | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 -- cgit v1.2.3 From 3b12abba3c4fa0dbd6e8c92bd68fa433847d142c Mon Sep 17 00:00:00 2001 From: David Geukers Date: Tue, 21 Oct 2014 15:13:09 -0400 Subject: Simplify rake test vs rake test:all Renames `rake test:all` to `rake test` by changing old `rake test:run` to previous version of `rake test:all`. Removes old definition of `rake test`. Also renames `rake test:all:db` to `rake test:db` and deprecates `rake test:all` & `rake test:all:db` --- guides/source/testing.md | 5 ++--- railties/CHANGELOG.md | 6 ++++++ railties/lib/rails/test_unit/testing.rake | 23 ++++++++++++++++++++--- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index b784098fbb..4f10245612 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -792,7 +792,7 @@ when you initiate a Rails project. | 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,8 +801,7 @@ 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 and resets the db | Brief Note About `Minitest` diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md index e1a11482e6..201a73339a 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -181,4 +181,10 @@ *Yves Senn*, *Carlos Antonio da Silva*, *Robin Dupret* +* 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* + Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/railties/CHANGELOG.md) for previous changes. 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") -- cgit v1.2.3 From 3c60fb429d9e4271bce3a71b0f5fb4bb2f7fbe2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Tue, 11 Nov 2014 01:04:06 -0200 Subject: Make FlashHash#key? work with symbol and string Closes #17586 --- actionpack/lib/action_dispatch/middleware/flash.rb | 2 +- actionpack/test/controller/flash_hash_test.rb | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb index e90f8b9ce6..7a91674c3c 100644 --- a/actionpack/lib/action_dispatch/middleware/flash.rb +++ b/actionpack/lib/action_dispatch/middleware/flash.rb @@ -132,7 +132,7 @@ module ActionDispatch end def key?(name) - @flashes.key? name + @flashes.key? name.to_s end def delete(key) 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' -- cgit v1.2.3 From 4223fa70f978af3d18af1b4301013a68a776a498 Mon Sep 17 00:00:00 2001 From: Dave Powers Date: Tue, 11 Nov 2014 13:06:53 -0500 Subject: Replace "behaviour" with "behavior" Update to consistently use American English [ci skip] --- guides/source/upgrading_ruby_on_rails.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 25759a0c77..6f5dea45b5 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -421,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. @@ -795,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. -- cgit v1.2.3 From 56dc95bc92301dae89e5d6b5ca306b043b095661 Mon Sep 17 00:00:00 2001 From: Igor Kapkov Date: Wed, 12 Nov 2014 16:27:42 +0800 Subject: Fix Rails::Paths::Path.unshift interface --- railties/CHANGELOG.md | 5 +++++ railties/lib/rails/paths.rb | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md index ca2bd62b43..8b391e9031 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -1,3 +1,8 @@ +* `Rails::Paths::Path.unshift` is now have the same interface as + `Array.unshift`. + + *Igor Kapkov* + * `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`. 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 -- cgit v1.2.3 From b1879124a82b34168412ac699cf6f654e005c4d6 Mon Sep 17 00:00:00 2001 From: Andrey Deryabin Date: Wed, 12 Nov 2014 15:11:36 +0300 Subject: Follow the coding conventions --- activerecord/lib/active_record/scoping/named.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/scoping/named.rb b/activerecord/lib/active_record/scoping/named.rb index ec1edf0e01..35420e6551 100644 --- a/activerecord/lib/active_record/scoping/named.rb +++ b/activerecord/lib/active_record/scoping/named.rb @@ -139,7 +139,7 @@ module ActiveRecord # Article.published.featured.latest_article # Article.featured.titles def scope(name, body, &block) - unless body.respond_to?:call + unless body.respond_to?(:call) raise ArgumentError, 'The scope body needs to be callable.' end -- cgit v1.2.3 From 6ff78469cd70ce821dd1455f3607780863f5a9d7 Mon Sep 17 00:00:00 2001 From: Carlos Antonio da Silva Date: Wed, 12 Nov 2014 14:22:30 -0200 Subject: Improve railties changelog entry and move latest to the top [ci skip] --- railties/CHANGELOG.md | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md index 92187f3d91..f267be5eb8 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -1,8 +1,13 @@ -* `Rails::Paths::Path.unshift` is now have the same interface as - `Array.unshift`. +* `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`. @@ -186,10 +191,4 @@ *Yves Senn*, *Carlos Antonio da Silva*, *Robin Dupret* -* 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* - Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/railties/CHANGELOG.md) for previous changes. -- cgit v1.2.3 From 8573de4d10188372ebab9509238210ed1c6a30f8 Mon Sep 17 00:00:00 2001 From: Ryan Mohr Date: Wed, 12 Nov 2014 12:48:44 -1000 Subject: Abstract encoding strategy for ActiveSupport::MessageVerifier --- activesupport/lib/active_support/message_verifier.rb | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/activesupport/lib/active_support/message_verifier.rb b/activesupport/lib/active_support/message_verifier.rb index 4e0796f4f8..a8a8de5672 100644 --- a/activesupport/lib/active_support/message_verifier.rb +++ b/activesupport/lib/active_support/message_verifier.rb @@ -40,7 +40,7 @@ module ActiveSupport data, digest = signed_message.split("--") 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 @@ -51,11 +51,19 @@ module ActiveSupport end def generate(value) - data = ::Base64.strict_encode64(@serializer.dump(value)) + data = encode(@serializer.dump(value)) "#{data}--#{generate_digest(data)}" end private + def encode(data) + ::Base64.strict_encode64(data) + end + + def decode(data) + ::Base64.strict_decode64(data) + end + def generate_digest(data) require 'openssl' unless defined?(OpenSSL) OpenSSL::HMAC.hexdigest(OpenSSL::Digest.const_get(@digest).new, @secret, data) -- cgit v1.2.3 From 07e0d8cc0c108b2814d5c8d29f5f3f5b1db4f696 Mon Sep 17 00:00:00 2001 From: shiksha Date: Thu, 13 Nov 2014 11:13:44 +0530 Subject: Allow habtm class_name option to be consistent with other associations --- .../associations/builder/has_and_belongs_to_many.rb | 2 +- .../associations/has_and_belongs_to_many_associations_test.rb | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) 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 357b28ac94..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 @@ -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/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 9a57683ee3..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 @@ -79,6 +79,10 @@ 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, :computers @@ -892,4 +896,10 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase 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 -- cgit v1.2.3 From 062988efd31a0588b07a45d633ea6a8f46c884a6 Mon Sep 17 00:00:00 2001 From: Sandip Ransing Date: Fri, 14 Nov 2014 00:35:51 +0530 Subject: [ci skip] Add one more example to routing testing, and highlight association name keywords --- guides/source/testing.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index ce815156a7..79e7ac5aef 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 @@ -901,13 +901,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 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 ``` -- cgit v1.2.3 From d9d84cea53d951f9335164599bd03e7caf0df340 Mon Sep 17 00:00:00 2001 From: Sandip Ransing Date: Fri, 14 Nov 2014 02:07:22 +0530 Subject: [ci skip] Capybara added to other testing approaches --- guides/source/testing.md | 1 + 1 file changed, 1 insertion(+) diff --git a/guides/source/testing.md b/guides/source/testing.md index 79e7ac5aef..c31d24c6d4 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -1121,3 +1121,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 -- cgit v1.2.3 From c31e638a37946a120f6dbf207127d36beea5ab85 Mon Sep 17 00:00:00 2001 From: Sandip Ransing Date: Fri, 14 Nov 2014 02:48:52 +0530 Subject: [ci skip] Improve upon testing tasks guide Add missing testing tasks and also improve upon tasks descriptions --- guides/source/testing.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index c31d24c6d4..9f881f1f47 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -786,13 +786,14 @@ 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 +Rails comes with a number of built-in rake tasks to help in testing. +Below table lists available commands which comes along with `Rakefile` tasks when you initiate a Rails project. | Tasks | Description | | ----------------------- | ----------- | -| `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` | Runs all tests in the test folder by default | +| `rake test:all` | Runs tests quickly by merging all types and not resetting the db | | `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` | @@ -802,6 +803,7 @@ when you initiate a Rails project. | `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:db` | Runs all tests and resets the db | +| `rake test:all:db` | Runs tests quickly by merging all types and resets the db | Brief Note About `Minitest` -- cgit v1.2.3 From 50079298260a8a406713a309524b29552ceec270 Mon Sep 17 00:00:00 2001 From: Genadi Samokovarov Date: Thu, 13 Nov 2014 23:25:33 +0100 Subject: Add basic tests for ActionDispatch::ExceptionWrapper --- actionpack/test/dispatch/exception_wrapper_test.rb | 66 ++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 actionpack/test/dispatch/exception_wrapper_test.rb diff --git a/actionpack/test/dispatch/exception_wrapper_test.rb b/actionpack/test/dispatch/exception_wrapper_test.rb new file mode 100644 index 0000000000..3ddaa7294b --- /dev/null +++ b/actionpack/test/dispatch/exception_wrapper_test.rb @@ -0,0 +1,66 @@ +require 'abstract_unit' + +module ActionDispatch + class ExceptionWrapperTest < ActionDispatch::IntegrationTest + class TestError < StandardError + attr_reader :backtrace + + def initialize(*backtrace) + @backtrace = backtrace.flatten + 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_extract 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', file: 'lib/file.rb', line_number: 42 ], wrapper.source_extract + 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 '#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 '#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 '#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 -- cgit v1.2.3 From aeb917d475dfccb8b5f3b5a57f62df5358ad3ef0 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 13 Nov 2014 15:31:54 -0800 Subject: exec_prepared is GVL friendly, so lets use it. also increase the version of pg required so that people will get the GVL friendly version --- Gemfile | 2 +- .../lib/active_record/connection_adapters/postgresql_adapter.rb | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/Gemfile b/Gemfile index 931c8e85bc..fa17d217c9 100644 --- a/Gemfile +++ b/Gemfile @@ -81,7 +81,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/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 9941f74766..6310d70192 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' @@ -596,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 -- cgit v1.2.3 From 5e3c5cef857cb2b7c17e5df792b9a7897fb2a47a Mon Sep 17 00:00:00 2001 From: Sandip Ransing Date: Fri, 14 Nov 2014 11:51:06 +0530 Subject: [ci skip] Remove deprecated testing tasks This has changed recently and so rake test:all and rake test:all:db are deprecated. --- guides/source/testing.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index 9f881f1f47..b51a422583 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -792,8 +792,7 @@ when you initiate a Rails project. | Tasks | Description | | ----------------------- | ----------- | -| `rake test` | Runs all tests in the test folder by default | -| `rake test:all` | Runs tests quickly by merging all types and not resetting the db | +| `rake test` | Runs all tests in the `test` folder 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` | @@ -802,8 +801,7 @@ 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:db` | Runs all tests and resets the db | -| `rake test:all:db` | Runs tests quickly by merging all types and resets the db | +| `rake test:db` | Runs all tests in the `test` folder and resets the db | Brief Note About `Minitest` -- cgit v1.2.3 From f88a4d39000991f0b2b138c1396612a03a518a32 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Fri, 14 Nov 2014 16:36:26 +0800 Subject: [CI SKIP] Corrections to testing guide. Partially revert https://github.com/rails/rails/commit/c31e638a37946a120f6dbf207127d36beea5ab85. --- guides/source/testing.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index b51a422583..d2b8ce8ed2 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -787,12 +787,12 @@ 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 built-in rake tasks to help in testing. -Below table lists available commands which comes along with `Rakefile` tasks +Below table lists available commands which come along in the default `Rakefile` when you initiate a Rails project. | Tasks | Description | | ----------------------- | ----------- | -| `rake test` | Runs all tests in the `test` folder 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` | -- cgit v1.2.3 From 9ae210ba091bc9f54de08da4be1540f0a9782771 Mon Sep 17 00:00:00 2001 From: Arun Agrawal Date: Fri, 14 Nov 2014 09:55:32 +0100 Subject: Build fix when running in isolation `Computer` class needs to be require See #17217 for more details --- activerecord/test/cases/adapters/mysql2/explain_test.rb | 1 + activerecord/test/cases/adapters/postgresql/explain_test.rb | 1 + activerecord/test/cases/adapters/sqlite3/explain_test.rb | 1 + activerecord/test/cases/associations/belongs_to_associations_test.rb | 1 + activerecord/test/cases/associations/callbacks_test.rb | 1 + activerecord/test/cases/associations/eager_test.rb | 1 + activerecord/test/cases/associations/extension_test.rb | 1 + activerecord/test/cases/associations/has_many_associations_test.rb | 1 + .../test/cases/associations/has_many_through_associations_test.rb | 1 + activerecord/test/cases/associations/has_one_associations_test.rb | 1 + activerecord/test/cases/associations_test.rb | 1 + activerecord/test/cases/attribute_methods_test.rb | 1 + activerecord/test/cases/autosave_association_test.rb | 1 + activerecord/test/cases/base_test.rb | 1 + activerecord/test/cases/callbacks_test.rb | 2 ++ activerecord/test/cases/finder_test.rb | 1 + activerecord/test/cases/fixtures_test.rb | 1 + activerecord/test/cases/integration_test.rb | 1 + activerecord/test/cases/migration_test.rb | 1 + activerecord/test/cases/modules_test.rb | 1 + activerecord/test/cases/persistence_test.rb | 1 + activerecord/test/cases/readonly_test.rb | 1 + activerecord/test/cases/relation/merging_test.rb | 1 + activerecord/test/cases/relations_test.rb | 1 + activerecord/test/cases/scoping/default_scoping_test.rb | 1 + activerecord/test/cases/scoping/named_scoping_test.rb | 1 + activerecord/test/cases/scoping/relation_scoping_test.rb | 1 + activerecord/test/cases/timestamp_test.rb | 1 + activerecord/test/cases/transactions_test.rb | 1 + activerecord/test/cases/validations_test.rb | 1 + 30 files changed, 31 insertions(+) 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/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/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/associations/belongs_to_associations_test.rb b/activerecord/test/cases/associations/belongs_to_associations_test.rb index bcd0cf82d5..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' 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 8234ee95be..4539b99504 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' 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_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 69f7bde4bc..5a963b6458 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' 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_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 c3e8ceb0da..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' diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 734fd5fe18..71c34d816a 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -4,6 +4,7 @@ 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' diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index 3675401555..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' diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb index c8f56e3c73..5e07f8a03c 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' diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index dc73faa5be..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' diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 7141d3ee7f..4b0ebe13d1 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -10,6 +10,7 @@ require 'models/company' require 'models/computer' require 'models/course' require 'models/developer' +require 'models/computer' require 'models/joke' require 'models/matey' require 'models/parrot' 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_test.rb b/activerecord/test/cases/migration_test.rb index 6b7a0a9000..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" 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 5b903e4f2c..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' 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/relations_test.rb b/activerecord/test/cases/relations_test.rb index 410b5ba5a3..8ac4a4ca36 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' 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 c2816c3670..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 diff --git a/activerecord/test/cases/scoping/relation_scoping_test.rb b/activerecord/test/cases/scoping/relation_scoping_test.rb index 73835c85a8..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' 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/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' -- cgit v1.2.3 From 85b40edd949678abe2a50a4291029be123cb03c5 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Fri, 14 Nov 2014 07:39:32 -0700 Subject: Use `DelegateClass` instead of `SimpleDelegator` for type decorators There is a significant performance difference between the two. Closes --- .../lib/active_record/attribute_methods/time_zone_conversion.rb | 2 +- activerecord/lib/active_record/type/serialized.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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/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 -- cgit v1.2.3 From d987bdd7fa0958b5b765c22d5ac62e3e70c12cad Mon Sep 17 00:00:00 2001 From: Jon Atack Date: Fri, 14 Nov 2014 21:22:10 +0100 Subject: Simplify and fix grammar [skip ci] --- guides/source/testing.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index d2b8ce8ed2..b4c70dfa1d 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -785,10 +785,9 @@ 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 built-in rake tasks to help in testing. -Below table lists available commands which 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 | | ----------------------- | ----------- | @@ -804,7 +803,7 @@ when you initiate a Rails project. | `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. -- cgit v1.2.3 From 70d1b5a7f8e25b077168deaf592e0e58c3f2bdd1 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Fri, 14 Nov 2014 10:45:53 -0700 Subject: Revert "Improve performance of AR object instantiation" This reverts commit 8fee923888192a658d8823b31e77ed0683dfd665. Conflicts: activerecord/lib/active_record/attribute_set/builder.rb This solution sucks, and is hard to actually apply across the board. Going to try other solutions --- .../lib/active_record/attribute_set/builder.rb | 21 +++------------- activerecord/lib/active_record/inheritance.rb | 12 ++++------ activerecord/lib/active_record/persistence.rb | 28 +++------------------- activerecord/lib/active_record/querying.rb | 2 +- activerecord/lib/active_record/result.rb | 9 ------- 5 files changed, 11 insertions(+), 61 deletions(-) diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb index 0a62c68bfb..d4a787f2fe 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -8,33 +8,18 @@ module ActiveRecord end def build_from_database(values = {}, additional_types = {}) - build_from_database_pairs(values.keys, values.values, additional_types) - end - - def build_from_database_pairs(columns, values, additional_types) - attributes = build_attributes_from_values(columns, values, additional_types) + attributes = build_attributes_from_values(values, additional_types) add_uninitialized_attributes(attributes) AttributeSet.new(attributes) end private - def build_attributes_from_values(columns, values, additional_types) - # We are performing manual iteration here as this method is a performance - # hotspot - hash = {} - index = 0 - length = columns.length - - while index < length - name = columns[index] - value = values[index] + 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) - index += 1 end - - hash end def add_uninitialized_attributes(attributes) diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb index 4aad3217cb..f58145ab05 100644 --- a/activerecord/lib/active_record/inheritance.rb +++ b/activerecord/lib/active_record/inheritance.rb @@ -165,19 +165,15 @@ module ActiveRecord # record instance. For single-table inheritance, we check the record # for a +type+ column and return the corresponding class. def discriminate_class_for_record(record) - discriminate_class_for_value(record[inheritance_column]) - end - - def discriminate_class_for_value(value) - if using_single_table_inheritance?(value) - find_sti_class(value) + if using_single_table_inheritance?(record) + find_sti_class(record[inheritance_column]) else super end end - def using_single_table_inheritance?(value) - value.present? && columns_hash.include?(inheritance_column) + def using_single_table_inheritance?(record) + record[inheritance_column].present? && columns_hash.include?(inheritance_column) end def find_sti_class(type_name) diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index 06c8bceb30..507faf2879 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -65,41 +65,19 @@ module ActiveRecord # how this "single-table" inheritance mapping is implemented. def instantiate(attributes, column_types = {}) klass = discriminate_class_for_record(attributes) - klass.instantiate_pairs(attributes.keys, attributes.values, column_types) - end - - def instantiate_pairs(columns, values, column_types = {}) # :nodoc: - attributes = attributes_builder.build_from_database_pairs(columns, values, column_types) - allocate.init_with('attributes' => attributes, 'new_record' => false) - end - - def instantiate_result_set(result_set, column_types = {}) # :nodoc: - inheritance_column_index = inheritance_column && result_set.columns.find_index(inheritance_column) - - result_set.each_pair.map do |columns, values| - inheritance_value = inheritance_column_index && values[inheritance_column_index] - klass = discriminate_class_for_value(inheritance_value) - klass.instantiate_pairs(columns, values, column_types) - end + attributes = klass.attributes_builder.build_from_database(attributes, column_types) + klass.allocate.init_with('attributes' => attributes, 'new_record' => false) end private # Called by +instantiate+ to decide which class to use for a new # record instance. # - # See +ActiveRecord::Inheritance#discriminate_class_for_value+ for + # See +ActiveRecord::Inheritance#discriminate_class_for_record+ for # the single-table inheritance discriminator. - def discriminate_class_for_value(*) - self - end - def discriminate_class_for_record(record) self end - - def inheritance_column - nil - end end # Returns true if this object hasn't been saved yet -- that is, a record diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb index 9d4df81b07..e8de4db3a7 100644 --- a/activerecord/lib/active_record/querying.rb +++ b/activerecord/lib/active_record/querying.rb @@ -47,7 +47,7 @@ module ActiveRecord } message_bus.instrument('instantiation.active_record', payload) do - instantiate_result_set(result_set, column_types) + result_set.map { |record| instantiate(record, column_types) } end end diff --git a/activerecord/lib/active_record/result.rb b/activerecord/lib/active_record/result.rb index c84ad586e2..3a3e65ef32 100644 --- a/activerecord/lib/active_record/result.rb +++ b/activerecord/lib/active_record/result.rb @@ -54,15 +54,6 @@ module ActiveRecord end end - def each_pair - return to_enum(__method__) unless block_given? - - columns = @columns.map { |c| c.dup.freeze } - @rows.each do |row| - yield columns, row - end - end - def to_hash hash_rows end -- cgit v1.2.3 From 0f29c216074c5da6644feddb5184c4881c078b0d Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Fri, 14 Nov 2014 11:20:28 -0700 Subject: Reduce the amount of work performed when instantiating AR models We don't know which attributes will or won't be used, and we don't want to create massive bottlenecks at instantiation. Rather than doing *any* iteration over types and values, we can lazily instantiate the object. The lazy attribute hash should not fully implement hash, or subclass hash at any point in the future. It is not meant to be a replacement, but instead implement its own interface which happens to overlap. --- .../active_record/attribute_methods/primary_key.rb | 1 + activerecord/lib/active_record/attribute_set.rb | 14 ++-- .../lib/active_record/attribute_set/builder.rb | 78 +++++++++++++++++----- activerecord/lib/active_record/core.rb | 2 - activerecord/lib/active_record/model_schema.rb | 2 +- activerecord/test/cases/attribute_set_test.rb | 9 +++ 6 files changed, 79 insertions(+), 27 deletions(-) diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb index 9bd333bbac..104d84a1f8 100644 --- a/activerecord/lib/active_record/attribute_methods/primary_key.rb +++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb @@ -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_set.rb b/activerecord/lib/active_record/attribute_set.rb index 98ac63c7e1..21c58cbf1d 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,6 +23,10 @@ module ActiveRecord attributes.key?(name) && self[name].initialized? end + def keys + attributes.initialized_keys + end + def fetch_value(name, &block) self[name].value(&block) end @@ -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..3946e02d10 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -1,35 +1,83 @@ 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 private + end + end + + class LazyAttributeHash + delegate :select, :transform_values, to: :materialize + delegate :[], :[]=, :freeze, to: :delegate_hash + + def initialize(types, values, additional_types) + @types = types + @values = values + @additional_types = additional_types + @materialized = false + @delegate_hash = {} + assign_default_proc + end + + def key?(key) + delegate_hash.key?(key) || values.key?(key) || types.key?(key) + end + + def initialized_keys + delegate_hash.keys | values.keys + end - 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) + def initialize_dup(_) + @delegate_hash = delegate_hash.transform_values(&:dup) + assign_default_proc + super + end + + def initialize_clone(_) + @delegate_hash = delegate_hash.clone + super + end + + protected + + attr_reader :types, :values, :additional_types, :delegate_hash + + private + + def assign_default_proc + delegate_hash.default_proc = proc do |hash, name| + type = additional_types.fetch(name, types[name]) + + if values.key?(name) + hash[name] = Attribute.from_database(name, values[name], type) + elsif type + hash[name] = Attribute.uninitialized(name, type) end 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| delegate_hash[key] } + types.each_key { |key| delegate_hash[key] } + @materialized = true end + delegate_hash end end end diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index 952aeaa703..89d8932e9e 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -536,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/model_schema.rb b/activerecord/lib/active_record/model_schema.rb index a444aac23c..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: diff --git a/activerecord/test/cases/attribute_set_test.rb b/activerecord/test/cases/attribute_set_test.rb index dc20c3c676..a531be482e 100644 --- a/activerecord/test/cases/attribute_set_test.rb +++ b/activerecord/test/cases/attribute_set_test.rb @@ -123,6 +123,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? -- cgit v1.2.3 From 3f63ac4e4dd22a452a37ad7a654cf5e4f4e66349 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Fri, 14 Nov 2014 11:58:35 -0700 Subject: Correctly determine if an attribute is uninitialized In real usage, we give the builder a types hash with a default value of `Type::Value.new`. This means we need to explicitly check for the key, rather than the truthiness of the type to determine if it's a known but uninitialized attribute --- activerecord/lib/active_record/attribute_set/builder.rb | 2 +- activerecord/test/cases/attribute_set_test.rb | 10 +++++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb index 3946e02d10..54e9cbb779 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -65,7 +65,7 @@ module ActiveRecord if values.key?(name) hash[name] = Attribute.from_database(name, values[name], type) - elsif type + elsif types.key?(name) hash[name] = Attribute.uninitialized(name, type) end end diff --git a/activerecord/test/cases/attribute_set_test.rb b/activerecord/test/cases/attribute_set_test.rb index a531be482e..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 -- cgit v1.2.3 From 895a53e7161e9bdc6285fe03f16b49ec74972416 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Fri, 14 Nov 2014 12:02:05 -0700 Subject: Allow `LazyAttributeHash` to be marshalled `default_proc` makes a hash unmarshallable, and adds unneccessary overhead. Since we control all access to the hash, let's just handle it in that method. This has the side effect of improving performance on initialization (but not neccessarily on access). We'll need to profile further once the tests are passing. --- .../lib/active_record/attribute_set/builder.rb | 30 ++++++++++++---------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb index 54e9cbb779..4134032659 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -23,7 +23,7 @@ module ActiveRecord class LazyAttributeHash delegate :select, :transform_values, to: :materialize - delegate :[], :[]=, :freeze, to: :delegate_hash + delegate :[]=, :freeze, to: :delegate_hash def initialize(types, values, additional_types) @types = types @@ -31,20 +31,26 @@ module ActiveRecord @additional_types = additional_types @materialized = false @delegate_hash = {} - assign_default_proc end def key?(key) delegate_hash.key?(key) || values.key?(key) || types.key?(key) end + def [](key) + if delegate_hash.key?(key) + delegate_hash[key] + else + assign_default_value(key) + end + end + def initialized_keys delegate_hash.keys | values.keys end def initialize_dup(_) @delegate_hash = delegate_hash.transform_values(&:dup) - assign_default_proc super end @@ -59,22 +65,20 @@ module ActiveRecord private - def assign_default_proc - delegate_hash.default_proc = proc do |hash, name| - type = additional_types.fetch(name, types[name]) + def assign_default_value(name) + type = additional_types.fetch(name, types[name]) - if values.key?(name) - hash[name] = Attribute.from_database(name, values[name], type) - elsif types.key?(name) - hash[name] = Attribute.uninitialized(name, type) - end + if values.key?(name) + delegate_hash[name] = Attribute.from_database(name, values[name], type) + elsif types.key?(name) + delegate_hash[name] = Attribute.uninitialized(name, type) end end def materialize unless @materialized - values.each_key { |key| delegate_hash[key] } - types.each_key { |key| delegate_hash[key] } + values.each_key { |key| self[key] } + types.each_key { |key| self[key] } @materialized = true end delegate_hash -- cgit v1.2.3 From 48f2620df98e6926d38b8951087ab1bbc512580c Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Fri, 14 Nov 2014 12:37:25 -0700 Subject: Don't freeze the same hash we use for memoization --- activerecord/lib/active_record/attribute_set/builder.rb | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb index 4134032659..73b77d2eda 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -23,7 +23,6 @@ module ActiveRecord class LazyAttributeHash delegate :select, :transform_values, to: :materialize - delegate :[]=, :freeze, to: :delegate_hash def initialize(types, values, additional_types) @types = types @@ -45,6 +44,13 @@ module ActiveRecord end 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 @@ -54,11 +60,6 @@ module ActiveRecord super end - def initialize_clone(_) - @delegate_hash = delegate_hash.clone - super - end - protected attr_reader :types, :values, :additional_types, :delegate_hash -- cgit v1.2.3 From 3e296e7a3a43099321d80c6d92a326e738b8322a Mon Sep 17 00:00:00 2001 From: "yuuji.yaginuma" Date: Sat, 15 Nov 2014 13:48:03 +0900 Subject: [ci skip] add "Qu" to Backends Features list --- activejob/lib/active_job/queue_adapters.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/activejob/lib/active_job/queue_adapters.rb b/activejob/lib/active_job/queue_adapters.rb index f22b0502dc..4b91c93dbe 100644 --- a/activejob/lib/active_job/queue_adapters.rb +++ b/activejob/lib/active_job/queue_adapters.rb @@ -19,6 +19,7 @@ module ActiveJob # |-------------------|-------|--------|-----------|------------|---------|---------| # | 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 | -- cgit v1.2.3 From a25753b299218fd51aa7d9cb11798a7df7e5c7d2 Mon Sep 17 00:00:00 2001 From: Benjamin Fleischer Date: Sat, 15 Nov 2014 03:39:06 -0600 Subject: Update to Unicode 7.0.0 7.0.0 was released on June 16, 2014 http://unicode-inc.blogspot.com.ar/2014/10/unicode-version-70-complete-text-of.html ruby bin/generate_tables --- .../lib/active_support/multibyte/unicode.rb | 2 +- .../lib/active_support/values/unicode_tables.dat | Bin 904640 -> 1001806 bytes 2 files changed, 1 insertion(+), 1 deletion(-) 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/values/unicode_tables.dat b/activesupport/lib/active_support/values/unicode_tables.dat index 394ee95f4b..760be4c07a 100644 Binary files a/activesupport/lib/active_support/values/unicode_tables.dat and b/activesupport/lib/active_support/values/unicode_tables.dat differ -- cgit v1.2.3 From e05714fdbc4d6a767f207b08a94ba3ebf147213e Mon Sep 17 00:00:00 2001 From: Genadi Samokovarov Date: Sun, 16 Nov 2014 17:17:06 +0200 Subject: Don't let #{application,framework,full}_trace be nil Those three can be nil when exception backtrace is nil. This happens and that forced a couple of nil guards in the code. I'm proposing to make those always return an array, even on nil backtrace. --- .../middleware/exception_wrapper.rb | 24 +++++++------- .../middleware/templates/rescues/_source.erb | 38 ++++++++++------------ actionpack/test/dispatch/exception_wrapper_test.rb | 31 ++++++++++++++++++ 3 files changed, 62 insertions(+), 31 deletions(-) diff --git a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb index e0140b0692..b8381aba70 100644 --- a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb +++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb @@ -62,14 +62,12 @@ module ActionDispatch framework_trace_with_ids = [] full_trace_with_ids = [] - if full_trace - full_trace.each_with_index do |trace, idx| - trace_with_id = { id: idx, trace: trace } + full_trace.each_with_index do |trace, idx| + trace_with_id = { id: idx, trace: trace } - appplication_trace_with_ids << trace_with_id if application_trace.include?(trace) - framework_trace_with_ids << trace_with_id if framework_trace.include?(trace) - full_trace_with_ids << trace_with_id - end + appplication_trace_with_ids << trace_with_id if application_trace.include?(trace) + framework_trace_with_ids << trace_with_id if framework_trace.include?(trace) + full_trace_with_ids << trace_with_id end { @@ -84,7 +82,7 @@ module ActionDispatch end def source_extract - exception.backtrace.map do |trace| + backtrace.map do |trace| file, line = trace.split(":") line_number = line.to_i { @@ -92,11 +90,15 @@ module ActionDispatch 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 @@ -111,9 +113,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/templates/rescues/_source.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb index eabac3a9d2..101cea13f9 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] %> -
" id="frame-source-<%=index%>"> -
- Extracted source (around line #<%= extract_source[:line_number] %>): -
-
- - - +
-
-                  <% extract_source[:code].each_key do |line_number| %>
+<% @source_extract.each_with_index do |extract_source, index| %>
+  <% if extract_source[:code] %>
+    
" id="frame-source-<%=index%>"> +
+ Extracted source (around line #<%= extract_source[:line_number] %>): +
+
+ + + + <% end %> + + - -
+
+                <% extract_source[:code].each_key do |line_number| %>
 <%= line_number -%>
-                  <% end %>
-                
-
 <% extract_source[:code].each do |line, source| -%>
"><%= source -%>
<% end -%>
-
+
- <% end %> +
<% end %> <% end %> diff --git a/actionpack/test/dispatch/exception_wrapper_test.rb b/actionpack/test/dispatch/exception_wrapper_test.rb index 3ddaa7294b..57292d3191 100644 --- a/actionpack/test/dispatch/exception_wrapper_test.rb +++ b/actionpack/test/dispatch/exception_wrapper_test.rb @@ -10,6 +10,12 @@ module ActionDispatch end end + class BadlyDefinedError < StandardError + def backtrace + nil + end + end + setup do Rails.stubs(:root).returns(Pathname.new('.')) @@ -28,6 +34,7 @@ module ActionDispatch assert_equal [ code: 'foo', file: 'lib/file.rb', line_number: 42 ], wrapper.source_extract 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) @@ -35,6 +42,14 @@ module ActionDispatch 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) @@ -42,6 +57,14 @@ module ActionDispatch 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) @@ -49,6 +72,14 @@ module ActionDispatch 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) -- cgit v1.2.3 From b7c262b2500a0e73856f9848f83589414987f172 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Sun, 16 Nov 2014 23:22:33 +0800 Subject: [CI SKIP] Missing space. --- guides/source/active_job_basics.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md index ca851371a9..0e9e4eff1d 100644 --- a/guides/source/active_job_basics.md +++ b/guides/source/active_job_basics.md @@ -248,7 +248,7 @@ end ``` -ActionMailer +Action Mailer ------------ One of the most common jobs in a modern web application is sending emails outside -- cgit v1.2.3 From e950c3e47b89a83aa81a9b0cde3c1f4848dc006d Mon Sep 17 00:00:00 2001 From: Greg Molnar Date: Sun, 16 Nov 2014 16:38:08 +0000 Subject: add Nokogiri to docs generation guides --- guides/source/getting_started.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 92f8ef5b08..1996158e27 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -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 -- cgit v1.2.3 From 20ad04e5fcfd5b972bfffb6c47b44646c41b8a82 Mon Sep 17 00:00:00 2001 From: Genadi Samokovarov Date: Mon, 3 Nov 2014 22:59:45 +0200 Subject: Rename #source_extract to #source_extracts in ExceptionWrapper It returns multiple source extracts since 1ed264bc. Also cleaned its result structure, as we no longer need the file in a code extract. --- actionpack/lib/action_dispatch/middleware/debug_exceptions.rb | 2 +- actionpack/lib/action_dispatch/middleware/exception_wrapper.rb | 4 ++-- .../action_dispatch/middleware/templates/rescues/_source.erb | 10 +++++----- actionpack/test/dispatch/exception_wrapper_test.rb | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb index 798c087d64..9651692952 100644 --- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb @@ -53,7 +53,7 @@ module ActionDispatch 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 ) diff --git a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb index b8381aba70..49f526d6be 100644 --- a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb +++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb @@ -81,13 +81,13 @@ module ActionDispatch Rack::Utils.status_code(@@rescue_responses[class_name]) end - def source_extract + 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 diff --git a/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb index 101cea13f9..e7b913bbe4 100644 --- a/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb +++ b/actionpack/lib/action_dispatch/middleware/templates/rescues/_source.erb @@ -1,22 +1,22 @@ -<% @source_extract.each_with_index do |extract_source, index| %> - <% if extract_source[:code] %> +<% @source_extracts.each_with_index do |source_extract, index| %> + <% if source_extract[:code] %>
" id="frame-source-<%=index%>">
- Extracted source (around line #<%= extract_source[:line_number] %>): + Extracted source (around line #<%= source_extract[:line_number] %>):
diff --git a/actionpack/test/dispatch/exception_wrapper_test.rb b/actionpack/test/dispatch/exception_wrapper_test.rb index 57292d3191..d7408164ba 100644 --- a/actionpack/test/dispatch/exception_wrapper_test.rb +++ b/actionpack/test/dispatch/exception_wrapper_test.rb @@ -25,13 +25,13 @@ module ActionDispatch @environment = { 'action_dispatch.backtrace_cleaner' => cleaner } end - test '#source_extract fetches source fragments for every backtrace entry' do + 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', file: 'lib/file.rb', line_number: 42 ], wrapper.source_extract + assert_equal [ code: 'foo', line_number: 42 ], wrapper.source_extracts end -- cgit v1.2.3 From 2301d8cd26c6802c2b6729787c2122c52ea8c201 Mon Sep 17 00:00:00 2001 From: Genadi Samokovarov Date: Sun, 16 Nov 2014 19:19:48 +0200 Subject: Don't show full trace on routing errors Since dbcbbcf2bc58e8971672b143d1c52c0244e33f26 the full trace is shown by default on routing errors. While this is a nice feature to have, it does take the attention off the routes table in this view and I think this is what most of the people look for in this page. Added an exception to the default trace switching rule to remove that noise. --- actionpack/lib/action_dispatch/middleware/debug_exceptions.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb index 798c087d64..9755d949e7 100644 --- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb @@ -38,7 +38,7 @@ module ActionDispatch traces = wrapper.traces trace_to_show = 'Application Trace' - if traces[trace_to_show].empty? + if traces[trace_to_show].empty? && wrapper.rescue_template != 'routing_error' trace_to_show = 'Full Trace' end -- cgit v1.2.3 From ff1902789d45190dd298b65342699d6043dd8ef2 Mon Sep 17 00:00:00 2001 From: Genadi Samokovarov Date: Thu, 13 Nov 2014 23:59:45 +0100 Subject: Don't double check trace origin in ExceptionWrapper#traces If a trace isn't an application one, then it comes from a framework. That's the definition of framework trace. We can speed up the traces generation if we don't double check that. --- actionpack/lib/action_dispatch/middleware/exception_wrapper.rb | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb index b8381aba70..edd98c5cf2 100644 --- a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb +++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb @@ -65,8 +65,12 @@ module ActionDispatch full_trace.each_with_index do |trace, idx| trace_with_id = { id: idx, trace: trace } - appplication_trace_with_ids << trace_with_id if application_trace.include?(trace) - framework_trace_with_ids << trace_with_id if framework_trace.include?(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 -- cgit v1.2.3 From 2cfaa22d3829e89ff06cfdc5467e16a7921c62ef Mon Sep 17 00:00:00 2001 From: michaeljayt Date: Mon, 17 Nov 2014 02:42:29 +0800 Subject: Skip spring install in Cygwin due to fork() bad support. See also: https://www.cygwin.com/faq.html#faq.using.fixing-fork-failures --- railties/lib/rails/generators/app_base.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index 92ed9136a0..b651623b53 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -342,7 +342,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 -- cgit v1.2.3 From c3e8d15e8babd8c27aa04ced8cde40fdc124416a Mon Sep 17 00:00:00 2001 From: Calvin Correli Date: Wed, 12 Nov 2014 13:06:18 +0100 Subject: Fix for assigns(:..) resetting template assertions When calling assigns(:...) or cookies(:...), template assertions would be reset, which they obviously shouldn't be. --- actionpack/lib/action_dispatch/testing/integration.rb | 10 +++++++--- actionpack/test/dispatch/template_assertions_test.rb | 14 +++++++++++++- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/actionpack/lib/action_dispatch/testing/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index fb816aa875..731305227d 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -334,9 +334,13 @@ module ActionDispatch 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 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 -- cgit v1.2.3 From da99a2a2982d35f670ad9647463e09bfe9032b70 Mon Sep 17 00:00:00 2001 From: Sam Date: Mon, 17 Nov 2014 14:55:17 +1100 Subject: PERF: optimise type lookup to avoid invoking procs --- .../connection_adapters/postgresql_adapter.rb | 20 +++++++++++++------- .../lib/active_record/type/hash_lookup_type_map.rb | 20 +++++++++++++++++++- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 6310d70192..d3e5b0a4ad 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -431,16 +431,22 @@ module ActiveRecord private def get_oid_type(oid, fmod, column_name, sql_type = '') # :nodoc: - if !type_map.key?(oid) + + result = type_map.fetch(oid, fmod, sql_type) { + nil + } + + unless result load_additional_types(type_map, [oid]) + result = type_map.fetch(oid, fmod, sql_type) { + warn "unknown OID #{oid}: failed to recognize type of '#{column_name}'. It will be treated as String." + Type::Value.new.tap do |cast_type| + type_map.register_type(oid, cast_type) + end + } end - type_map.fetch(oid, fmod, sql_type) { - warn "unknown OID #{oid}: failed to recognize type of '#{column_name}'. It will be treated as String." - Type::Value.new.tap do |cast_type| - type_map.register_type(oid, cast_type) - end - } + result end def initialize_type_map(m) # :nodoc: 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..2a146d38a9 100644 --- a/activerecord/lib/active_record/type/hash_lookup_type_map.rb +++ b/activerecord/lib/active_record/type/hash_lookup_type_map.rb @@ -1,6 +1,12 @@ module ActiveRecord module Type class HashLookupTypeMap < TypeMap # :nodoc: + + def initialize + @cache = {} + super + end + delegate :key?, to: :@mapping def lookup(type, *args) @@ -8,12 +14,24 @@ module ActiveRecord end def fetch(type, *args, &block) - @mapping.fetch(type, block).call(type, *args) + cache = (@cache[type] ||= {}) + resolved = cache[args] + + unless resolved + resolved = cache[args] = @mapping.fetch(type, block).call(type, *args) + end + + resolved end def alias_type(type, alias_type) register_type(type) { |_, *args| lookup(alias_type, *args) } end + + def register_type(key, value=nil, &block) + @cache = {} + super(key, value, &block) + end end end end -- cgit v1.2.3 From 6f57e1240eed636a6f47f131a9f39360e28a80c4 Mon Sep 17 00:00:00 2001 From: George Millo Date: Mon, 17 Nov 2014 15:26:33 +0700 Subject: Minor English fixes in docs [ci skip] --- guides/source/active_support_core_extensions.md | 2 +- railties/lib/rails/engine.rb | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index f6f96b79c6..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 diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index d985518fd9..023ea98145 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: # -- cgit v1.2.3 From 402cc9f46acfd1ff172fdff5bc99f397d498607d Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Mon, 17 Nov 2014 03:42:00 -0800 Subject: Revert "Merge pull request #16622 from matthewd/default-debug" This reverts commit 2602a49a8600ab52f807599bbd5b1f9c0be4214f, reversing changes made to 5d7c1057684c377bc2801c8851e99ff11ab23530. The explicit default was introduced in 21f6d72, so apps created with Rails < 4 have the commented out version, which means that this change would break those apps. --- railties/lib/rails/application/configuration.rb | 2 +- .../rails/app/templates/config/environments/production.rb.tt | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/railties/lib/rails/application/configuration.rb b/railties/lib/rails/application/configuration.rb index 786dcee007..8a5bce64a0 100644 --- a/railties/lib/rails/application/configuration.rb +++ b/railties/lib/rails/application/configuration.rb @@ -118,7 +118,7 @@ module Rails end def log_level - @log_level ||= :debug + @log_level ||= Rails.env.production? ? :info : :debug end def colorize_logging 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..aa7b93f0a1 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,8 @@ 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 + # Set to :info to decrease the log volume. + config.log_level = :debug # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] -- cgit v1.2.3 From a6de6f508c6566af098999ca70f93ee8023bc9a5 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Mon, 17 Nov 2014 04:17:23 -0800 Subject: Deprecate different default for `log_level` in production This is a more conservative approach to 2602a49. Also changed the comment to be more inline with everything else in the file (describing what the config value is doing and why). People should just read the docs for alternatives. --- railties/lib/rails/application/bootstrap.rb | 13 +++++++++++++ railties/lib/rails/application/configuration.rb | 13 +++++++++++-- .../app/templates/config/environments/production.rb.tt | 3 ++- 3 files changed, 26 insertions(+), 3 deletions(-) diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb index 0f4d932749..92ecc29a5f 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_leve` 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 8a5bce64a0..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 ||= Rails.env.production? ? :info : :debug + @log_level ||= (Rails.env.production? ? :info : :debug) end def colorize_logging 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 aa7b93f0a1..91dea5858f 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,7 +45,8 @@ Rails.application.configure do # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true - # Set to :info to decrease the log volume. + # 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. -- cgit v1.2.3 From c7727559e1df44e5930983901949e035b6346774 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Mon, 17 Nov 2014 04:23:00 -0800 Subject: Meant to describe the concept, not the setting [ci skip] --- .../generators/rails/app/templates/config/environments/production.rb.tt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 91dea5858f..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,7 +45,7 @@ Rails.application.configure do # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true - # Use the lowest log_level to ensure availability of diagnostic information + # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug -- cgit v1.2.3 From 409e7e4fc5332bf6199ac927d816c51f1d6a3307 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Mon, 17 Nov 2014 05:59:06 -0800 Subject: Remove pointless `private` This class no longer has any private methods --- activerecord/lib/active_record/attribute_set/builder.rb | 2 -- 1 file changed, 2 deletions(-) diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb index 73b77d2eda..60154a0647 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -16,8 +16,6 @@ module ActiveRecord attributes = LazyAttributeHash.new(types, values, additional_types) AttributeSet.new(attributes) end - - private end end -- cgit v1.2.3 From 7da5d8a5dc0116dabc395cb25482adf3d733d597 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Mon, 17 Nov 2014 06:39:32 -0800 Subject: Add StackProf to the test group for 2.1 Makes life easier for people profiling on master. --- Gemfile | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Gemfile b/Gemfile index fa17d217c9..e7b7913970 100644 --- a/Gemfile +++ b/Gemfile @@ -64,6 +64,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 -- cgit v1.2.3 From 29b3e548f32c42cb99d9dd2d03c2cd34fa53d867 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Mon, 17 Nov 2014 07:11:13 -0800 Subject: Improve the performance of quoting table names on PG This caused a pretty major performance regression for 4.2, as this is a hotspot for query construction. We're still slightly slower than 4.1, but it's much less significant. --- .../connection_adapters/postgresql/utils.rb | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) 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 # * "schema_name".table_name # * "schema.name"."table name" 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 -- cgit v1.2.3 From 1966ecf6687d62e1130d862be7f86c5b1b56e341 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Mon, 17 Nov 2014 23:45:58 +0800 Subject: Fix typo. --- railties/lib/rails/application/bootstrap.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/application/bootstrap.rb b/railties/lib/rails/application/bootstrap.rb index 92ecc29a5f..71d3febde4 100644 --- a/railties/lib/rails/application/bootstrap.rb +++ b/railties/lib/rails/application/bootstrap.rb @@ -58,7 +58,7 @@ INFO 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_leve` is `:info` for the production " \ + "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 " \ -- cgit v1.2.3 From 5b7b98d5904e9f01f13b783f1a692a1c11168b2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Mon, 17 Nov 2014 16:37:17 -0200 Subject: document_root_element need to be public --- Gemfile | 1 + actionpack/lib/action_controller/test_case.rb | 8 ++++---- actionview/lib/action_view/test_case.rb | 10 +++++----- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/Gemfile b/Gemfile index e7b7913970..0705a21046 100644 --- a/Gemfile +++ b/Gemfile @@ -15,6 +15,7 @@ gem 'jquery-rails', '~> 4.0.0.beta2' gem 'coffee-rails', '~> 4.1.0' gem 'turbolinks' gem 'arel', github: 'rails/arel' +gem 'rails-dom-testing', path: '~/src/rails/rails-dom-testing' # require: false so bcrypt is loaded only when has_secure_password is used. # This is to avoid ActiveModel (and by extension the entire framework) diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index aa475dc4c4..097019144c 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -679,6 +679,10 @@ module ActionController klass.new end + def document_root_element + html_document + end + included do include ActionController::TemplateAssertions include ActionDispatch::Assertions @@ -688,10 +692,6 @@ module ActionController private - def document_root_element - html_document - end - def check_required_ivars # Sanity check for required instance variables so we can give an # understandable error message. diff --git a/actionview/lib/action_view/test_case.rb b/actionview/lib/action_view/test_case.rb index fec980462d..5cffddcd4f 100644 --- a/actionview/lib/action_view/test_case.rb +++ b/actionview/lib/action_view/test_case.rb @@ -125,6 +125,11 @@ module ActionView @_rendered_views ||= RenderedViewsCollection.new end + # 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) + end + class RenderedViewsCollection def initialize @rendered_views ||= Hash.new { |hash, key| hash[key] = [] } @@ -156,11 +161,6 @@ module ActionView private - # 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) - end - def say_no_to_protect_against_forgery! _helpers.module_eval do remove_possible_method :protect_against_forgery? -- cgit v1.2.3 From 27a181f7518616b5b508e17271145e330d948cd2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Mon, 17 Nov 2014 16:38:30 -0200 Subject: Use GitHub, not my local fork :sweat_smile: --- Gemfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Gemfile b/Gemfile index 0705a21046..60b668401d 100644 --- a/Gemfile +++ b/Gemfile @@ -15,7 +15,7 @@ gem 'jquery-rails', '~> 4.0.0.beta2' gem 'coffee-rails', '~> 4.1.0' gem 'turbolinks' gem 'arel', github: 'rails/arel' -gem 'rails-dom-testing', path: '~/src/rails/rails-dom-testing' +gem 'rails-dom-testing', github: 'rails/rails-dom-testing' # require: false so bcrypt is loaded only when has_secure_password is used. # This is to avoid ActiveModel (and by extension the entire framework) -- cgit v1.2.3 From 916731686ba2b48abf96251639fdb8b8af63814c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Mon, 17 Nov 2014 16:44:15 -0200 Subject: Generate new applications with the right rails-dom-testing version --- railties/lib/rails/generators/app_base.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index b651623b53..5f8c33c713 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -195,9 +195,11 @@ module Rails def rails_gemfile_entry if options.dev? - [GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH)] + [GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH), + GemfileEntry.github('rails-dom-testing', 'rails/rails-dom-testing')] elsif options.edge? - [GemfileEntry.github('rails', 'rails/rails')] + [GemfileEntry.github('rails', 'rails/rails'), + GemfileEntry.github('rails-dom-testing', 'rails/rails-dom-testing')] else [GemfileEntry.version('rails', Rails::VERSION::STRING, -- cgit v1.2.3 From bf149679f426c1f6d3e5d280ed19b42f62c9b33f Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Mon, 17 Nov 2014 14:36:00 -0800 Subject: Force table creation in tests If something causes the teardown block to not get run (errors, interrupting test runs), we have to manually delete them, which is a pain. --- activerecord/test/cases/migration/foreign_key_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/activerecord/test/cases/migration/foreign_key_test.rb b/activerecord/test/cases/migration/foreign_key_test.rb index 406dd70c37..52e963a14f 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 -- cgit v1.2.3 From c01b20b658c9fe4b7d54f4a227a09cb090b5763d Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Mon, 17 Nov 2014 14:56:06 -0800 Subject: rm `reorder_bind_params` Arel handles this for us automatically. Updated tests, as BindParam is no longer a subclass of SqlLiteral. We should remove the second argument to substitute_at entirely, as it's no longer used --- .../lib/active_record/connection_adapters/abstract_adapter.rb | 2 +- .../connection_adapters/postgresql/database_statements.rb | 4 ---- activerecord/lib/active_record/relation.rb | 1 - activerecord/lib/active_record/relation/query_methods.rb | 10 ---------- activerecord/test/cases/adapters/mysql/connection_test.rb | 2 +- .../test/cases/adapters/postgresql/postgresql_adapter_test.rb | 5 +---- .../test/cases/adapters/sqlite3/sqlite3_adapter_test.rb | 2 +- activerecord/test/cases/bind_parameter_test.rb | 4 ++-- activerecord/test/cases/relations_test.rb | 2 +- 9 files changed, 7 insertions(+), 25 deletions(-) diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index 582dd360f0..a2df76259b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -265,7 +265,7 @@ module ActiveRecord # Returns a bind substitution value given a bind +index+ and +column+ # NOTE: The column param is currently being used by the sqlserver-adapter def substitute_at(column, index = 0) - Arel::Nodes::BindParam.new '?' + Arel::Nodes::BindParam.new end # REFERENTIAL INTEGRITY ==================================== 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 cf379ab210..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 = 0) - 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/relation.rb b/activerecord/lib/active_record/relation.rb index 03bce4f5b7..3aaf037d31 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -84,7 +84,6 @@ module ActiveRecord um = relation .arel .compile_update(substitutes, @klass.primary_key) - reorder_bind_params(um.ast, bvs) @klass.connection.update( um, diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index a686e3263b..cb4e33f1b1 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -881,19 +881,9 @@ 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 - reorder_bind_params(arel.ast, bvs) arel end - def reorder_bind_params(ast, bvs) - ast.grep(Arel::Nodes::BindParam).each_with_index do |bp, i| - column = bvs[i].first - bp.replace connection.substitute_at(column, i) - end - end - def symbol_unscoping(scope) if !VALID_UNSCOPING_VALUES.include?(scope) raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}." diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb index 3dabb1104a..9353607f5d 100644 --- a/activerecord/test/cases/adapters/mysql/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql/connection_test.rb @@ -70,7 +70,7 @@ class MysqlConnectionTest < ActiveRecord::TestCase def test_bind_value_substitute bind_param = @connection.substitute_at('foo', 0) - assert_equal Arel.sql('?'), bind_param + assert_equal Arel.sql('?'), bind_param.to_sql end def test_exec_no_binds diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb index a71c0dfb26..7d6c15c826 100644 --- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb +++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb @@ -305,10 +305,7 @@ module ActiveRecord 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 + assert_equal Arel.sql('$1'), bind.to_sql end def test_partial_index diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index 8c1c22d3bf..54e0309167 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -134,7 +134,7 @@ module ActiveRecord def test_bind_value_substitute bind_param = @conn.substitute_at('foo', 0) - assert_equal Arel.sql('?'), bind_param + assert_equal Arel.sql('?'), bind_param.to_sql end def test_exec_no_binds diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb index 0bc7ee6d64..d1fdfb2458 100644 --- a/activerecord/test/cases/bind_parameter_test.rb +++ b/activerecord/test/cases/bind_parameter_test.rb @@ -33,7 +33,7 @@ module ActiveRecord def test_binds_are_logged sub = @connection.substitute_at(@pk, 0) 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) @@ -44,7 +44,7 @@ module ActiveRecord def test_binds_are_logged_after_type_cast sub = @connection.substitute_at(@pk, 0) 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/relations_test.rb b/activerecord/test/cases/relations_test.rb index 8ac4a4ca36..ca86d58b35 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -1703,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]] -- cgit v1.2.3 From eb26f24bde62cbbcd8ef0e7ee9c64060b098baff Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Mon, 17 Nov 2014 15:04:40 -0800 Subject: Remove the unused second argument to `substitute_at` Oh hey, we got to remove some code because of that! --- .../lib/active_record/associations/association_scope.rb | 3 +-- .../associations/join_dependency/join_association.rb | 2 +- .../active_record/connection_adapters/abstract_adapter.rb | 4 ++-- activerecord/lib/active_record/locking/optimistic.rb | 2 +- activerecord/lib/active_record/persistence.rb | 2 +- activerecord/lib/active_record/relation.rb | 2 +- activerecord/lib/active_record/relation/merger.rb | 12 ------------ activerecord/test/cases/adapters/mysql/connection_test.rb | 2 +- .../cases/adapters/postgresql/postgresql_adapter_test.rb | 2 +- .../test/cases/adapters/sqlite3/sqlite3_adapter_test.rb | 2 +- activerecord/test/cases/bind_parameter_test.rb | 4 ++-- 11 files changed, 12 insertions(+), 25 deletions(-) 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/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/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index a2df76259b..57aa2f9c58 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -262,9 +262,9 @@ 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 = 0) + def substitute_at(column) Arel::Nodes::BindParam.new 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/persistence.rb b/activerecord/lib/active_record/persistence.rb index 507faf2879..ee3b7b6163 100644 --- a/activerecord/lib/active_record/persistence.rb +++ b/activerecord/lib/active_record/persistence.rb @@ -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)) diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 3aaf037d31..8575e5a7be 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -98,7 +98,7 @@ module ActiveRecord end substitutes = values.each_with_index.map do |(arel_attr, _), i| - [arel_attr, @klass.connection.substitute_at(binds[i][0], i)] + [arel_attr, @klass.connection.substitute_at(binds[i][0])] end [substitutes, binds] diff --git a/activerecord/lib/active_record/relation/merger.rb b/activerecord/lib/active_record/relation/merger.rb index a8febf6a18..a27f990f74 100644 --- a/activerecord/lib/active_record/relation/merger.rb +++ b/activerecord/lib/active_record/relation/merger.rb @@ -118,18 +118,6 @@ module ActiveRecord 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 diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb index 9353607f5d..52eebe1886 100644 --- a/activerecord/test/cases/adapters/mysql/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql/connection_test.rb @@ -69,7 +69,7 @@ class MysqlConnectionTest < ActiveRecord::TestCase end def test_bind_value_substitute - bind_param = @connection.substitute_at('foo', 0) + bind_param = @connection.substitute_at('foo') assert_equal Arel.sql('?'), bind_param.to_sql end diff --git a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb index 7d6c15c826..c3c696b871 100644 --- a/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb +++ b/activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb @@ -304,7 +304,7 @@ module ActiveRecord end def test_substitute_at - bind = @connection.substitute_at(nil, 0) + bind = @connection.substitute_at(nil) assert_equal Arel.sql('$1'), bind.to_sql end diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index 54e0309167..d83c65cf0e 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -133,7 +133,7 @@ module ActiveRecord end def test_bind_value_substitute - bind_param = @conn.substitute_at('foo', 0) + bind_param = @conn.substitute_at('foo') assert_equal Arel.sql('?'), bind_param.to_sql end diff --git a/activerecord/test/cases/bind_parameter_test.rb b/activerecord/test/cases/bind_parameter_test.rb index d1fdfb2458..c4634d11e2 100644 --- a/activerecord/test/cases/bind_parameter_test.rb +++ b/activerecord/test/cases/bind_parameter_test.rb @@ -31,7 +31,7 @@ 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.to_sql}" @@ -42,7 +42,7 @@ 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.to_sql}" -- cgit v1.2.3 From 6f7910aed5ceeb8833de760f396858bee917c7bc Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Mon, 17 Nov 2014 17:58:49 -0800 Subject: [PERF] Speed up integer type casting from DB MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We don't have the check the range when the value is coming from the DB, so override type_cast_from_database to short-circuit the extra work. type_cast_from_database (small) 3437507.5 (±29.2%) i/s - 14223135 in 4.996973s type_cast_from_database (large) 3158588.7 (±28.3%) i/s - 13265628 in 4.992121s type_cast (small) 481984.8 (±14.2%) i/s - 2352012 in 5.005694s type_cast (large) 477331.8 (±14.2%) i/s - 2332824 in 5.012365s Comparison: type_cast_from_database (small): 3437507.5 i/s type_cast_from_database (large): 3158588.7 i/s - 1.09x slower type_cast (small): 481984.8 i/s - 7.13x slower type_cast (large): 477331.8 i/s - 7.20x slower The difference is huge but the absolute gain is quite small. That being said this is a hotspot and it showed up on the radar when benchmarking discourse. --- activerecord/lib/active_record/type/integer.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/type/integer.rb b/activerecord/lib/active_record/type/integer.rb index d69e5b3f28..fb6d9df58f 100644 --- a/activerecord/lib/active_record/type/integer.rb +++ b/activerecord/lib/active_record/type/integer.rb @@ -12,7 +12,9 @@ module ActiveRecord :integer end - alias type_cast_for_database type_cast + def type_cast_from_database(value) + value.to_i unless value.nil? + end protected -- cgit v1.2.3 From 52c70d496f34ed4d6c9c8cc1719bc7f86011634b Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Mon, 17 Nov 2014 18:09:40 -0800 Subject: :nail_care: Put escape clause first, keeps @sgrif happy :grin: See comment on 6f7910a --- activerecord/lib/active_record/type/integer.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/type/integer.rb b/activerecord/lib/active_record/type/integer.rb index fb6d9df58f..0149d60b6e 100644 --- a/activerecord/lib/active_record/type/integer.rb +++ b/activerecord/lib/active_record/type/integer.rb @@ -13,7 +13,8 @@ module ActiveRecord end def type_cast_from_database(value) - value.to_i unless value.nil? + return if value.nil? + value.to_i end protected -- cgit v1.2.3 From 3098579f276d5cecbca0b57e35526b99fadfbe5f Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Mon, 17 Nov 2014 18:33:07 -0800 Subject: Revert "[PERF] Speed up integer type casting from DB" This reverts commit 6f7910a and 52c70d4. Query params are type cased through the same method, so this approach doesn't work. --- activerecord/lib/active_record/type/integer.rb | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/activerecord/lib/active_record/type/integer.rb b/activerecord/lib/active_record/type/integer.rb index 0149d60b6e..d69e5b3f28 100644 --- a/activerecord/lib/active_record/type/integer.rb +++ b/activerecord/lib/active_record/type/integer.rb @@ -12,10 +12,7 @@ module ActiveRecord :integer end - def type_cast_from_database(value) - return if value.nil? - value.to_i - end + alias type_cast_for_database type_cast protected -- cgit v1.2.3 From 9aa2b2d7bf52c0f3974090cd033341be2edeae6d Mon Sep 17 00:00:00 2001 From: Sam Date: Tue, 18 Nov 2014 21:38:27 +1100 Subject: PERF: stop allocating the string "id" over and over --- activerecord/lib/active_record/attribute_methods/read.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb index bf2a084a00..55beb309ca 100644 --- a/activerecord/lib/active_record/attribute_methods/read.rb +++ b/activerecord/lib/active_record/attribute_methods/read.rb @@ -76,12 +76,14 @@ module ActiveRecord end end + ID = 'id'.freeze + # Returns the value of the attribute identified by attr_name 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' + name = self.class.primary_key if name == ID @attributes.fetch_value(name, &block) end -- cgit v1.2.3 From 3f38762361a49495a9b728acac7cec7fed4c2b23 Mon Sep 17 00:00:00 2001 From: Rishi Jain Date: Tue, 18 Nov 2014 16:55:54 +0530 Subject: fixed minor typos in RELEASE doc [ci skip] --- RELEASING_RAILS.rdoc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 -- cgit v1.2.3 From e1af2634677b0a301345afa363525bc9268415be Mon Sep 17 00:00:00 2001 From: Javier Vidal Date: Tue, 18 Nov 2014 17:47:06 +0100 Subject: Ruby on Rails 3.0 Release Notes: fix broken link --- guides/source/3_0_release_notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/3_0_release_notes.md b/guides/source/3_0_release_notes.md index 46be2613ab..2630207c0f 100644 --- a/guides/source/3_0_release_notes.md +++ b/guides/source/3_0_release_notes.md @@ -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/) -- cgit v1.2.3 From 8b2c98f6c7c0b7371265905a43fc7d3ad966643a Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Tue, 18 Nov 2014 11:26:16 -0800 Subject: Remove call to `key?` in `LazyAttributeHash#[]` Performance improvement, as well as improved code clarity --- activerecord/lib/active_record/attribute_set/builder.rb | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb index 60154a0647..b433205af3 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -35,11 +35,7 @@ module ActiveRecord end def [](key) - if delegate_hash.key?(key) - delegate_hash[key] - else - assign_default_value(key) - end + delegate_hash[key] || assign_default_value(key) end def []=(key, value) -- cgit v1.2.3 From 3ecc5d30eb0901f4e3c4d3bca1957f633a6a695b Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Tue, 18 Nov 2014 11:46:17 -0800 Subject: LazyAttributeHash is private --- activerecord/lib/active_record/attribute_set/builder.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb index b433205af3..fd134a304b 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -19,7 +19,7 @@ module ActiveRecord end end - class LazyAttributeHash + class LazyAttributeHash # :nodoc: delegate :select, :transform_values, to: :materialize def initialize(types, values, additional_types) -- cgit v1.2.3 From edc39ff756d09b746bdc1acb8d814c3148289846 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Tue, 18 Nov 2014 12:31:23 -0800 Subject: Remove needless call to `key?` when building attributes This appears to be a performance hotspot, see #17655. --- activerecord/lib/active_record/attribute_set/builder.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/attribute_set/builder.rb b/activerecord/lib/active_record/attribute_set/builder.rb index fd134a304b..05138ae36d 100644 --- a/activerecord/lib/active_record/attribute_set/builder.rb +++ b/activerecord/lib/active_record/attribute_set/builder.rb @@ -62,9 +62,11 @@ module ActiveRecord def assign_default_value(name) type = additional_types.fetch(name, types[name]) + value_present = true + value = values.fetch(name) { value_present = false } - if values.key?(name) - delegate_hash[name] = Attribute.from_database(name, values[name], type) + if value_present + delegate_hash[name] = Attribute.from_database(name, value, type) elsif types.key?(name) delegate_hash[name] = Attribute.uninitialized(name, type) end -- cgit v1.2.3 From 1b9e85dbbd7d974143e67affb3166d7244cc99db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Tue, 18 Nov 2014 18:47:22 -0200 Subject: Make sure assert_select can assert body tag This reverts commit f93df52845766216f0fe36a4586f8abad505cac4, reversing changes made to a455e3f4e9dbfb9630d47878e1239bc424fb7d13. Conflicts: actionpack/lib/action_controller/test_case.rb actionview/lib/action_view/test_case.rb --- actionpack/lib/action_controller/test_case.rb | 8 ++++---- .../lib/action_dispatch/testing/assertions.rb | 2 +- .../lib/action_dispatch/testing/integration.rb | 2 +- actionpack/test/controller/integration_test.rb | 6 +++--- actionpack/test/controller/test_case_test.rb | 21 +++++++++++++++++++++ actionview/lib/action_view/test_case.rb | 9 +++++---- 6 files changed, 35 insertions(+), 13 deletions(-) diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 097019144c..30eae41f60 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -679,10 +679,6 @@ module ActionController klass.new end - def document_root_element - html_document - end - included do include ActionController::TemplateAssertions include ActionDispatch::Assertions @@ -692,6 +688,10 @@ module ActionController private + def document_root_element + html_document.root + end + def check_required_ivars # Sanity check for required instance variables so we can give an # understandable error message. 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/integration.rb b/actionpack/lib/action_dispatch/testing/integration.rb index 731305227d..a9a1576fed 100644 --- a/actionpack/lib/action_dispatch/testing/integration.rb +++ b/actionpack/lib/action_dispatch/testing/integration.rb @@ -505,7 +505,7 @@ module ActionDispatch end def document_root_element - html_document + html_document.root end end end diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index 27b30536b0..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 "You are being redirected.", 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! diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb index 957c0a5288..475af90032 100644 --- a/actionpack/test/controller/test_case_test.rb +++ b/actionpack/test/controller/test_case_test.rb @@ -132,6 +132,14 @@ XML render :nothing => true end + def test_without_body + render html: '
'.html_safe + end + + def test_with_body + render html: ''.html_safe + end + private def generate_url(opts) @@ -179,6 +187,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 diff --git a/actionview/lib/action_view/test_case.rb b/actionview/lib/action_view/test_case.rb index 5cffddcd4f..812b011bd7 100644 --- a/actionview/lib/action_view/test_case.rb +++ b/actionview/lib/action_view/test_case.rb @@ -126,10 +126,6 @@ module ActionView end # 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) - end - class RenderedViewsCollection def initialize @rendered_views ||= Hash.new { |hash, key| hash[key] = [] } @@ -161,6 +157,11 @@ module ActionView private + # Need to experiment if this priority is the best one: rendered => output_buffer + def document_root_element + Nokogiri::HTML::Document.parse(@rendered.blank? ? @output_buffer : @rendered).root + end + def say_no_to_protect_against_forgery! _helpers.module_eval do remove_possible_method :protect_against_forgery? -- cgit v1.2.3 From 52fddcc653458456f98b3683dffd781cf00b35fe Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Tue, 18 Nov 2014 13:40:03 -0800 Subject: Speed up integer casting from DB We don't have the check the range when the value is coming from the DB, so override type_cast_from_database to short-circuit the extra work. The difference is huge but the absolute gain is quite small. That being said this is a hotspot and it showed up on the radar when benchmarking discourse. --- activerecord/lib/active_record/type/integer.rb | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/activerecord/lib/active_record/type/integer.rb b/activerecord/lib/active_record/type/integer.rb index d69e5b3f28..36bbd9cd5e 100644 --- a/activerecord/lib/active_record/type/integer.rb +++ b/activerecord/lib/active_record/type/integer.rb @@ -14,6 +14,11 @@ module ActiveRecord 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 -- cgit v1.2.3 From 78e7a0d3b7eaafe1ad0a45e3e355e1123cae3f8b Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Tue, 18 Nov 2014 14:22:33 -0800 Subject: pull the preloader allocation in to a factory method --- activerecord/lib/active_record/relation.rb | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 8575e5a7be..460daf99bc 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -639,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 @@ -650,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) -- cgit v1.2.3 From 08576b94ad4f19dfc368619d7751e211d23dcad8 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Tue, 18 Nov 2014 15:19:15 -0800 Subject: Improve the performance of reading attributes We added a comparison to "id", and call to `self.class.primary_key` a *lot*. We also have performance hits from `&block` all over the place. We skip the check in a new method, in order to avoid breaking the behavior of `read_attribute` --- activerecord/lib/active_record/aggregations.rb | 4 ++-- .../lib/active_record/associations/has_many_association.rb | 2 +- .../associations/has_many_through_association.rb | 2 +- activerecord/lib/active_record/attribute_methods.rb | 4 ++-- activerecord/lib/active_record/attribute_methods/dirty.rb | 2 +- .../lib/active_record/attribute_methods/primary_key.rb | 2 +- activerecord/lib/active_record/attribute_methods/read.rb | 14 ++++++++++---- activerecord/lib/active_record/attribute_set.rb | 4 ++-- activerecord/lib/active_record/enum.rb | 2 +- activerecord/lib/active_record/reflection.rb | 2 +- activerecord/lib/active_record/validations/uniqueness.rb | 2 +- activerecord/test/cases/inheritance_test.rb | 2 +- 12 files changed, 24 insertions(+), 18 deletions(-) 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/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 bde23fc116..6329fdfe95 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -20,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 diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index 34ec397aee..d766996d37 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -332,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 @@ -433,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 104d84a1f8..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 diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb index 55beb309ca..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 @@ -84,13 +84,19 @@ module ActiveRecord def read_attribute(attr_name, &block) name = attr_name.to_s name = self.class.primary_key if name == ID - @attributes.fetch_value(name, &block) + _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_set.rb b/activerecord/lib/active_record/attribute_set.rb index 21c58cbf1d..6b1d7ea79e 100644 --- a/activerecord/lib/active_record/attribute_set.rb +++ b/activerecord/lib/active_record/attribute_set.rb @@ -27,8 +27,8 @@ module ActiveRecord attributes.initialized_keys end - def fetch_value(name, &block) - self[name].value(&block) + def fetch_value(name) + self[name].value { |n| yield n if block_given? } end def write_from_database(name, value) 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/reflection.rb b/activerecord/lib/active_record/reflection.rb index 4b58f2deb7..f4a351b092 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -287,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 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/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 -- cgit v1.2.3 From 644696e2ac04099623a0425016470cc5485e067b Mon Sep 17 00:00:00 2001 From: Akira Matsuda Date: Wed, 19 Nov 2014 08:29:22 +0900 Subject: Duplicated Hash key :prompt --- actionview/test/template/date_helper_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 << %(\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n) expected << "\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 -- cgit v1.2.3 From 995c697511a4e77fbe1e00793486ae07b18c5017 Mon Sep 17 00:00:00 2001 From: dtaniwaki Date: Wed, 19 Nov 2014 10:17:44 +0900 Subject: Support symbol foreign key to delete --- .../connection_adapters/abstract/schema_statements.rb | 2 +- activerecord/test/cases/migration/foreign_key_test.rb | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) 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 cbf87df356..cc86c3776e 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -740,7 +740,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 diff --git a/activerecord/test/cases/migration/foreign_key_test.rb b/activerecord/test/cases/migration/foreign_key_test.rb index 52e963a14f..51e21528c2 100644 --- a/activerecord/test/cases/migration/foreign_key_test.rb +++ b/activerecord/test/cases/migration/foreign_key_test.rb @@ -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" -- cgit v1.2.3 From 97f2c4129ae23ee074986a588628acc689a86462 Mon Sep 17 00:00:00 2001 From: Ryan Bigg Date: Wed, 19 Nov 2014 19:20:19 +1100 Subject: Add space in :start_year description for date_select --- actionview/lib/action_view/helpers/date_helper.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionview/lib/action_view/helpers/date_helper.rb b/actionview/lib/action_view/helpers/date_helper.rb index 01a9747035..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} (%02d)" for example. # See Kernel.sprintf for documentation on format sequences. # * :date_separator - Specifies a string to separate the date fields. Default is "" (i.e. nothing). - # * :start_year - Set the start year for the year select. Default is Date.today.year - 5if + # * :start_year - Set the start year for the year select. Default is Date.today.year - 5 if # you are creating new record. While editing existing record, :start_year defaults to # the current selected year minus 5. # * :end_year - Set the end year for the year select. Default is Date.today.year + 5 if -- cgit v1.2.3 From 74c35b46e362a128fe06f909744da8bb1aeed0e0 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Wed, 19 Nov 2014 11:24:18 -0800 Subject: Introduce test to demonstrate regression caused by da99a2a2 --- activerecord/test/cases/type/type_map_test.rb | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/activerecord/test/cases/type/type_map_test.rb b/activerecord/test/cases/type/type_map_test.rb index 4e32f92dd0..81ac7394a8 100644 --- a/activerecord/test/cases/type/type_map_test.rb +++ b/activerecord/test/cases/type/type_map_test.rb @@ -124,6 +124,16 @@ module ActiveRecord assert_equal mapping.lookup(3), 'string' assert_kind_of Type::Value, mapping.lookup(4) end + + def test_aliases_are_not_improperly_cached + mapping = HashLookupTypeMap.new + + mapping.register_type("foo") { |*args| args.join("-") } + mapping.alias_type("bar", "foo") + + assert_equal "bar-1-2-3", mapping.lookup("bar", 1, 2, 3) + assert_equal "foo-1-2-3", mapping.lookup("foo", 1, 2, 3) + end end end end -- cgit v1.2.3 From b03f9ef86a44b190948be0737bf9ab68e30fc112 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Wed, 19 Nov 2014 11:24:49 -0800 Subject: Revert "PERF: optimise type lookup to avoid invoking procs" This reverts commit da99a2a2982d35f670ad9647463e09bfe9032b70. --- .../connection_adapters/postgresql_adapter.rb | 20 +++++++------------- .../lib/active_record/type/hash_lookup_type_map.rb | 20 +------------------- 2 files changed, 8 insertions(+), 32 deletions(-) diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index d3e5b0a4ad..6310d70192 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -431,22 +431,16 @@ module ActiveRecord private def get_oid_type(oid, fmod, column_name, sql_type = '') # :nodoc: - - result = type_map.fetch(oid, fmod, sql_type) { - nil - } - - unless result + if !type_map.key?(oid) load_additional_types(type_map, [oid]) - result = type_map.fetch(oid, fmod, sql_type) { - warn "unknown OID #{oid}: failed to recognize type of '#{column_name}'. It will be treated as String." - Type::Value.new.tap do |cast_type| - type_map.register_type(oid, cast_type) - end - } end - result + type_map.fetch(oid, fmod, sql_type) { + warn "unknown OID #{oid}: failed to recognize type of '#{column_name}'. It will be treated as String." + Type::Value.new.tap do |cast_type| + type_map.register_type(oid, cast_type) + end + } end def initialize_type_map(m) # :nodoc: 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 2a146d38a9..bf92680268 100644 --- a/activerecord/lib/active_record/type/hash_lookup_type_map.rb +++ b/activerecord/lib/active_record/type/hash_lookup_type_map.rb @@ -1,12 +1,6 @@ module ActiveRecord module Type class HashLookupTypeMap < TypeMap # :nodoc: - - def initialize - @cache = {} - super - end - delegate :key?, to: :@mapping def lookup(type, *args) @@ -14,24 +8,12 @@ module ActiveRecord end def fetch(type, *args, &block) - cache = (@cache[type] ||= {}) - resolved = cache[args] - - unless resolved - resolved = cache[args] = @mapping.fetch(type, block).call(type, *args) - end - - resolved + @mapping.fetch(type, block).call(type, *args) end def alias_type(type, alias_type) register_type(type) { |_, *args| lookup(alias_type, *args) } end - - def register_type(key, value=nil, &block) - @cache = {} - super(key, value, &block) - end end end end -- cgit v1.2.3 From 7d54cccb8474e92454f33c9df975d20a80119fb9 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Wed, 19 Nov 2014 11:29:05 -0800 Subject: =?UTF-8?q?That=20last=20test=20was=20incorrect...=20=E2=98=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- activerecord/test/cases/type/type_map_test.rb | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/activerecord/test/cases/type/type_map_test.rb b/activerecord/test/cases/type/type_map_test.rb index 81ac7394a8..4e32f92dd0 100644 --- a/activerecord/test/cases/type/type_map_test.rb +++ b/activerecord/test/cases/type/type_map_test.rb @@ -124,16 +124,6 @@ module ActiveRecord assert_equal mapping.lookup(3), 'string' assert_kind_of Type::Value, mapping.lookup(4) end - - def test_aliases_are_not_improperly_cached - mapping = HashLookupTypeMap.new - - mapping.register_type("foo") { |*args| args.join("-") } - mapping.alias_type("bar", "foo") - - assert_equal "bar-1-2-3", mapping.lookup("bar", 1, 2, 3) - assert_equal "foo-1-2-3", mapping.lookup("foo", 1, 2, 3) - end end end end -- cgit v1.2.3 From 6d8f677ad946d4a5240278f8b4da506988cfcebf Mon Sep 17 00:00:00 2001 From: Steven Nunez Date: Wed, 19 Nov 2014 14:31:28 -0500 Subject: Remove bullet point to unwritten/unreferenced section --- guides/source/action_view_overview.md | 1 - 1 file changed, 1 deletion(-) 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. -------------------------------------------------------------------------------- -- cgit v1.2.3 From cafed35b610d830049b7dffd924cbcdeedab72bb Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Wed, 19 Nov 2014 11:54:19 -0800 Subject: Add tests for `TypeMap#fetch` and push up to `TypeMap` It doesn't make sense for the subclass to implement this method, and not have it on the parent. We can also DRY up the implementation of `#lookup` to be defined in terms of fetch, which will give us a single point of entry --- .../lib/active_record/type/hash_lookup_type_map.rb | 4 ---- activerecord/lib/active_record/type/type_map.rb | 6 +++++- activerecord/test/cases/type/type_map_test.rb | 15 +++++++++++++++ 3 files changed, 20 insertions(+), 5 deletions(-) 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..90a8c674cb 100644 --- a/activerecord/lib/active_record/type/hash_lookup_type_map.rb +++ b/activerecord/lib/active_record/type/hash_lookup_type_map.rb @@ -3,10 +3,6 @@ module ActiveRecord class HashLookupTypeMap < TypeMap # :nodoc: delegate :key?, to: :@mapping - def lookup(type, *args) - @mapping.fetch(type, proc { default_value }).call(type, *args) - end - def fetch(type, *args, &block) @mapping.fetch(type, block).call(type, *args) end diff --git a/activerecord/lib/active_record/type/type_map.rb b/activerecord/lib/active_record/type/type_map.rb index 88c5f9c497..13d4943861 100644 --- a/activerecord/lib/active_record/type/type_map.rb +++ b/activerecord/lib/active_record/type/type_map.rb @@ -6,6 +6,10 @@ module ActiveRecord end def lookup(lookup_key, *args) + fetch(lookup_key, *args) { default_value } + end + + def fetch(lookup_key, *args) matching_pair = @mapping.reverse_each.detect do |key, _| key === lookup_key end @@ -13,7 +17,7 @@ module ActiveRecord if matching_pair matching_pair.last.call(lookup_key, *args) else - default_value + yield lookup_key, *args end end diff --git a/activerecord/test/cases/type/type_map_test.rb b/activerecord/test/cases/type/type_map_test.rb index 4e32f92dd0..1e4eba1961 100644 --- a/activerecord/test/cases/type/type_map_test.rb +++ b/activerecord/test/cases/type/type_map_test.rb @@ -124,6 +124,21 @@ 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 end end end -- cgit v1.2.3 From f767ac22fa213df754e160c59189d28ed4f95568 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Wed, 19 Nov 2014 12:04:51 -0800 Subject: Reintroduce cache with tests --- .../lib/active_record/type/hash_lookup_type_map.rb | 10 ++++--- activerecord/lib/active_record/type/type_map.rb | 28 ++++++++++++------- activerecord/test/cases/type/type_map_test.rb | 32 ++++++++++++++++++++++ 3 files changed, 56 insertions(+), 14 deletions(-) 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 90a8c674cb..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,13 +3,15 @@ module ActiveRecord class HashLookupTypeMap < TypeMap # :nodoc: delegate :key?, to: :@mapping - def fetch(type, *args, &block) - @mapping.fetch(type, block).call(type, *args) - end - def alias_type(type, alias_type) register_type(type) { |_, *args| lookup(alias_type, *args) } end + + private + + def perform_fetch(type, *args, &block) + @mapping.fetch(type, block).call(type, *args) + end end end end diff --git a/activerecord/lib/active_record/type/type_map.rb b/activerecord/lib/active_record/type/type_map.rb index 13d4943861..7c194c0cdf 100644 --- a/activerecord/lib/active_record/type/type_map.rb +++ b/activerecord/lib/active_record/type/type_map.rb @@ -3,26 +3,22 @@ module ActiveRecord class TypeMap # :nodoc: def initialize @mapping = {} + @cache = Hash.new do |h, key| + h[key] = {} + end end def lookup(lookup_key, *args) fetch(lookup_key, *args) { default_value } end - def 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 + def fetch(lookup_key, *args, &block) + @cache[lookup_key][args] ||= perform_fetch(lookup_key, *args, &block) end def register_type(key, value = nil, &block) raise ::ArgumentError unless value || block + @cache.clear if block @mapping[key] = block @@ -44,6 +40,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/test/cases/type/type_map_test.rb b/activerecord/test/cases/type/type_map_test.rb index 1e4eba1961..172c6dfc4c 100644 --- a/activerecord/test/cases/type/type_map_test.rb +++ b/activerecord/test/cases/type/type_map_test.rb @@ -139,6 +139,38 @@ module ActiveRecord 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 -- cgit v1.2.3 From 70c2bf9d21386731135b69125ef00c8810a22a1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Wed, 19 Nov 2014 18:30:06 -0200 Subject: Fix shell quote on the release task --- tasks/release.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 -- cgit v1.2.3 From 7839e27b4e467b5cf94e83555b9b6f0a4f6aaf8a Mon Sep 17 00:00:00 2001 From: Akira Matsuda Date: Thu, 20 Nov 2014 06:57:22 +0900 Subject: Some valid block calls in templates caused syntax errors Now ActionView accepts <%= foo(){ %> and <%= foo()do %> :golf: --- actionview/CHANGELOG.md | 5 +++++ actionview/lib/action_view/template/handlers/erb.rb | 2 +- actionview/test/fixtures/test/_label_with_block.erb | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md index e388e6ecd3..d7875def51 100644 --- a/actionview/CHANGELOG.md +++ b/actionview/CHANGELOG.md @@ -1,3 +1,8 @@ +* 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. 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/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 %> -- cgit v1.2.3 From a668b09ee387bf241a3481a764a18a5c8a4df8cd Mon Sep 17 00:00:00 2001 From: Sam Date: Wed, 19 Nov 2014 08:44:45 +1100 Subject: PERF: avoid string allocations --- activerecord/lib/active_record/relation/query_methods.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index cb4e33f1b1..eb69943551 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -1059,8 +1059,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]) -- cgit v1.2.3 From 9ce105734d0b28de324c79a9e89906219f1555b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20van=20den=20Berg?= Date: Thu, 20 Nov 2014 09:58:45 +0100 Subject: Explain that default_scope also influences update_all This was not explicitly stated before and I needed to try it out to be certain. A little explicit statement in the API docs might help here. --- activerecord/lib/active_record/relation.rb | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 460daf99bc..fc3306ee81 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -304,11 +304,12 @@ 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. 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. + # Updates all records in the current scope (respecting the default_scope, where, + # limit and order specified) with details given. This method constructs a single SQL update_all + # 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 # @@ -319,6 +320,12 @@ module ActiveRecord # # Update all customers with the given attributes # Customer.update_all wants_email: true # + # # Update all active accounts with the given attributes + # class Account < ActiveRecord::Base + # default_scope -> { where active: true } + # end + # Account.update_all(failed_logins: 0) + # # # Update all books with 'Rails' in their title # Book.where('title LIKE ?', '%Rails%').update_all(author: 'David') # -- cgit v1.2.3 From d56be864f61cc00eeff27ed42e7cec4194c5347f Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Thu, 20 Nov 2014 15:30:46 +0100 Subject: synchronize code and docs for `timestamps` and `add_timestamps`. This makes the following changes: * warn if `:null` is not passed to `add_timestamps` * `timestamps` method docs link to `add_timestamps` docs * explain where additional options go * adjust examples to include `null: false` (to prevent deprecation warnings) --- .../connection_adapters/abstract/schema_definitions.rb | 11 +++++------ .../connection_adapters/abstract/schema_statements.rb | 7 +++++-- .../lib/active_record/connection_adapters/abstract_adapter.rb | 1 + activerecord/test/cases/adapters/mysql/active_schema_test.rb | 2 +- activerecord/test/cases/adapters/mysql2/active_schema_test.rb | 2 +- activerecord/test/cases/ar_schema_test.rb | 9 +++++++++ 6 files changed, 22 insertions(+), 10 deletions(-) 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 5c4c214385..d2236d046b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -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 @@ -287,7 +287,9 @@ module ActiveRecord end # Appends :datetime columns :created_at and - # :updated_at to the table. + # :updated_at to the table. See SchemaStatements#add_timestamps + # + # t.timestamps null: false def timestamps(*args) options = args.extract_options! emit_warning_if_null_unspecified(options) @@ -412,8 +414,6 @@ module ActiveRecord # end # class Table - include TimestampDefaultDeprecation - attr_reader :name def initialize(table_name, base) @@ -462,9 +462,8 @@ module ActiveRecord # 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(name, options) 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 cc86c3776e..7cc5e666af 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -835,11 +835,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 null: false) 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 57aa2f9c58..fa3483a258 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -24,6 +24,7 @@ module ActiveRecord autoload :TableDefinition autoload :Table autoload :AlterTable + autoload :TimestampDefaultDeprecation end autoload_at 'active_record/connection_adapters/abstract/connection_pool' do 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/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/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 -- cgit v1.2.3 From 5758f26ba244d8b46cdbef3e64a35a89eebf56bc Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Thu, 20 Nov 2014 23:29:48 +0800 Subject: [CI SKIP] Improvements to Active Job guide. --- guides/source/active_job_basics.md | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md index 0e9e4eff1d..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 @@ -56,9 +56,6 @@ You can also create a job that will run on a specific queue: $ bin/rails generate job guests_cleanup --queue urgent ``` -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`. @@ -107,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 -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 ``` @@ -149,7 +151,7 @@ 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 ``` -- cgit v1.2.3 From bc43d7f57d99a6f691761aceb3f399ba3ac7bace Mon Sep 17 00:00:00 2001 From: Ilya Katz Date: Thu, 20 Nov 2014 15:14:53 -0500 Subject: Use request method instead of ActionDispatch::Request#request_method instead of ActionDispatch::Request#method to pick up overrides by the middleware --- actionpack/lib/action_controller/metal/instrumentation.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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") } -- cgit v1.2.3 From 753600b240ba6cfebaac1662f4e216bf6c399023 Mon Sep 17 00:00:00 2001 From: claudiob Date: Thu, 20 Nov 2014 10:48:29 -0800 Subject: Document *all* the options accepted by form_for The [current documentation of form_for](http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for) is incomplete: > The rightmost argument to form_for is an optional hash of options - > :url - The URL the form is to be submitted to. This may be represented in the same way as values passed to url_for or link_to. So for example you may use a named route directly. When the model is represented by a string or symbol, as in the example above, if the :url option is not specified, by default the form will be sent back to the current url (We will describe below an alternative resource-oriented usage of form_for in which the URL does not need to be specified explicitly). > :namespace - 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. > :html - Optional HTML attributes for the form tag. This commit completes the documentation by specifying that: * `:authenticity_token` is also a valid option (as [documented here](https://github.com/rails/rails/blob/b0f44c9ff0be84ebc42760029adeeb9dd954655f/actionview/lib/action_view/helpers/form_helper.rb#L396)) * `:method` is also a valid option (as [tested here](https://github.com/rails/rails/blob/b0f44c9ff0be84ebc42760029adeeb9dd954655f/actionview/test/template/form_helper_test.rb#L1819)) * `:remote` is also a valid option (as [tested here](https://github.com/rails/rails/blob/b0f44c9ff0be84ebc42760029adeeb9dd954655f/actionview/test/template/form_helper_test.rb#L1850)) [ci skip] --- actionview/lib/action_view/helpers/form_helper.rb | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/actionview/lib/action_view/helpers/form_helper.rb b/actionview/lib/action_view/helpers/form_helper.rb index 03f80ff360..ef413448e1 100644 --- a/actionview/lib/action_view/helpers/form_helper.rb +++ b/actionview/lib/action_view/helpers/form_helper.rb @@ -164,6 +164,21 @@ module ActionView # * :namespace - 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. + # * :method - 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 _method is added to + # simulate the verb over post. + # * :authenticity_token - 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 false). + # Remote forms may omit the embedded authenticity token by setting + # config.action_view.embed_authenticity_token_in_remote_forms = false. + # This is helpful when you're fragment-caching the form. Remote forms + # get the authenticity token from the meta tag, so embedding is + # unnecessary unless you support browsers without JavaScript. + # * :remote - If set to true, will allow the Unobtrusive + # JavaScript drivers to control the submit behavior. By default this + # behavior is an ajax submit. # * :html - Optional HTML attributes for the form tag. # # Also note that +form_for+ doesn't create an exclusive scope. It's still -- cgit v1.2.3 From b0cc858dd71576011c6f2a3995457c070d8b55d5 Mon Sep 17 00:00:00 2001 From: claudiob Date: Fri, 26 Sep 2014 20:11:39 -0700 Subject: Add `:enforce_utf8` option to form_for Since 06388b0 `form_tag` accepts the option `enforce_utf8` which, when set to false, prevents the hidden "UTF8 enforcer" field from appearing in the output. This commit implements the same behavior for `form_for`. Stems from https://github.com/rails/rails/pull/17685#issuecomment-63871395 --- actionview/CHANGELOG.md | 7 +++++ actionview/lib/action_view/helpers/form_helper.rb | 3 ++ actionview/test/template/form_helper_test.rb | 36 +++++++++++++++++++++-- 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md index d7875def51..6b7adbe4a3 100644 --- a/actionview/CHANGELOG.md +++ b/actionview/CHANGELOG.md @@ -1,3 +1,10 @@ +* 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. diff --git a/actionview/lib/action_view/helpers/form_helper.rb b/actionview/lib/action_view/helpers/form_helper.rb index 03f80ff360..2119ea938f 100644 --- a/actionview/lib/action_view/helpers/form_helper.rb +++ b/actionview/lib/action_view/helpers/form_helper.rb @@ -164,6 +164,8 @@ module ActionView # * :namespace - 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. + # * :enforce_utf8 - If set to false, a hidden input with name + # utf8 is not output. # * :html - Optional HTML attributes for the form tag. # # Also note that +form_for+ doesn't create an exclusive scope. It's still @@ -420,6 +422,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) diff --git a/actionview/test/template/form_helper_test.rb b/actionview/test/template/form_helper_test.rb index 4bbbdf4fb1..a131752b2a 100644 --- a/actionview/test/template/form_helper_test.rb +++ b/actionview/test/template/form_helper_test.rb @@ -1864,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 + "" + 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 + "" + 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) @@ -3313,8 +3337,14 @@ class FormHelperTest < ActionView::TestCase protected - def hidden_fields(method = nil) - txt = %{} + def hidden_fields(options = {}) + method = options[:method] + + if options.fetch(:enforce_utf8, true) + txt = %{} + else + txt = '' + end if method && !%w(get post).include?(method.to_s) txt << %{} @@ -3338,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_text(action, id, html_class, remote, multipart, method) + hidden_fields(options.slice :method, :enforce_utf8) + contents + "" end def protect_against_forgery? -- cgit v1.2.3 From f78006d6563ce4128a04be2fea5122f367957833 Mon Sep 17 00:00:00 2001 From: Nick Veys Date: Thu, 20 Nov 2014 14:50:24 -0600 Subject: Fixing documentation in JSON#from_json Commit d67b289 introduced a tiny regression in the docs for #from_json, true needs to be included when the root node is present. --- activemodel/lib/active_model/serializers/json.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/activemodel/lib/active_model/serializers/json.rb b/activemodel/lib/active_model/serializers/json.rb index 77f2a64b11..b66dbf1afe 100644 --- a/activemodel/lib/active_model/serializers/json.rb +++ b/activemodel/lib/active_model/serializers/json.rb @@ -130,10 +130,10 @@ module ActiveModel # # json = { person: { name: 'bob', age: 22, awesome:true } }.to_json # person = Person.new - # person.from_json(json) # => # - # person.name # => "bob" - # person.age # => 22 - # person.awesome # => true + # person.from_json(json, true) # => # + # person.name # => "bob" + # person.age # => 22 + # person.awesome # => true def from_json(json, include_root=include_root_in_json) hash = ActiveSupport::JSON.decode(json) hash = hash.values.first if include_root -- cgit v1.2.3 From 900f633acae7136fb80105c13e9cce1be93627d9 Mon Sep 17 00:00:00 2001 From: Roberto Miranda Date: Thu, 20 Nov 2014 15:59:01 -0500 Subject: _will_change! method is not needed any more [ci skip] ref #15674 --- guides/source/active_record_postgresql.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md index 6c94218ef6..36345e3137 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 -- cgit v1.2.3 From 02e821f329bec116ca367886233d16feae6723ef Mon Sep 17 00:00:00 2001 From: claudiob Date: Thu, 20 Nov 2014 14:44:56 -0800 Subject: Wrap code snippets in +, not backticks, in sdoc [ci skip] --- actionpack/lib/action_dispatch/routing/mapper.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index ac03ecb2c8..be54d43172 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -391,7 +391,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: @@ -402,7 +402,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: # @@ -457,7 +457,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 # params[<:param>]. -- cgit v1.2.3 From 5aedabe82d3a9d7df19007aa0fd7719d4a55ef7e Mon Sep 17 00:00:00 2001 From: claudiob Date: Thu, 20 Nov 2014 14:54:22 -0800 Subject: Wrap code snippets in +, not backticks, in sdoc I grepped the source code for code snippets wrapped in backticks in the comments and replaced the backticks with plus signs so they are correctly displayed in the Rails documentation. [ci skip] --- actionpack/lib/action_controller/metal/etag_with_template_digest.rb | 4 ++-- actionpack/lib/action_controller/metal/http_authentication.rb | 6 +++--- actionview/lib/action_view/template/handlers.rb | 2 +- .../lib/active_record/associations/collection_association.rb | 4 ++-- .../active_record/connection_adapters/connection_specification.rb | 2 +- activerecord/lib/active_record/connection_adapters/mysql_adapter.rb | 2 +- .../lib/active_record/connection_adapters/postgresql_adapter.rb | 4 ++-- 7 files changed, 12 insertions(+), 12 deletions(-) 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/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb index 25c123edf7..2717a41d36 100644 --- a/actionpack/lib/action_controller/metal/http_authentication.rb +++ b/actionpack/lib/action_controller/metal/http_authentication.rb @@ -462,14 +462,14 @@ module ActionController raw_params.map { |param| param.split %r/=(.+)?/ } end - # This removes the `"` characters wrapping the value. + # This removes the " 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 :, ;, or \t + # delimiters defined in +AUTHN_PAIR_DELIMITERS+. def raw_params(auth) auth.sub(TOKEN_REGEX, '').split(/\s*#{AUTHN_PAIR_DELIMITERS}\s*/) end 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/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 93f611dd8d..d59cebb08b 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -175,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. diff --git a/activerecord/lib/active_record/connection_adapters/connection_specification.rb b/activerecord/lib/active_record/connection_adapters/connection_specification.rb index 609ec7dabd..e54e3199ff 100644 --- a/activerecord/lib/active_record/connection_adapters/connection_specification.rb +++ b/activerecord/lib/active_record/connection_adapters/connection_specification.rb @@ -234,7 +234,7 @@ module ActiveRecord 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/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 3357ed52e5..8b7459ef27 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 # * :encoding - (Optional) Sets the client encoding by executing "SET NAMES " after connection. # * :reconnect - Defaults to false (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html). # * :strict - Defaults to true. Enable STRICT_ALL_TABLES. (See MySQL documentation: http://dev.mysql.com/doc/refman/5.0/en/server-sql-mode.html) - # * :variables - (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). + # * :variables - (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). # * :sslca - Necessary to use MySQL with an SSL connection. # * :sslkey - Necessary to use MySQL with an SSL connection. # * :sslcert - Necessary to use MySQL with an SSL connection. diff --git a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb index 6310d70192..3698957d8d 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb @@ -125,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 @@ -134,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 -- cgit v1.2.3 From 3e92806357543cdbabad813884a591fca69193c2 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Thu, 20 Nov 2014 17:37:54 -0800 Subject: raise a better exception for renaming long indexes --- .../connection_adapters/abstract/schema_statements.rb | 3 +++ .../connection_adapters/postgresql/schema_statements.rb | 3 +++ activerecord/test/cases/migration/index_test.rb | 14 ++++++++++++++ 3 files changed, 20 insertions(+) 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 7cc5e666af..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 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 51853c6812..b4b066c06e 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -478,6 +478,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/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) { -- cgit v1.2.3 From 17efb3b919e8eff1ca5da49b12e3c1f607eb93e3 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Thu, 20 Nov 2014 19:17:10 -0700 Subject: Remove is_a? check when ignoring tables Technically changes the API, as it will allow any object which responds to `===`. Personally, I think this is more flexible. --- activerecord/lib/active_record/schema_dumper.rb | 7 +------ activerecord/test/cases/schema_dumper_test.rb | 10 ---------- 2 files changed, 1 insertion(+), 16 deletions(-) diff --git a/activerecord/lib/active_record/schema_dumper.rb b/activerecord/lib/active_record/schema_dumper.rb index 261fb9d992..1dd2cadc01 100644 --- a/activerecord/lib/active_record/schema_dumper.rb +++ b/activerecord/lib/active_record/schema_dumper.rb @@ -244,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/test/cases/schema_dumper_test.rb b/activerecord/test/cases/schema_dumper_test.rb index 6303393c22..8731531f54 100644 --- a/activerecord/test/cases/schema_dumper_test.rb +++ b/activerecord/test/cases/schema_dumper_test.rb @@ -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) -- cgit v1.2.3 From f245fe856d424cfce623f45d346f5618e1ed0840 Mon Sep 17 00:00:00 2001 From: Shunsuke Aida Date: Fri, 21 Nov 2014 09:50:46 +0900 Subject: if you want to ignore all the logfiles, no need for extensions --- railties/lib/rails/generators/rails/app/templates/gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore index 8775e5e235..ee61b7c5a8 100644 --- a/railties/lib/rails/generators/rails/app/templates/gitignore +++ b/railties/lib/rails/generators/rails/app/templates/gitignore @@ -14,5 +14,5 @@ <% end -%> # Ignore all logfiles and tempfiles. -/log/*.log +/log /tmp -- cgit v1.2.3 From 8ffc8da71360f0defcc4ac44d25c1732b3f73820 Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Fri, 21 Nov 2014 09:25:22 +0100 Subject: ignore all logfiles but keep the log directory. #17700 [ci skip] We generate a `.keep` file inside the log directory to make sure the directory itself is under version control. let's keep it that way. /cc @matthewd --- railties/lib/rails/generators/rails/app/templates/gitignore | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/railties/lib/rails/generators/rails/app/templates/gitignore b/railties/lib/rails/generators/rails/app/templates/gitignore index ee61b7c5a8..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/.keep /tmp -- cgit v1.2.3 From e0e9d5bd8600c01de6b73487bf66046d179c0ed7 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Fri, 21 Nov 2014 17:44:24 +0800 Subject: Fix select_tag generating tag when set to false. Fixes https://github.com/rails/rails/issues/17701. --- actionview/lib/action_view/helpers/form_tag_helper.rb | 4 +++- actionview/test/template/form_tag_helper_test.rb | 6 ++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/actionview/lib/action_view/helpers/form_tag_helper.rb b/actionview/lib/action_view/helpers/form_tag_helper.rb index c0218fd55d..93c04fbec6 100644 --- a/actionview/lib/action_view/helpers/form_tag_helper.rb +++ b/actionview/lib/action_view/helpers/form_tag_helper.rb @@ -140,7 +140,9 @@ module ActionView include_blank = '' end - option_tags = content_tag(:option, include_blank, value: '').safe_concat(option_tags) + if include_blank + option_tags = content_tag(:option, include_blank, value: '').safe_concat(option_tags) + end end if prompt = options.delete(:prompt) diff --git a/actionview/test/template/form_tag_helper_test.rb b/actionview/test/template/form_tag_helper_test.rb index f8fd642809..84a581b107 100644 --- a/actionview/test/template/form_tag_helper_test.rb +++ b/actionview/test/template/form_tag_helper_test.rb @@ -232,6 +232,12 @@ class FormTagHelperTest < ActionView::TestCase assert_dom_equal expected, actual end + def test_select_tag_with_include_blank_false + actual = select_tag "places", "".html_safe, include_blank: false + expected = %() + assert_dom_equal expected, actual + end + def test_select_tag_with_include_blank_string actual = select_tag "places", "".html_safe, include_blank: 'Choose' expected = %() -- cgit v1.2.3 From e389720ddd392b8ed90db190e4f514444b66da76 Mon Sep 17 00:00:00 2001 From: Francis Go Date: Fri, 21 Nov 2014 23:36:05 +1100 Subject: Update grammar in Getting Started Guide [ci skip] --- guides/source/getting_started.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 1996158e27..87cb6d8b0b 100644 --- a/guides/source/getting_started.md +++ b/guides/source/getting_started.md @@ -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. -- cgit v1.2.3 From f766abd4cf3eb75469d3646cfb6d85e668c619f3 Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Fri, 21 Nov 2014 14:57:25 +0100 Subject: make it possible to access fixtures excluded by a `default_scope`. Prior to this patch you'd end up with an error like: ``` ActiveRecord::RecordNotFound: Couldn't find with 'id'= [WHERE ()] ``` --- activerecord/CHANGELOG.md | 4 ++++ activerecord/lib/active_record/fixtures.rb | 2 +- activerecord/test/cases/fixtures_test.rb | 14 ++++++++++++++ activerecord/test/fixtures/bulbs.yml | 5 +++++ 4 files changed, 24 insertions(+), 1 deletion(-) create mode 100644 activerecord/test/fixtures/bulbs.yml diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index e4c59673cd..fcc6523d6e 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,7 @@ +* Make it possible to access fixtures excluded by a `default_scope`. + + *Yves Senn* + * Add `Table#name` to match `TableDefinition#name`. *Cody Cutrer* diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index db6421dacb..660ba18a98 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -806,7 +806,7 @@ module ActiveRecord def find if model_class - model_class.find(fixture[model_class.primary_key]) + model_class.unscoped.find(fixture[model_class.primary_key]) else raise FixtureClassNotFound, "No class attached to find." end diff --git a/activerecord/test/cases/fixtures_test.rb b/activerecord/test/cases/fixtures_test.rb index 4b0ebe13d1..9edeb8b47f 100644 --- a/activerecord/test/cases/fixtures_test.rb +++ b/activerecord/test/cases/fixtures_test.rb @@ -5,6 +5,7 @@ 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' @@ -853,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/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 -- cgit v1.2.3 From 27908faf63bb96372254d5d407952d98254f81a8 Mon Sep 17 00:00:00 2001 From: Francis Go Date: Sat, 22 Nov 2014 02:37:56 +1100 Subject: Move 'the' outside of SQLite and Bundler link text [ci skip] --- guides/source/getting_started.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/guides/source/getting_started.md b/guides/source/getting_started.md index 1996158e27..e1554c9c93 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
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
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.| -- cgit v1.2.3 From 91e3dab804fffe0b1daebb438091418faa1fa256 Mon Sep 17 00:00:00 2001 From: "siddharth@vinsol.com" Date: Thu, 20 Nov 2014 01:35:04 +0530 Subject: Fix includes on association with a scope containing joins along with conditions on the joined assoiciation --- activerecord/CHANGELOG.md | 6 ++++++ .../lib/active_record/associations/preloader/association.rb | 10 ++-------- activerecord/lib/active_record/relation/query_methods.rb | 6 ++---- activerecord/test/cases/associations/eager_test.rb | 6 ++++++ activerecord/test/models/post.rb | 1 + 5 files changed, 17 insertions(+), 12 deletions(-) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index fcc6523d6e..a92571a04a 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -2,6 +2,12 @@ *Yves Senn* +* Fix includes on association with a scope containing joins along with conditions + on the joined assoiciation. + + *Siddharth Sharma* + + * Add `Table#name` to match `TableDefinition#name`. *Cody Cutrer* diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb index 496c426986..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! diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index eb69943551..6e384facce 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -427,14 +427,12 @@ 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 diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index 4539b99504..dd4f530791 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -904,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 } diff --git a/activerecord/test/models/post.rb b/activerecord/test/models/post.rb index 36cf221d45..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' -- cgit v1.2.3 From 38cfaa828502b2f5d137a6a2952c68ae5efc15b1 Mon Sep 17 00:00:00 2001 From: Andy Jeffries Date: Mon, 17 Nov 2014 10:44:04 +0000 Subject: Creates an ApplicationMailer and layout by default, including html and body tags to reduce spam score --- .../rails/generators/mailer/mailer_generator.rb | 1 + .../mailer/templates/application_mailer.rb | 4 ++++ .../rails/generators/mailer/templates/mailer.rb | 3 +-- .../generators/erb/mailer/mailer_generator.rb | 20 +++++++++++++++++ .../erb/mailer/templates/layout.html.erb | 5 +++++ .../erb/mailer/templates/layout.text.erb | 1 + railties/test/generators/mailer_generator_test.rb | 26 +++++++++++++++++----- .../test/generators/namespaced_generators_test.rb | 6 ++--- 8 files changed, 54 insertions(+), 12 deletions(-) create mode 100644 actionmailer/lib/rails/generators/mailer/templates/application_mailer.rb create mode 100644 railties/lib/rails/generators/erb/mailer/templates/layout.html.erb create mode 100644 railties/lib/rails/generators/erb/mailer/templates/layout.text.erb diff --git a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb index d5bf864595..97a01f9ef3 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", File.join('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/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb index 66b17bd10e..b047973241 100644 --- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb @@ -3,6 +3,26 @@ require 'rails/generators/erb/controller/controller_generator' module Erb # :nodoc: module Generators # :nodoc: class MailerGenerator < ControllerGenerator # :nodoc: + def copy_view_files + view_base_path = File.join("app/views", class_path, file_name) + empty_directory view_base_path + + layout_base_path = File.join("app/views/layouts") + + actions.each do |action| + @action = action + + formats.each do |format| + @view_path = File.join(view_base_path, filename_with_extensions(action, format)) + template filename_with_extensions(:view, format), @view_path + + @layout_path = File.join(layout_base_path, filename_with_extensions("mailer", format)) + template filename_with_extensions(:layout, format), @layout_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 @@ + + + <%%= yield %> + + 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/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb index 25649881eb..915dde1109 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 @@ -69,27 +79,31 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_invokes_default_text_template_engine run_generator assert_file "app/views/notifier/foo.text.erb" do |view| - assert_match(%r(\sapp/views/notifier/foo\.text\.erb), view) assert_match(/<%= @greeting %>/, view) end assert_file "app/views/notifier/bar.text.erb" do |view| - 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 run_generator assert_file "app/views/notifier/foo.html.erb" do |view| - assert_match(%r(\sapp/views/notifier/foo\.html\.erb), view) assert_match(/<%= @greeting %>/, view) end assert_file "app/views/notifier/bar.html.erb" do |view| - 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{\n \n <%= yield %>\n \n}, view) + end end def test_invokes_default_template_engine_even_with_no_action @@ -105,7 +119,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/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb index 7eeb084eab..20e8d2d5d3 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 @@ -174,12 +174,10 @@ class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase def test_invokes_default_template_engine run_generator assert_file "app/views/test_app/notifier/foo.text.erb" do |view| - assert_match(%r(app/views/test_app/notifier/foo\.text\.erb), view) assert_match(/<%= @greeting %>/, view) end assert_file "app/views/test_app/notifier/bar.text.erb" do |view| - assert_match(%r(app/views/test_app/notifier/bar\.text\.erb), view) assert_match(/<%= @greeting %>/, view) end end -- cgit v1.2.3 From 1000e4c51ad4ba6816b0a3356e6ecd6c911f5755 Mon Sep 17 00:00:00 2001 From: claudiob Date: Fri, 21 Nov 2014 12:33:44 -0800 Subject: Move test that depends on ActiveRecord This commit moves a test from `test/template` to `test/activerecord` since the test depends on ActiveRecord. This matches the documentation from [RUNNING_UNIT_TESTS](https://github.com/rails/rails/blob/f28d1ddd507174ac233b773cc4f35c3c05ad32e7/actionview/RUNNING_UNIT_TESTS.rdoc): > Test cases in the test/activerecord/ directory depend on having activerecord and sqlite3 installed. > If Active Record is not in actionview/../activerecord directory, or the sqlite3 rubygem is not installed, these tests are skipped. > Other tests are runnable from a fresh copy of actionview without any configuration. --- More details about this commit. All the tests starting with `require 'active_record_unit'` are already inside `test/activerecord`, except for the one test this commit moves. If you don't have `active_record` on your machine, the following command currently fails on master: ```bash ``` --- actionview/test/activerecord/debug_helper_test.rb | 8 ++++++++ actionview/test/template/debug_helper_test.rb | 8 -------- 2 files changed, 8 insertions(+), 8 deletions(-) create mode 100644 actionview/test/activerecord/debug_helper_test.rb delete mode 100644 actionview/test/template/debug_helper_test.rb diff --git a/actionview/test/activerecord/debug_helper_test.rb b/actionview/test/activerecord/debug_helper_test.rb new file mode 100644 index 0000000000..5609694cd5 --- /dev/null +++ b/actionview/test/activerecord/debug_helper_test.rb @@ -0,0 +1,8 @@ +require 'active_record_unit' + +class DebugHelperTest < ActionView::TestCase + def test_debug + company = Company.new(name: "firebase") + assert_match "name: firebase", debug(company) + end +end diff --git a/actionview/test/template/debug_helper_test.rb b/actionview/test/template/debug_helper_test.rb deleted file mode 100644 index 5609694cd5..0000000000 --- a/actionview/test/template/debug_helper_test.rb +++ /dev/null @@ -1,8 +0,0 @@ -require 'active_record_unit' - -class DebugHelperTest < ActionView::TestCase - def test_debug - company = Company.new(name: "firebase") - assert_match "name: firebase", debug(company) - end -end -- cgit v1.2.3 From 71bb8c34f539f8ffbb7e7968f50f797e08812133 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Fri, 21 Nov 2014 15:33:46 -0700 Subject: ConnectionAdapter#substitute_at is technically public API... We can't change the signature without a deprecation cycle. --- activerecord/lib/active_record/connection_adapters/abstract_adapter.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb index fa3483a258..e0a4af5359 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb @@ -265,7 +265,7 @@ module ActiveRecord # 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) + def substitute_at(column, _unused = 0) Arel::Nodes::BindParam.new end -- cgit v1.2.3 From 85774cfb1ab424a58c1af6759ad8a42df85089bc Mon Sep 17 00:00:00 2001 From: "yuuji.yaginuma" Date: Sat, 22 Nov 2014 16:13:33 +0900 Subject: [ci skip] correct example output and filename in pg guide --- guides/source/active_record_postgresql.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md index 36345e3137..a2681a80e9 100644 --- a/guides/source/active_record_postgresql.md +++ b/guides/source/active_record_postgresql.md @@ -214,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 @@ -276,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! -- cgit v1.2.3 From ee5dfe27277dab94e3b22507389057aaeb8c7160 Mon Sep 17 00:00:00 2001 From: Javier Vidal Date: Sat, 22 Nov 2014 16:46:43 +0100 Subject: Fixing wrong link in 'Ruby on Rails Security Guide' [ci skip] The URL http://www.h-online.com/security/Symantec-reports-first-active-attack-on-a-DSL-router--/news/102352 points to an article titled 'The H is closing down'. The good one is: http://www.h-online.com/security/news/item/Symantec-reports-first-active-attack-on-a-DSL-router-735883.html --- guides/source/security.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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.
 -- cgit v1.2.3 From b33ed44ad312c5274fe72b26172ac0116d9ffb28 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Sat, 22 Nov 2014 11:29:45 -0800 Subject: Remove outdated comments [ci skip] They were introduced in 23b6def; the serial stuff has been removed since a5d80f8 --- actionpack/lib/action_dispatch/testing/assertions/routing.rb | 6 ------ 1 file changed, 6 deletions(-) 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 -- cgit v1.2.3 From dcc143cd702bfbfef9cb92e1fde75171d088a5ac Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Sat, 22 Nov 2014 13:16:14 -0700 Subject: Rename the primary key index when renaming a table in pg Also checked to make sure this does not affect foreign key constraints. (It doesn't). Fixes #12856 Closes #14088 --- activerecord/CHANGELOG.md | 6 ++++ .../postgresql/schema_statements.rb | 3 ++ .../cases/adapters/postgresql/rename_table_test.rb | 34 ++++++++++++++++++++++ 3 files changed, 43 insertions(+) create mode 100644 activerecord/test/cases/adapters/postgresql/rename_table_test.rb diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index fcc6523d6e..16f776df58 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,9 @@ +* 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* 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 b4b066c06e..515ff2dd44 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -411,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) 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 -- cgit v1.2.3 From 6cd9e2bd29b26e1ea781fafce18614217b7adf7b Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Sat, 22 Nov 2014 15:36:50 -0700 Subject: Fix build failures For some reason changing `.find` to `.unscoped.find` in https://github.com/rails/rails/commit/f766abd4cf3eb75469d3646cfb6d85e668c619f3 caused `scoping` to leak in some tests when run in isolation (looks like a concurrency issue?). `relation_scoping_test.rb` is a case that failed. From what I can tell it should not be possible, but changing to the block form fixes it. There is a deeper issue that I can't seem to find. /cc @senny --- activerecord/lib/active_record/fixtures.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 660ba18a98..7c53ee0a9a 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -806,7 +806,9 @@ module ActiveRecord def find if model_class - model_class.unscoped.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 -- cgit v1.2.3 From 46041c520809714b3937e7c79c2f220018a4a111 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Sat, 22 Nov 2014 21:42:19 +0800 Subject: Anchor should not be appended when set to nil/false. Fixes https://github.com/rails/rails/issues/17714. --- actionpack/lib/action_dispatch/http/url.rb | 4 +++- actionpack/test/controller/routing_test.rb | 3 +++ actionpack/test/controller/url_for_test.rb | 14 ++++++++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) 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/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index c18914cc8e..aca9f03748 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 diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index c05cde87e4..f0eba17556 100644 --- a/actionpack/test/controller/url_for_test.rb +++ b/actionpack/test/controller/url_for_test.rb @@ -54,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')) -- cgit v1.2.3 From 5dc598814efa45a1019c262ee01e5cc2db864d26 Mon Sep 17 00:00:00 2001 From: Arthur Neves Date: Sat, 22 Nov 2014 20:29:29 -0500 Subject: Add changelog entry for .reflections API change `.reflections` public API changed to return a String instead of a Symbol as keys. see commit 1f31488499111fdfce79d8dc1cc8fb008f7cdb25 and 6259e4e2dcca9a79f22f96658c33efe81936bc0d [fixes #16928] [fixes #17610] --- activerecord/CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 16f776df58..a4de332d4c 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,9 @@ +* 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 -- cgit v1.2.3 From 31b3069615529eabc42cc5bee1cd76e52bd1560b Mon Sep 17 00:00:00 2001 From: Arthur Neves Date: Sat, 22 Nov 2014 20:33:00 -0500 Subject: Update reflections public API doc --- activerecord/lib/active_record/reflection.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb index f4a351b092..4219632596 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -63,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 -- cgit v1.2.3 From 13b0ac7b69773813ffc3da91e2fa4040763c87d6 Mon Sep 17 00:00:00 2001 From: yui-knk Date: Sun, 23 Nov 2014 11:04:17 +0900 Subject: Fix explanation for ActionDispatch::Callbacks. ActionDispatch::Callbacks dose not run the prepare callbacks, so change with comment on ActionDispatch::Callbacks. --- guides/source/rails_on_rack.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md index 8bc2678d8f..968906cb5f 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. +* Provide callbacks to be executed before and after the request dispatch. **`ActiveRecord::Migration::CheckPending`** -- cgit v1.2.3 From ddce3dd37d4076bab8f1e73be21851935e379254 Mon Sep 17 00:00:00 2001 From: Zachary Scott Date: Sat, 22 Nov 2014 19:11:51 -0800 Subject: [ci skip] Dispatching is a verb :bow: cc #17719 --- guides/source/rails_on_rack.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md index 968906cb5f..5c2386f469 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`** -* Provide callbacks to be executed before and after the request dispatch. +* Provides callbacks to be executed before and after dispatching the request. **`ActiveRecord::Migration::CheckPending`** -- cgit v1.2.3 From 1069641bbc48dce6b919fe4bfb3badc2b72b2546 Mon Sep 17 00:00:00 2001 From: yui-knk Date: Sun, 23 Nov 2014 13:20:28 +0900 Subject: [ci skip] Fix class name of middleware. --- guides/source/rails_on_rack.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/rails_on_rack.md b/guides/source/rails_on_rack.md index 5c2386f469..0dec0e139b 100644 --- a/guides/source/rails_on_rack.md +++ b/guides/source/rails_on_rack.md @@ -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. -- cgit v1.2.3 From 9cb831ff849b0e26ad4b06f24b55ef1b6d6866a4 Mon Sep 17 00:00:00 2001 From: yui-knk Date: Sun, 23 Nov 2014 13:22:36 +0900 Subject: [ci skip] Fix comment of ActionDispatch::Callbacks cc ddce3dd --- actionpack/lib/action_dispatch/middleware/callbacks.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 -- cgit v1.2.3 From 331482ab68a43e16cb4b219e58147ed3a2c75141 Mon Sep 17 00:00:00 2001 From: Matthew Cullum Date: Sat, 22 Nov 2014 20:48:10 -0800 Subject: Specified beta branch for web-console gem --- guides/source/upgrading_ruby_on_rails.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 6f5dea45b5..042ff76212 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -55,7 +55,7 @@ a [pull request](https://github.com/rails/rails/edit/master/guides/source/upgrad ### 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. +First, add `gem 'web-console', '~> 2.0.0.beta4'` 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: -- cgit v1.2.3 From 77a276411e717353bc562c04d62e144f4410e706 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Sun, 23 Nov 2014 00:07:30 -0800 Subject: Test using `ActionController::TestCase` with engines Reference #17453 [Godfrey Chan, Washington Luiz] --- actionpack/test/controller/test_case_test.rb | 52 ++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb index 475af90032..fdabad3abd 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 @@ -753,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' } + + 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") -- cgit v1.2.3 From b7b9e92093ed128c2b27a64c5732f6a98191cbf0 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Sun, 23 Nov 2014 00:15:47 -0800 Subject: Correct example in the engines testing guide [ci skip] Reference #17453 --- guides/source/engines.md | 39 +++++++++++++++++++++++++-------------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/guides/source/engines.md b/guides/source/engines.md index 21ac941ac0..de33f5f067 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 ------------------------------ -- cgit v1.2.3 From 938d130c62b530d3445c9f06933cb113ff477fed Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Sun, 23 Nov 2014 01:08:53 -0800 Subject: Fix cases where the wrong name is passed to `Formatter#generate` These are currently working "by accident" because `match_route` does not check that the name is valid. --- actionpack/test/controller/routing_test.rb | 2 +- actionpack/test/journey/router_test.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index aca9f03748..f46b32e019 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -1386,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/journey/router_test.rb b/actionpack/test/journey/router_test.rb index fbac86e8ca..19c61b5914 100644 --- a/actionpack/test/journey/router_test.rb +++ b/actionpack/test/journey/router_test.rb @@ -415,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", -- cgit v1.2.3 From c23bb156fe29481c3c900e9a4bd3c1f84e71c6d0 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Sun, 23 Nov 2014 01:18:33 -0800 Subject: Deprecate passing an invalid name to `Formatter#generate` The internal tests that (incorrectly) relied on this were already fixed in 938d130. However, we cannot simply fix this bug because the guides prior to b7b9e92 recommended a workaround that relies on this buggy behavior. Reference #17453 --- actionpack/lib/action_dispatch/journey/formatter.rb | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/actionpack/lib/action_dispatch/journey/formatter.rb b/actionpack/lib/action_dispatch/journey/formatter.rb index 992c1a9efe..62bd4a33f2 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 @@ -80,6 +81,15 @@ module ActionDispatch if named_routes.key?(name) yield named_routes[name] else + if name + 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 + end + routes = non_recursive(cache, options) hash = routes.group_by { |_, r| r.score(options) } -- cgit v1.2.3 From 8e73abbda8d3a55459bac728530606fdf69468f5 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Sun, 23 Nov 2014 01:39:17 -0800 Subject: Deprecate `use_route` in controller tests Reference #17453 --- actionpack/lib/action_controller/test_case.rb | 23 ++++++++++++++++++++++- actionpack/test/controller/test_case_test.rb | 4 ++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index 30eae41f60..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' @@ -710,7 +711,27 @@ module ActionController :relative_url_root => nil, :_recall => @request.path_parameters) - route_name = options.delete :use_route + 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 diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb index fdabad3abd..ba2ff7d12c 100644 --- a/actionpack/test/controller/test_case_test.rb +++ b/actionpack/test/controller/test_case_test.rb @@ -528,7 +528,7 @@ XML get 'via_named_route', as: :a_named_route, to: 'test_case_test/test#test_uri' end - get :test_uri, use_route: :a_named_route + assert_deprecated { get :test_uri, use_route: :a_named_route } assert_equal '/via_named_route', @response.body end end @@ -798,7 +798,7 @@ module EngineControllerTests with_routing do |set| set.draw { mount Engine => '/foo' } - get :index, use_route: :foo + assert_deprecated { get :index, use_route: :foo } assert_equal @response.body, 'bar' end end -- cgit v1.2.3 From 23b21f6182e36c05c6b2a240c0fb824ae828465e Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Sun, 23 Nov 2014 01:46:51 -0800 Subject: Don't show the warning if we're already raising the error anyway If the route set is empty, or if none of the routes matches with a score > 0, there is no point showing the deprecation message because we are already be raising the `ActionController::UrlGenerationError` mentioned in the warning. In this case it is the expected behavior and the user wouldn't have to take any actions. --- actionpack/lib/action_dispatch/journey/formatter.rb | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/actionpack/lib/action_dispatch/journey/formatter.rb b/actionpack/lib/action_dispatch/journey/formatter.rb index 62bd4a33f2..177f586c0e 100644 --- a/actionpack/lib/action_dispatch/journey/formatter.rb +++ b/actionpack/lib/action_dispatch/journey/formatter.rb @@ -81,14 +81,8 @@ module ActionDispatch if named_routes.key?(name) yield named_routes[name] else - if name - 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 - end + # Make sure we don't show the deprecation warning more than once + warned = false routes = non_recursive(cache, options) @@ -98,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 -- cgit v1.2.3 From 7fe3cf810f28c15ff7e74198bfa6d6f0843b6bfa Mon Sep 17 00:00:00 2001 From: Jonathan Cutrell Date: Sun, 23 Nov 2014 13:03:01 -0500 Subject: Adding simple docs for ActionDispatch::Flash::FlashHash#to_session_value --- actionpack/lib/action_dispatch/middleware/flash.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb index 7a91674c3c..8fee9c9e8c 100644 --- a/actionpack/lib/action_dispatch/middleware/flash.rb +++ b/actionpack/lib/action_dispatch/middleware/flash.rb @@ -91,7 +91,10 @@ module ActionDispatch flash.tap(&:sweep) end - + + # 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 return nil if empty? {'discard' => @discard.to_a, 'flashes' => @flashes} -- cgit v1.2.3 From 6dd0dc3e7217f8af7877c5831b3d8816d156f21e Mon Sep 17 00:00:00 2001 From: Jonathan Cutrell Date: Sun, 23 Nov 2014 13:39:53 -0500 Subject: adding nodoc to private methods --- actionpack/lib/action_dispatch/middleware/flash.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb index 8fee9c9e8c..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)) @@ -95,7 +95,7 @@ module ActionDispatch # 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 + def to_session_value #:nodoc: return nil if empty? {'discard' => @discard.to_a, 'flashes' => @flashes} end -- cgit v1.2.3 From be8d1a9b57175732f9dafe23f790da82d4b06135 Mon Sep 17 00:00:00 2001 From: Zachary Scott Date: Sun, 23 Nov 2014 12:06:57 -0800 Subject: Add a test for reflection keys as Strings, fixes #16928 See also PR: #17610 --- activerecord/test/cases/reflection_test.rb | 4 ++++ 1 file changed, 4 insertions(+) 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 -- cgit v1.2.3 From 1d85c707b633b6ed1623290fa9aff5d7fd74d05e Mon Sep 17 00:00:00 2001 From: Yuki Nishijima Date: Sun, 23 Nov 2014 13:04:31 -0800 Subject: Do not rescue Exception in ParamsParser Unlike ShowExceptions or PublicExceptions, ParamsParser shouldn't transform exceptions like Interrupt and NoMemoryError into ParserError. --- actionpack/lib/action_dispatch/middleware/params_parser.rb | 2 +- actionpack/test/controller/webservice_test.rb | 10 ++++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) 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/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 -- cgit v1.2.3 From 32be4ddda5c8f2ea31bdbd411499e65e1e07dc0c Mon Sep 17 00:00:00 2001 From: Zachary Scott Date: Sun, 23 Nov 2014 23:09:46 -0800 Subject: Clarify what is being serialized and when it will be deserialized [ci skip] --- guides/source/4_2_release_notes.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 8553cffa9d..6463477c18 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -49,8 +49,8 @@ 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 -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 -- cgit v1.2.3 From 6a93aa6194661fc0c930345ac6831de24104959a Mon Sep 17 00:00:00 2001 From: Zachary Scott Date: Sun, 23 Nov 2014 23:17:26 -0800 Subject: Grammar pass on Web Console release note [ci skip] --- guides/source/4_2_release_notes.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 6463477c18..60dbb93e55 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -103,9 +103,9 @@ 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. -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. -- cgit v1.2.3 From a58da25d90962a39ad916fc4de22a0a0c81ba034 Mon Sep 17 00:00:00 2001 From: Andy Jeffries Date: Mon, 24 Nov 2014 09:37:32 +0000 Subject: Removing unnecessary File.join calls --- actionmailer/lib/rails/generators/mailer/mailer_generator.rb | 2 +- railties/lib/rails/generators/erb/mailer/mailer_generator.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb index 97a01f9ef3..094ec85114 100644 --- a/actionmailer/lib/rails/generators/mailer/mailer_generator.rb +++ b/actionmailer/lib/rails/generators/mailer/mailer_generator.rb @@ -8,7 +8,7 @@ module Rails def create_mailer_file template "mailer.rb", File.join('app/mailers', class_path, "#{file_name}.rb") - template "application_mailer.rb", File.join('app/mailers/application_mailer.rb') + template "application_mailer.rb", 'app/mailers/application_mailer.rb' end hook_for :template_engine, :test_framework diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb index b047973241..1e290bb938 100644 --- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb @@ -7,7 +7,7 @@ module Erb # :nodoc: view_base_path = File.join("app/views", class_path, file_name) empty_directory view_base_path - layout_base_path = File.join("app/views/layouts") + layout_base_path = "app/views/layouts" actions.each do |action| @action = action -- cgit v1.2.3 From 47ca6664fb51823709cc8fbcfa5cea510da18879 Mon Sep 17 00:00:00 2001 From: yui-knk Date: Mon, 24 Nov 2014 19:48:51 +0900 Subject: Replace ActionDispatch::Head with Rack::Head. --- guides/source/configuring.md | 6 +++--- railties/lib/rails/configuration.rb | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/guides/source/configuring.md b/guides/source/configuring.md index 2957232186..7688962c01 100644 --- a/guides/source/configuring.md +++ b/guides/source/configuring.md @@ -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: 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 Magical::Unicorns 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: # -- cgit v1.2.3 From 77fbc5358616c131884df4e0b622241ebf2a129b Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Mon, 24 Nov 2014 12:14:47 +0100 Subject: cleanup, remove trailing whitespace [ci skip] --- activerecord/lib/active_record/migration.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 2024b225e4..4e00eb3d99 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. rake db:migrate STEP=2 will rollback # the latest two migrations. - # - # If any of the migrations throw an ActiveRecord::IrreversibleMigration exception, + # + # If any of the migrations throw an ActiveRecord::IrreversibleMigration exception, # that step will fail and you'll have some manual work to do. # # == Database support -- cgit v1.2.3 From 91c0c277698ab6ca4132a580f4212aa913492a8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20van=20den=20Berg?= Date: Mon, 24 Nov 2014 16:03:07 +0100 Subject: Reword documentation for update_all It now contains a carefully formulated reference to the "current relation" which might help clarify that the receiving will generate its own scope, escaping the need for explicitly referencing `default_scope` which is, after all, just another way of specifying a scope and nothing special. --- activerecord/lib/active_record/relation.rb | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index fc3306ee81..561ed222d1 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -304,8 +304,7 @@ module ActiveRecord klass.current_scope = previous end - # Updates all records in the current scope (respecting the default_scope, where, - # limit and order specified) with details given. This method constructs a single SQL update_all + # 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 @@ -320,12 +319,6 @@ module ActiveRecord # # Update all customers with the given attributes # Customer.update_all wants_email: true # - # # Update all active accounts with the given attributes - # class Account < ActiveRecord::Base - # default_scope -> { where active: true } - # end - # Account.update_all(failed_logins: 0) - # # # Update all books with 'Rails' in their title # Book.where('title LIKE ?', '%Rails%').update_all(author: 'David') # -- cgit v1.2.3 From 7b378403d334fdfccfae64261df9cd5865b805d8 Mon Sep 17 00:00:00 2001 From: Richard Littauer Date: Mon, 24 Nov 2014 09:42:58 -0500 Subject: Change 'of plugins' syntax Currently, the docs uses a syntax that is unclear and not general American English. I've switched it to be clearer wording. Not a big fix, but may be helpful. --- .../rails/app/templates/app/assets/javascripts/application.js.tt | 2 +- .../rails/app/templates/app/assets/stylesheets/application.css | 2 +- .../lib/rails/generators/rails/plugin/templates/rails/javascripts.js | 2 +- .../lib/rails/generators/rails/plugin/templates/rails/stylesheets.css | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) 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/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..c07accc219 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/javascripts 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 -- cgit v1.2.3 From 746c3741e7011580efa69ab3fd1d5eb55e4f3348 Mon Sep 17 00:00:00 2001 From: Richard Littauer Date: Mon, 24 Nov 2014 10:25:09 -0500 Subject: Fix wrong path in comments about stylesheets I put the wrong path in my last PR by accident. Fixed here. Related to #17742 --- .../lib/rails/generators/rails/plugin/templates/rails/stylesheets.css | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 c07accc219..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 any plugin's vendor/assets/javascripts directory 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 -- cgit v1.2.3 From 72e8442797b90d865811e39418ef9d49238b193a Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Mon, 24 Nov 2014 11:24:31 -0700 Subject: Ensure the type map's cache is thread safe Thanks to @thedarkone for pointing out that an instance of this object is used in a shared context. --- activerecord/lib/active_record/type/type_map.rb | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/activerecord/lib/active_record/type/type_map.rb b/activerecord/lib/active_record/type/type_map.rb index 7c194c0cdf..09f5ba6b74 100644 --- a/activerecord/lib/active_record/type/type_map.rb +++ b/activerecord/lib/active_record/type/type_map.rb @@ -1,10 +1,12 @@ +require 'thread_safe' + module ActiveRecord module Type class TypeMap # :nodoc: def initialize @mapping = {} - @cache = Hash.new do |h, key| - h[key] = {} + @cache = ThreadSafe::Cache.new do |h, key| + h.fetch_or_store(key, ThreadSafe::Cache.new) end end @@ -13,7 +15,9 @@ module ActiveRecord end def fetch(lookup_key, *args, &block) - @cache[lookup_key][args] ||= perform_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) -- cgit v1.2.3 From 96393c53f2de4afd4632a1f7c0e72c8d38e0cdbf Mon Sep 17 00:00:00 2001 From: Arthur Neves Date: Mon, 24 Nov 2014 13:42:30 -0500 Subject: Add `.reflections` change to release note [skip ci] [related #17718] --- guides/source/4_2_release_notes.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 60dbb93e55..1ee3bfe0a4 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -630,6 +630,9 @@ Please refer to the [Changelog][active-record] for detailed changes. ### Notable changes +* `ActiveRecord::Base#reflections` now returns a hash with `String` keys instead of `Symbol` keys. + ([Pull Request](https://github.com/rails/rails/pull/17718)) + * The PostgreSQL adapter now supports the `JSONB` datatype in PostgreSQL 9.4+. ([Pull Request](https://github.com/rails/rails/pull/16220)) -- cgit v1.2.3 From 83821e2c4a32b17b153fcbcb247dec6e32f47284 Mon Sep 17 00:00:00 2001 From: claudiob Date: Mon, 24 Nov 2014 10:27:58 -0800 Subject: Mark comments that should not be in the docs Some comments that are meant to separate blocks of code in a file show up on http://api.rubyonrails.org as though they were part of the documentation. This commit hides those comments from the documentation. Stems from the discussion with @zzak at https://github.com/voloko/sdoc/issues/79#issuecomment-64158738 [ci skip] --- .../lib/active_record/connection_adapters/abstract_mysql_adapter.rb | 2 ++ .../lib/active_record/connection_adapters/mysql2_adapter.rb | 6 ++++++ activerecord/lib/active_record/connection_adapters/mysql_adapter.rb | 4 ++++ .../lib/active_record/connection_adapters/sqlite3_adapter.rb | 2 ++ 4 files changed, 14 insertions(+) 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 167453657d..c824a7b11b 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -285,7 +285,9 @@ module ActiveRecord end end + #-- # DATABASE STATEMENTS ====================================== + #++ def clear_cache! super diff --git a/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb index 5b83131f0e..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)}" diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 8b7459ef27..53ad71b445 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -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 diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb index b18cb353f1..0b8b6a2bf8 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb @@ -266,7 +266,9 @@ module ActiveRecord end end + #-- # DATABASE STATEMENTS ====================================== + #++ def explain(arel, binds = []) sql = "EXPLAIN QUERY PLAN #{to_sql(arel, binds)}" -- cgit v1.2.3 From 92ace39692200d088ec70110b980325a27de8fac Mon Sep 17 00:00:00 2001 From: Genadi Samokovarov Date: Mon, 24 Nov 2014 18:54:03 +0200 Subject: Show source view and backtrace on missing template errors This will help you debug missing template errors, especially if they come from a programmatic template selection. Thanks to @dhh for suggesting that. As a bonus, also show request and response info on the routing error page for consistency. --- .../templates/rescues/missing_template.html.erb | 4 ++++ .../templates/rescues/routing_error.html.erb | 2 ++ actionpack/test/dispatch/debug_exceptions_test.rb | 27 ++++++++++++++++++++++ 3 files changed, 33 insertions(+) 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 @@

<%= h @exception.message %>

+ + <%= render template: "rescues/_source" %> + <%= render template: "rescues/_trace" %> + <%= render template: "rescues/_request_and_response" %>
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" %> diff --git a/actionpack/test/dispatch/debug_exceptions_test.rb b/actionpack/test/dispatch/debug_exceptions_test.rb index f8851f0152..5e87744f6b 100644 --- a/actionpack/test/dispatch/debug_exceptions_test.rb +++ b/actionpack/test/dispatch/debug_exceptions_test.rb @@ -43,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" @@ -120,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 @@ -275,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 -- cgit v1.2.3 From 12a468fe95b5bf6f84fe00eb255ab20a0546ca8e Mon Sep 17 00:00:00 2001 From: Genadi Samokovarov Date: Mon, 24 Nov 2014 22:57:56 +0200 Subject: Don't center the routes table on routing errors --- .../lib/action_dispatch/middleware/templates/routes/_table.html.erb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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; } -- cgit v1.2.3 From 0349516ddbb712680b1b47ef160206946252a2d3 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Mon, 24 Nov 2014 14:07:27 -0700 Subject: Document `String#html_safe` [ci skip] It should be part of the documented public API, since we have an entire section of the guides dedicated to it. Documented in a way that addresses the concerns which kept it undocumented in the past. --- activesupport/lib/active_support/core_ext/string/output_safety.rb | 5 +++++ 1 file changed, 5 insertions(+) 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 042283e4fc..ba92afd5f4 100644 --- a/activesupport/lib/active_support/core_ext/string/output_safety.rb +++ b/activesupport/lib/active_support/core_ext/string/output_safety.rb @@ -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 -- cgit v1.2.3 From 8e1e9f6c70e626e51b158511fb9ef417f04e5397 Mon Sep 17 00:00:00 2001 From: Arthur Neves Date: Mon, 24 Nov 2014 15:48:43 -0500 Subject: Fix sprockets-rails dependency dance - Remove sprockets-rails from generated Gemfile as rails has a hard-dependency on it - Also allow sprockets-rails >= 2.0.0 --- rails.gemspec | 2 +- railties/lib/rails/generators/app_base.rb | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/rails.gemspec b/rails.gemspec index 99685252e0..cc1b8cb1a6 100644 --- a/rails.gemspec +++ b/rails.gemspec @@ -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', '>= 2.0.0' end diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index 5f8c33c713..ec32bb8efc 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -239,8 +239,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 -- cgit v1.2.3 From fbef981fdc7ba64678f7ae1fc82b2cd790469280 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 24 Nov 2014 14:15:45 -0800 Subject: allow the "USING" statement to be specified on change column calls --- .../postgresql/schema_statements.rb | 4 +++- .../adapters/postgresql/change_schema_test.rb | 25 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) create mode 100644 activerecord/test/cases/adapters/postgresql/change_schema_test.rb 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 515ff2dd44..208302b365 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -433,7 +433,9 @@ 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] + 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) 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..90cd28c2ec --- /dev/null +++ b/activerecord/test/cases/adapters/postgresql/change_schema_test.rb @@ -0,0 +1,25 @@ +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)' + end + end + end +end -- cgit v1.2.3 From 63963801c01279d99930de1cb252a8238909bc0c Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 24 Nov 2014 14:18:33 -0800 Subject: oops, forgot to add the real assertion! --- activerecord/test/cases/adapters/postgresql/change_schema_test.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/activerecord/test/cases/adapters/postgresql/change_schema_test.rb b/activerecord/test/cases/adapters/postgresql/change_schema_test.rb index 90cd28c2ec..ec1b446dab 100644 --- a/activerecord/test/cases/adapters/postgresql/change_schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/change_schema_test.rb @@ -19,6 +19,7 @@ module ActiveRecord 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 -- cgit v1.2.3 From cdd90f39d796986dabf1678b3277b230dbe18961 Mon Sep 17 00:00:00 2001 From: Aaron Patterson Date: Mon, 24 Nov 2014 14:29:04 -0800 Subject: allow types to be passed in for USING casts This allows us so abstract the migration from the type that is actually used by Rails. For example, ":string" may be a varchar or something, but the framework does that translation, and the app shouldn't need to know. --- .../active_record/connection_adapters/postgresql/schema_statements.rb | 3 +++ 1 file changed, 3 insertions(+) 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 208302b365..193c950261 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -435,6 +435,9 @@ module ActiveRecord sql_type << "[]" if options[:array] 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) -- cgit v1.2.3 From 9685080a7677abfa5d288a81c3e078368c6bb67c Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sun, 23 Nov 2014 13:53:01 -0800 Subject: let mailer templates generate URLs by default [Xavier Noria, Richard Schneeman] --- actionmailer/CHANGELOG.md | 7 +++ .../fixtures/url_test_mailer/exercise_url_for.erb | 1 + actionmailer/test/url_test.rb | 60 ++++++++++++++++++++++ .../lib/action_dispatch/routing/route_set.rb | 8 ++- actionpack/lib/action_dispatch/routing/url_for.rb | 6 +++ actionview/lib/action_view/rendering.rb | 4 +- actionview/lib/action_view/routing_url_for.rb | 33 +++++++++--- 7 files changed, 107 insertions(+), 12 deletions(-) create mode 100644 actionmailer/test/fixtures/url_test_mailer/exercise_url_for.erb diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md index 5685871ac9..1b3e802cb2 100644 --- a/actionmailer/CHANGELOG.md +++ b/actionmailer/CHANGELOG.md @@ -1,3 +1,10 @@ +* `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. 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..8fce7c3827 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}, relative: 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/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index a641ea3ea9..d2ae2a496f 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -457,7 +457,7 @@ module ActionDispatch RUBY end - def url_helpers(include_path_helpers = true) + def url_helpers(supports_path = true) routes = self Module.new do @@ -484,7 +484,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) @@ -502,6 +502,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 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/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 -- cgit v1.2.3 From 9e7037f19865021030893880b16be7b1ecbd3470 Mon Sep 17 00:00:00 2001 From: eileencodes Date: Mon, 24 Nov 2014 14:56:27 -0500 Subject: Combine aliased_table_for and aliased_name_for This refactoring reduces the number of conditionals needed to build `aliased_table_for` and removes `aliased_name_for` because it's no longer necessary. `aliased_name_for` was also used in `JoinDependency#initialize` so that was replaced with `aliased_table_for` as well. --- .../lib/active_record/associations/alias_tracker.rb | 15 +++------------ .../lib/active_record/associations/join_dependency.rb | 2 +- 2 files changed, 4 insertions(+), 13 deletions(-) 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/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb index c5c4edd090..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 } -- cgit v1.2.3 From 49f74fbc4d0d4986c417e7e5dd10292370b78599 Mon Sep 17 00:00:00 2001 From: Zachary Scott Date: Mon, 24 Nov 2014 16:13:25 -0800 Subject: Add a CHANGELOG entry for #16622 and a6de6f5 [ci skip] --- railties/CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md index a1c7587f4d..aa6b142932 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -1,3 +1,7 @@ +* Deprecate different default for `log_level` in production. + + *Godfrey Chan*, *Matthew Draper* + * Generated `.gitignore` excludes the whole `log/` directory, not only `*.log` files. -- cgit v1.2.3 From b8d8ce7ba8e5e83e9b41e48fb6ef449bd36a97e3 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Tue, 25 Nov 2014 09:14:59 +0800 Subject: Add tests which were incorrectly removed. --- railties/lib/rails/generators/erb/mailer/mailer_generator.rb | 8 ++++---- railties/test/generators/mailer_generator_test.rb | 4 ++++ railties/test/generators/namespaced_generators_test.rb | 2 ++ 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb index 1e290bb938..a228484c11 100644 --- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb @@ -13,11 +13,11 @@ module Erb # :nodoc: @action = action formats.each do |format| - @view_path = File.join(view_base_path, filename_with_extensions(action, format)) - template filename_with_extensions(:view, format), @view_path + @path = File.join(view_base_path, filename_with_extensions(action, format)) + template filename_with_extensions(:view, format), @path - @layout_path = File.join(layout_base_path, filename_with_extensions("mailer", format)) - template filename_with_extensions(:layout, format), @layout_path + layout_path = File.join(layout_base_path, filename_with_extensions("mailer", format)) + template filename_with_extensions(:layout, format), layout_path end end diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb index 915dde1109..20fffd25de 100644 --- a/railties/test/generators/mailer_generator_test.rb +++ b/railties/test/generators/mailer_generator_test.rb @@ -79,10 +79,12 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_invokes_default_text_template_engine run_generator assert_file "app/views/notifier/foo.text.erb" do |view| + assert_match(%r(\sapp/views/notifier/foo\.text\.erb), view) assert_match(/<%= @greeting %>/, view) end assert_file "app/views/notifier/bar.text.erb" do |view| + assert_match(%r(\sapp/views/notifier/bar\.text\.erb), view) assert_match(/<%= @greeting %>/, view) end @@ -94,10 +96,12 @@ class MailerGeneratorTest < Rails::Generators::TestCase def test_invokes_default_html_template_engine run_generator assert_file "app/views/notifier/foo.html.erb" do |view| + assert_match(%r(\sapp/views/notifier/foo\.html\.erb), view) assert_match(/<%= @greeting %>/, view) end assert_file "app/views/notifier/bar.html.erb" do |view| + assert_match(%r(\sapp/views/notifier/bar\.html\.erb), view) assert_match(/<%= @greeting %>/, view) end diff --git a/railties/test/generators/namespaced_generators_test.rb b/railties/test/generators/namespaced_generators_test.rb index 20e8d2d5d3..6075805152 100644 --- a/railties/test/generators/namespaced_generators_test.rb +++ b/railties/test/generators/namespaced_generators_test.rb @@ -174,10 +174,12 @@ class NamespacedMailerGeneratorTest < NamespacedGeneratorTestCase def test_invokes_default_template_engine run_generator assert_file "app/views/test_app/notifier/foo.text.erb" do |view| + assert_match(%r(app/views/test_app/notifier/foo\.text\.erb), view) assert_match(/<%= @greeting %>/, view) end assert_file "app/views/test_app/notifier/bar.text.erb" do |view| + assert_match(%r(app/views/test_app/notifier/bar\.text\.erb), view) assert_match(/<%= @greeting %>/, view) end end -- cgit v1.2.3 From 35628a44b2b8ccf6d1931222447c5ab27b19c7e7 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Tue, 25 Nov 2014 09:16:11 +0800 Subject: MailerGenerator should inherit from Base. --- railties/lib/rails/generators/erb/mailer/mailer_generator.rb | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb index a228484c11..e2f142fd02 100644 --- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb @@ -1,8 +1,10 @@ -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 @@ -20,7 +22,6 @@ module Erb # :nodoc: template filename_with_extensions(:layout, format), layout_path end end - end protected -- cgit v1.2.3 From 7a47690a13f403278036f38b69465167466f6b5f Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Tue, 25 Nov 2014 09:21:37 +0800 Subject: Generate mailer layouts even if no action is given. --- railties/lib/rails/generators/erb/mailer/mailer_generator.rb | 8 ++++---- railties/test/generators/mailer_generator_test.rb | 2 ++ 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb index e2f142fd02..f9b3658ae7 100644 --- a/railties/lib/rails/generators/erb/mailer/mailer_generator.rb +++ b/railties/lib/rails/generators/erb/mailer/mailer_generator.rb @@ -9,7 +9,10 @@ module Erb # :nodoc: view_base_path = File.join("app/views", class_path, file_name) empty_directory view_base_path - layout_base_path = "app/views/layouts" + 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 @@ -17,9 +20,6 @@ module Erb # :nodoc: formats.each do |format| @path = File.join(view_base_path, filename_with_extensions(action, format)) template filename_with_extensions(:view, format), @path - - layout_path = File.join(layout_base_path, filename_with_extensions("mailer", format)) - template filename_with_extensions(:layout, format), layout_path end end end diff --git a/railties/test/generators/mailer_generator_test.rb b/railties/test/generators/mailer_generator_test.rb index 20fffd25de..bab15ce172 100644 --- a/railties/test/generators/mailer_generator_test.rb +++ b/railties/test/generators/mailer_generator_test.rb @@ -113,6 +113,8 @@ class MailerGeneratorTest < Rails::Generators::TestCase 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 -- cgit v1.2.3 From cd902a0d1d06054019d6f60ab3580516031afceb Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Tue, 25 Nov 2014 09:28:16 +0800 Subject: Add missing CHANGELOG entry. --- actionmailer/CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md index 1b3e802cb2..9fdda52f77 100644 --- a/actionmailer/CHANGELOG.md +++ b/actionmailer/CHANGELOG.md @@ -1,3 +1,10 @@ +* MailerGenerator now generates layouts by default. HTML mailer layout will + include `` and `` 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`. -- cgit v1.2.3 From ec49324bd764d62fc61399844cf4b547cf8bc831 Mon Sep 17 00:00:00 2001 From: Guo Xiang Tan Date: Tue, 25 Nov 2014 09:49:29 +0800 Subject: Update docs to reflect changes to MailerGenerator. --- actionmailer/lib/action_mailer/base.rb | 28 +++++++++++++++---------- guides/source/action_mailer_basics.md | 37 ++++++++++++++++++++++++---------- 2 files changed, 43 insertions(+), 22 deletions(-) diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index a70bf1544a..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 ActionMailer::Base. A mailer model defines methods + # The generated model inherits from ApplicationMailer which in turn + # inherits from ActionMailer::Base. 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 :from 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' # @@ -84,7 +90,7 @@ module ActionMailer # name as the method in your mailer model. For example, in the mailer defined above, the template at # app/views/notifier/welcome.text.erb would be used to generate the email. # - # Variables defined in the methods of your mailer model are accessible as instance variables in their + # 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: @@ -178,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") @@ -194,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: "") @@ -206,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") @@ -245,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 # @@ -263,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 @@ -271,7 +277,7 @@ module ActionMailer # Finally, Action Mailer also supports passing Proc 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 @@ -296,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 @@ -703,7 +709,7 @@ 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. # - # It accepts a headers hash. This hash allows you to specify + # 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 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 -- cgit v1.2.3 From 4d84922840deb89754f5b5fb61ebea0aeadc52df Mon Sep 17 00:00:00 2001 From: Melanie Gilman Date: Mon, 24 Nov 2014 10:06:16 -0500 Subject: Deprecate string options in URL helpers Fixes https://github.com/rails/rails/issues/16958 [Byron Bischoff & Melanie Gilman] --- actionpack/CHANGELOG.md | 6 ++++++ actionpack/lib/action_dispatch/routing/route_set.rb | 18 +++++++++++++++++- actionpack/test/dispatch/routing/route_set_test.rb | 20 ++++++++++++++++++++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index 158b22c0cc..7bca373920 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -1,3 +1,9 @@ +* 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 diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index a641ea3ea9..a8ef5531d5 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -271,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) @@ -293,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 diff --git a/actionpack/test/dispatch/routing/route_set_test.rb b/actionpack/test/dispatch/routing/route_set_test.rb index a7acc0de41..5a39119446 100644 --- a/actionpack/test/dispatch/routing/route_set_test.rb +++ b/actionpack/test/dispatch/routing/route_set_test.rb @@ -160,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) -- cgit v1.2.3 From 0bc04ced98108687b4660f868a08da89a262b455 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Mon, 24 Nov 2014 19:18:33 -0700 Subject: Changelog format --- actionpack/CHANGELOG.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index 7bca373920..453da28309 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -1,8 +1,9 @@ * Deprecate use of string keys in URL helpers. - Use symbols instead. Fixes #16958. + Use symbols instead. + Fixes #16958. - *Byron Bischoff & Melanie Gilman* + *Byron Bischoff*, *Melanie Gilman* * Deprecate the `only_path` option on `*_path` helpers. -- cgit v1.2.3 From 4f8eb78b1a6f74504e7f19256007e29ad7c345fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A1bio=20Luiz=20Nery=20de=20Miranda?= Date: Thu, 20 Nov 2014 16:23:03 -0300 Subject: Add perform_enqueued_jobs It will set proper queue_adapter state required by assert_performed_jobs assertions. Also the block version of assert_performed_jobs will make sure this state is respected. Fixes #17684 --- activejob/lib/active_job/test_helper.rb | 36 +++++++++++++++++++++++++------- activejob/test/cases/test_helper_test.rb | 36 ++++++++++++++++++++------------ 2 files changed, 52 insertions(+), 20 deletions(-) diff --git a/activejob/lib/active_job/test_helper.rb b/activejob/lib/active_job/test_helper.rb index bb20d93947..1720b140e5 100644 --- a/activejob/lib/active_job/test_helper.rb +++ b/activejob/lib/active_job/test_helper.rb @@ -77,13 +77,21 @@ module ActiveJob end # Asserts that the number of performed jobs matches the given number. + # If no block is passed, perform_enqueued_jobs + # 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. @@ -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/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 -- cgit v1.2.3 From 116de0731e099313d9e7461b01670cae35bc57e9 Mon Sep 17 00:00:00 2001 From: Zachary Scott Date: Mon, 24 Nov 2014 15:39:11 -0800 Subject: Always default the log_level to :info for Railties --- railties/test/isolation/abstract_unit.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index bf2992005b..c3d4de0ba3 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 -- cgit v1.2.3 From 0613dd0234770ecd66e5f64dfb57aae6d19e9771 Mon Sep 17 00:00:00 2001 From: Zachary Scott Date: Mon, 24 Nov 2014 19:25:50 -0800 Subject: Add Release Note for #16622 [ci skip] --- guides/source/4_2_release_notes.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 1ee3bfe0a4..a5628f734f 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -311,6 +311,9 @@ Please refer to the [Changelog][railties] for detailed changes. * Deprecated `Rails::Rack::LogTailer` without replacement. ([Commit](https://github.com/rails/rails/commit/84a13e019e93efaa8994b3f8303d635a7702dbce)) +* Deprecated missing `config.log_level` for production environments. + ([Pull Request](https://github.com/rails/rails/pull/16622)) + ### Notable changes * Introduced `web-console` in the default application Gemfile. -- cgit v1.2.3 From 1faf222b934d61844d8b8bd4f40e1ef1d2b49433 Mon Sep 17 00:00:00 2001 From: Zachary Scott Date: Mon, 24 Nov 2014 19:42:58 -0800 Subject: Add release note for #17743 [ci skip] --- guides/source/4_2_release_notes.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 1ee3bfe0a4..0281213bf2 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -417,6 +417,19 @@ Please refer to the [Changelog][action-pack] for detailed changes. ([Commit](https://github.com/rails/rails/commit/cc26b6b7bccf0eea2e2c1a9ebdcc9d30ca7390d9)) +* Deprecated support for String keys in URL helpers: + + ```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') + # better :trollface: + Rails.application.routes.url_helpers.root_path(controller: 'posts', action: 'index') + ``` + + ([Pull Request](https://github.com/rails/rails/pull/17743)) + ### Notable changes * Rails will now automatically include the template's digest in ETags. -- cgit v1.2.3 From 79eedb346e103c5ff8e488b992c80b625c864097 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Mon, 24 Nov 2014 22:02:49 -0800 Subject: let the AM test suite pass in 1.9 --- actionmailer/test/url_test.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/actionmailer/test/url_test.rb b/actionmailer/test/url_test.rb index 8fce7c3827..7928fe9542 100644 --- a/actionmailer/test/url_test.rb +++ b/actionmailer/test/url_test.rb @@ -63,7 +63,7 @@ class ActionMailerUrlTest < ActionMailer::TestCase mail end - def assert_url_for(expected, options, relative: false) + 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 @@ -92,7 +92,7 @@ class ActionMailerUrlTest < ActionMailer::TestCase # 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}, relative: true + assert_url_for '/a/b/c', {controller: 'a', action: 'b', id: 'c', only_path: true}, true # model assert_url_for '/dummy_model', DummyModel.new -- cgit v1.2.3 From 1c61b74ce2844e9d41e7f3ecb9e0bd9d11db201a Mon Sep 17 00:00:00 2001 From: Peter Schrammel Date: Tue, 25 Nov 2014 08:56:01 +0100 Subject: be more general with adapter name --- railties/lib/rails/commands/dbconsole.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb index 1a2613a8d0..cb0936d1ef 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"] -- cgit v1.2.3 From 692ca9453c10bac7e54912c5efc29b2d5ba05448 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 01:51:42 -0800 Subject: Mention log_level deprecation in upgrade guides [ci skip] --- guides/source/upgrading_ruby_on_rails.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 042ff76212..b906077ae1 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -145,6 +145,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 -- cgit v1.2.3 From 03c1055b74a8689a7253bbcb1ec87ae0c44a9d92 Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Tue, 25 Nov 2014 19:48:09 +0900 Subject: Fix out of range error message --- activerecord/lib/active_record/type/integer.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/type/integer.rb b/activerecord/lib/active_record/type/integer.rb index 36bbd9cd5e..750f353472 100644 --- a/activerecord/lib/active_record/type/integer.rb +++ b/activerecord/lib/active_record/type/integer.rb @@ -38,7 +38,7 @@ module ActiveRecord def ensure_in_range(value) unless range.cover?(value) - raise RangeError, "#{value} is too large for #{self.class} with limit #{limit || 4}" + raise RangeError, "#{value} is out of range for #{self.class} with limit #{limit || 4}" end end -- cgit v1.2.3 From 6f08eeb6e8fe1082d5a427c0399c75ef8fcf380c Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 01:59:34 -0800 Subject: Set the default log_level to info in all tests This is a follow-up to 116de07. That change was for two reasons: 1) speed up the tests by reducing the amount of log lines 2) avoid a deprecation warning from a6de6f5. This setting need to be on the basic app too, otherwise the deprecation warning will show up on other unrelated test cases. --- railties/test/isolation/abstract_unit.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/railties/test/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index c3d4de0ba3..cbd06a76f6 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -163,6 +163,7 @@ 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.log_level = :info yield app if block_given? app.initialize! -- cgit v1.2.3 From 6ea7065a18671872f1486cff3fdaeb4f78fa6332 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 02:17:13 -0800 Subject: Set the test_order in the basic app as well, see 58e8b48 This removes the unwanted deprecation warnings in the tests --- railties/test/application/configuration_test.rb | 25 +++++++++++++++++++++++++ railties/test/isolation/abstract_unit.rb | 1 + 2 files changed, 26 insertions(+) diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index 391139d7f8..f97be6e91d 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -967,6 +967,31 @@ module ApplicationTests end end + test "Not setting config.log_level is not deprecated for non-production environment" do + build_app + remove_from_config "config.log_level = .*" + with_rails_env "development" do + assert_not_deprecated(/log_level/) { require "#{app_path}/config/environment" } + end + end + + test "Not setting config.log_level is deprecated for the production environment" do + build_app + remove_from_config "config.log_level = .*" + with_rails_env "production" do + assert_deprecated(/log_level/) { require "#{app_path}/config/environment" } + end + end + + test "Setting config.log_level removes the deprecation warning" do + build_app + remove_from_config "config.log_level = .*" + add_to_env_config "production", "config.log_level = :info" + with_rails_env "production" do + assert_not_deprecated(/log_level/) { require "#{app_path}/config/environment" } + 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/isolation/abstract_unit.rb b/railties/test/isolation/abstract_unit.rb index cbd06a76f6..9ad0ec0d34 100644 --- a/railties/test/isolation/abstract_unit.rb +++ b/railties/test/isolation/abstract_unit.rb @@ -163,6 +163,7 @@ 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? -- cgit v1.2.3 From f2a0567b314de7468d5fa16ccb0e11b41d9f4297 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 03:01:11 -0800 Subject: Added tests for log_level deprecation Closes #17756 [Godfrey Chan, Zachary Scott] --- railties/test/application/configuration_test.rb | 31 ++++++++++++++----------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/railties/test/application/configuration_test.rb b/railties/test/application/configuration_test.rb index f97be6e91d..1f97807f8c 100644 --- a/railties/test/application/configuration_test.rb +++ b/railties/test/application/configuration_test.rb @@ -967,28 +967,33 @@ module ApplicationTests end end - test "Not setting config.log_level is not deprecated for non-production environment" do - build_app - remove_from_config "config.log_level = .*" + test "Blank config.log_level is not deprecated for non-production environment" do with_rails_env "development" do - assert_not_deprecated(/log_level/) { require "#{app_path}/config/environment" } + assert_not_deprecated do + make_basic_app do |app| + app.config.log_level = nil + end + end end end - test "Not setting config.log_level is deprecated for the production environment" do - build_app - remove_from_config "config.log_level = .*" + test "Blank config.log_level is deprecated for the production environment" do with_rails_env "production" do - assert_deprecated(/log_level/) { require "#{app_path}/config/environment" } + assert_deprecated(/log_level/) do + make_basic_app do |app| + app.config.log_level = nil + end + end end end - test "Setting config.log_level removes the deprecation warning" do - build_app - remove_from_config "config.log_level = .*" - add_to_env_config "production", "config.log_level = :info" + test "Not blank config.log_level is not deprecated for the production environment" do with_rails_env "production" do - assert_not_deprecated(/log_level/) { require "#{app_path}/config/environment" } + assert_not_deprecated do + make_basic_app do |app| + app.config.log_level = :info + end + end end end -- cgit v1.2.3 From 56f2b70db1210f63e972a8755551cc6eb95dc497 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 03:55:15 -0800 Subject: Simplify section on adequate record [ci skip] --- guides/source/4_2_release_notes.md | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 69562e21da..ca61f9968f 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -54,26 +54,26 @@ 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 up to 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: -- cgit v1.2.3 From a50bf9d9a7ac10ef3426cf7c98135ac2e61369be Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 03:55:54 -0800 Subject: The default hasn't changed, so this is not an incompatibility [ci skip] --- guides/source/4_2_release_notes.md | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index ca61f9968f..a9e134c18d 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -206,22 +206,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 -- cgit v1.2.3 From c71025123472d3fa8b0a47605257993dca1f23b3 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 03:56:39 -0800 Subject: :scissors: TODO --- guides/source/4_2_release_notes.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index a9e134c18d..622df3ce24 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -228,10 +228,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. -- cgit v1.2.3 From ae5538ca6b25582be9676ce8f66b0e07d34fbc31 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 04:07:08 -0800 Subject: Final sync with CHANGELOGs [ci skip] --- guides/source/4_2_release_notes.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 622df3ce24..26142cd212 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -297,6 +297,13 @@ Please refer to the [Changelog][railties] for detailed changes. * 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)) + ### Notable changes * Introduced `web-console` in the default application Gemfile. @@ -409,8 +416,6 @@ Please refer to the [Changelog][action-pack] for detailed changes. # bad Rails.application.routes.url_helpers.root_path('controller' => 'posts', 'action' => 'index') # good - Rails.application.routes.url_helpers.root_path(:controller => 'posts', :action => 'index') - # better :trollface: Rails.application.routes.url_helpers.root_path(controller: 'posts', action: 'index') ``` -- cgit v1.2.3 From 1e5290a743f03a132fe82bf0c4631ee5a587c6a4 Mon Sep 17 00:00:00 2001 From: JONBRWN Date: Thu, 13 Nov 2014 19:03:38 -0500 Subject: sets script_name to always be a string. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #17615 #17616 when script_name is nil in the options hash, script_name is set to nil. options = {script_name: nil} script_name = options.delete(:script_name) {‘’} # => nil Signed-off-by: Santiago Pastorino --- actionpack/lib/action_dispatch/routing/route_set.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index dcfb819906..6e3ae36a7f 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -749,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: -- cgit v1.2.3 From ad973ab8a0cb268984533f9f61bf1b463d47a066 Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Tue, 25 Nov 2014 10:29:48 -0200 Subject: Add regression test case to ensure script_name as nil is not used anymore in url_for --- actionpack/test/controller/url_for_test.rb | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index f0eba17556..83302d880d 100644 --- a/actionpack/test/controller/url_for_test.rb +++ b/actionpack/test/controller/url_for_test.rb @@ -290,6 +290,13 @@ module AbstractController end end + def test_using_nil_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 -- cgit v1.2.3 From 4d3742c1d3c58ebad6a48e53c3d7bbd1651efa5f Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 04:30:15 -0800 Subject: Cross link to upgrade guide [ci skip] --- guides/source/4_2_release_notes.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 26142cd212..02857ec710 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -383,7 +383,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`. -- cgit v1.2.3 From c42ef3fd02b843e8e25d25910b89fa624f0a2522 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 04:32:05 -0800 Subject: Prepare for RC: link to the 4-2-stable [ci skip] --- guides/source/4_2_release_notes.md | 4 ++-- guides/source/upgrading_ruby_on_rails.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 02857ec710..4f8ebbf336 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -10,13 +10,13 @@ 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). +a [pull request](https://github.com/rails/rails/edit/4-2-stable/guides/source/4_2_release_notes.md). Upgrading to Rails 4.2 ---------------------- diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index b906077ae1..7423d2cb59 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -51,7 +51,7 @@ 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). +a [pull request](https://github.com/rails/rails/edit/4-2-stabble/guides/source/upgrading_ruby_on_rails.md). ### Web Console -- cgit v1.2.3 From 40c3880d8bc3273a8dbaa3ee0e95d084e71e1aa3 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 04:34:43 -0800 Subject: We shouldn't be linking to edgeapi [ci skip] --- guides/source/engines.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/engines.md b/guides/source/engines.md index de33f5f067..a1f2da18ed 100644 --- a/guides/source/engines.md +++ b/guides/source/engines.md @@ -1166,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. -- cgit v1.2.3 From 064d188f228fe94169d444ec4efcd607e7c9cf82 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 04:36:54 -0800 Subject: Prepare for RC: un-wip release notes [ci skip] --- guides/source/documents.yaml | 1 - 1 file changed, 1 deletion(-) 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 -- cgit v1.2.3 From 83c52c048696aa70bfe6f83eb231eac80df029c0 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 04:38:17 -0800 Subject: :scissors: WIP labels [ci skip] --- guides/source/4_2_release_notes.md | 3 --- guides/source/upgrading_ruby_on_rails.md | 3 --- 2 files changed, 6 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 4f8ebbf336..083473912d 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -15,9 +15,6 @@ 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/4-2-stable/guides/source/4_2_release_notes.md). - Upgrading to Rails 4.2 ---------------------- diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 7423d2cb59..24e4ea2c1f 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -50,9 +50,6 @@ 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/4-2-stabble/guides/source/upgrading_ruby_on_rails.md). - ### Web Console First, add `gem 'web-console', '~> 2.0.0.beta4'` 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. -- cgit v1.2.3 From 0715d8c3681306d6cf119ad3b460bbd0890d9b49 Mon Sep 17 00:00:00 2001 From: Godfrey Chan Date: Tue, 25 Nov 2014 04:56:00 -0800 Subject: Rearrange release notes by importance [ci skip] --- guides/source/4_2_release_notes.md | 184 +++++++++++++++++-------------------- 1 file changed, 85 insertions(+), 99 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 083473912d..ba45d5c6d1 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -288,9 +288,6 @@ Please refer to the [Changelog][railties] for detailed changes. ### Deprecations -* Deprecated `Rails::Rack::LogTailer` without replacement. - ([Commit](https://github.com/rails/rails/commit/84a13e019e93efaa8994b3f8303d635a7702dbce)) - * Deprecated missing `config.log_level` for production environments. ([Pull Request](https://github.com/rails/rails/pull/16622)) @@ -301,6 +298,9 @@ Please refer to the [Changelog][railties] for detailed changes. * 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)) + ### Notable changes * Introduced `web-console` in the default application Gemfile. @@ -309,9 +309,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 @@ -365,6 +362,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)) @@ -421,18 +421,6 @@ Please refer to the [Changelog][action-pack] for detailed changes. ### Notable changes -* Rails will now automatically include the template's digest in ETags. - ([Pull Request](https://github.com/rails/rails/pull/16527)) - -* `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)) - -* 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)) - * The `*_filter` family methods have been removed from the documentation. Their usage is discouraged in favor of the `*_action` family methods: @@ -459,6 +447,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)) @@ -466,9 +470,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)) @@ -483,19 +484,6 @@ Please refer to the [Changelog][action-pack] for detailed changes. 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 ------------- @@ -518,16 +506,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 `
` 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 `
` 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)) @@ -580,39 +568,15 @@ Please refer to the [Changelog][active-record] for detailed changes. ### Deprecations -* 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)) - * 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), @@ -630,34 +594,35 @@ 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)) -* `ActiveRecord::Base#reflections` now returns a hash with `String` keys instead of `Symbol` keys. - ([Pull Request](https://github.com/rails/rails/pull/17718)) +* 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 PostgreSQL adapter now supports the `JSONB` datatype in PostgreSQL 9.4+. - ([Pull Request](https://github.com/rails/rails/pull/16220)) +* Deprecated `Reflection#source_macro` without replacement as it is no longer + needed in Active Record. + ([Pull Request](https://github.com/rails/rails/pull/16373)) -* 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 `serialized_attributes` without replacement. + ([Pull Request](https://github.com/rails/rails/pull/15704)) -* 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 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)) -* Introduced `ActiveRecord::Base#validate!` that raises `RecordInvalid` if the - record is invalid. - ([Pull Request](https://github.com/rails/rails/pull/8639)) +* 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)) -* `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)) +### Notable changes -* Introduced the `bin/rake db:purge` task to empty the database for the - current environment. - ([Commit](https://github.com/rails/rails/commit/e2f232aba15937a4b9d14bd91e0392c6d55be58d)) +* 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 Active Record models will no longer save when @@ -667,35 +632,57 @@ Please refer to the [Changelog][active-record] for detailed changes. [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 ------------ @@ -718,6 +705,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), @@ -731,10 +721,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 -------------- -- cgit v1.2.3 From 7836e887d70f341a47061fafedcd595b7dfa7320 Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Tue, 25 Nov 2014 13:53:57 +0100 Subject: tests, run `test_test.rb` with `RAILS_ENV=test`. The tests to verify our testing setup used `RAILS_ENV=development` to execute the tests. Let's keep it as close to a real-world setup as possible. --- railties/test/application/test_test.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index c724c867ec..4d06056280 100644 --- a/railties/test/application/test_test.rb +++ b/railties/test/application/test_test.rb @@ -208,7 +208,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) -- cgit v1.2.3 From 8a170e609456ce906f589b584188eb2f7a2bbfb6 Mon Sep 17 00:00:00 2001 From: Javier Vidal Date: Tue, 25 Nov 2014 17:52:46 +0100 Subject: Fixing wrong link in 'Ruby on Rails 3.0 Release Notes' [ci skip] --- guides/source/3_0_release_notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/3_0_release_notes.md b/guides/source/3_0_release_notes.md index 2630207c0f..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 -- cgit v1.2.3 From 9e9793b440c044b765f2d1f702feeb92aef2b139 Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Tue, 25 Nov 2014 18:11:38 +0100 Subject: do not trigger AR lazy load hook before initializers ran. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit [Rafael Mendonça França & Yves Senn] This require caused the `active_record.set_configs` initializer to run immediately, before `config/initializers`. This means that setting any configuration on `Rails.application.config.active_record` inside of an initializer had no effects when rails was loaded through `rake`. Introduced by #6518 /cc @rafaelfranca --- activerecord/lib/active_record/railtie.rb | 2 -- 1 file changed, 2 deletions(-) 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 -- cgit v1.2.3 From 5c4495538bb4e8808ce077f08ea6b809952daa44 Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Mon, 24 Nov 2014 12:04:01 +0100 Subject: bring back `db:test:prepare`. This reverts deprecations added in #13528. The task is brought back for two reasons: 1. Give plugins a way to hook into the test database initialization process 2. Give the user a way to force a test database synchronization While `test:prepare` is still a dependency of every test task, `db:test:prepare` no longer hooks into it. This means that `test:prepare` runs before the schema is synchronized. Plugins, which insert data can now hook into `db:test:prepare`. The automatic schema maintenance can't detect when a migration is rolled-back, modified and reapplied. In this case the user has to fall back to `db:test:prepare` to force the synchronization to happen. --- activerecord/CHANGELOG.md | 15 ++++ activerecord/lib/active_record/migration.rb | 9 ++- .../lib/active_record/railties/databases.rake | 10 +-- railties/test/application/rake/dbs_test.rb | 9 --- railties/test/application/test_test.rb | 92 ++++++++++++++++++++++ 5 files changed, 120 insertions(+), 15 deletions(-) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 9130cfbe9e..2140b1ea83 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,18 @@ +* 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 was synchronized. + + Fixes #17171, #15787. + + *Yves Senn* + * Change `reflections` public api to return the keys as String objects. Fixes #16928. diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 4e00eb3d99..92f2951f2d 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -395,7 +395,14 @@ module ActiveRecord def load_schema_if_pending! if ActiveRecord::Migrator.needs_migration? || !ActiveRecord::Migrator.any_migrations? - ActiveRecord::Tasks::DatabaseTasks.load_schema_current_if_exists + # 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 diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index 3ec25f9f17..21b1c3f721 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -305,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 @@ -315,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 @@ -328,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 @@ -349,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/railties/test/application/rake/dbs_test.rb b/railties/test/application/rake/dbs_test.rb index 524c70aad2..0a5873bcbf 100644 --- a/railties/test/application/rake/dbs_test.rb +++ b/railties/test/application/rake/dbs_test.rb @@ -175,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 4d06056280..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) -- cgit v1.2.3 From 3848bbe870b77376263d776ea226402f89c57f83 Mon Sep 17 00:00:00 2001 From: Bruno Sutic Date: Tue, 25 Nov 2014 18:46:01 +0100 Subject: CSS fix for the router visualizer --- actionpack/lib/action_dispatch/journey/visualizer/fsm.css | 4 ---- 1 file changed, 4 deletions(-) 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} -- cgit v1.2.3 From dd986814e7f528916a44f841a02c955a4522307c Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Tue, 25 Nov 2014 10:52:33 -0700 Subject: Setting an association replaces records with the same id in memory The records weren't being replaced since equality in Active Record is defined in terms of `id` only. It is reasonable to expect that the references would be replaced in memory, even if no queries are actually executed. This change did not appear to affect any other parts of the code base. I chose not to execute callbacks since we're not actually modifying the association in a way that will be persisted. Fixes #17730 --- .../associations/collection_association.rb | 20 ++++++- .../associations/has_many_associations_test.rb | 64 ++++++++++++++++++++++ 2 files changed, 82 insertions(+), 2 deletions(-) diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index d59cebb08b..2b7d39893d 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -358,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 @@ -385,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 @@ -534,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/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 5a963b6458..8b7ab11570 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1997,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 -- cgit v1.2.3 From 5394f561a5d031357687fa99fd4f03348619fe4c Mon Sep 17 00:00:00 2001 From: Genadi Samokovarov Date: Tue, 25 Nov 2014 20:52:01 +0200 Subject: Remove Web Console /console references in the guides --- guides/source/4_2_release_notes.md | 9 ++++----- guides/source/upgrading_ruby_on_rails.md | 9 --------- 2 files changed, 4 insertions(+), 14 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index ba45d5c6d1..87a4f8b463 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -97,8 +97,8 @@ 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 let you execute code where the exception originated. It's quite handy being able to introspect the state that @@ -107,9 +107,8 @@ 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 diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index 24e4ea2c1f..cf6bdd0d0f 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -54,15 +54,6 @@ Upgrading from Rails 4.1 to Rails 4.2 First, add `gem 'web-console', '~> 2.0.0.beta4'` 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: -- cgit v1.2.3 From 8f7434adba492bfa52463d1eeeaf7d5cb16288f6 Mon Sep 17 00:00:00 2001 From: Agis- Date: Tue, 28 Oct 2014 23:18:58 +0200 Subject: Local vars should exist in partials for falsy `:object:` values too c67005f221f102fe2caca231027d9b11cf630484 made the local var in partials available only if what passed to `:object` was truthy. For example this would not make the local variable `foo` available inside the partial: render partial: 'foo', object: false Fixes #17373. --- actionview/CHANGELOG.md | 7 +++++++ actionview/lib/action_view/renderer/partial_renderer.rb | 4 ++-- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md index 6b7adbe4a3..de65543137 100644 --- a/actionview/CHANGELOG.md +++ b/actionview/CHANGELOG.md @@ -1,3 +1,10 @@ +* 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 diff --git a/actionview/lib/action_view/renderer/partial_renderer.rb b/actionview/lib/action_view/renderer/partial_renderer.rb index 0407632435..338ae270d2 100644 --- a/actionview/lib/action_view/renderer/partial_renderer.rb +++ b/actionview/lib/action_view/renderer/partial_renderer.rb @@ -366,7 +366,7 @@ module ActionView partial = options[:partial] if String === partial - @object = options[:object] + @object = options[:object] if options.has_key?(:object) @collection = collection_from_options @path = partial else @@ -506,7 +506,7 @@ module ActionView def retrieve_template_keys keys = @locals.keys - keys << @variable if @object || @collection + keys << @variable if defined?(@object) || @collection if @collection keys << @variable_counter keys << @variable_iteration -- cgit v1.2.3 From d74e716b48b19a608a0445996cfcf17d304f289f Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Tue, 25 Nov 2014 13:57:06 -0700 Subject: Move PG float quoting to the correct location Not sure how we missed this case when we moved everything else to the `_quote` method. --- .../connection_adapters/postgresql/quoting.rb | 22 ++++++---------------- 1 file changed, 6 insertions(+), 16 deletions(-) diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb b/activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb index f95f45c689..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}'" - 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 -- cgit v1.2.3 From e3f7817cec95ac395c9e1491178a1fad0a73af63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Tue, 25 Nov 2014 19:42:17 -0200 Subject: Use released rails-dom-testing --- Gemfile | 1 - actionmailer/actionmailer.gemspec | 2 +- actionpack/actionpack.gemspec | 2 +- actionview/actionview.gemspec | 2 +- railties/lib/rails/generators/app_base.rb | 2 -- 5 files changed, 3 insertions(+), 6 deletions(-) diff --git a/Gemfile b/Gemfile index 60b668401d..e7b7913970 100644 --- a/Gemfile +++ b/Gemfile @@ -15,7 +15,6 @@ gem 'jquery-rails', '~> 4.0.0.beta2' gem 'coffee-rails', '~> 4.1.0' gem 'turbolinks' gem 'arel', github: 'rails/arel' -gem 'rails-dom-testing', github: 'rails/rails-dom-testing' # require: false so bcrypt is loaded only when has_secure_password is used. # This is to avoid ActiveModel (and by extension the entire framework) diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec index abc047d339..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.4' + s.add_dependency 'rails-dom-testing', '~> 1.0', '>= 1.0.5' end diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index 5196e67e55..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.4' + 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/actionview/actionview.gemspec b/actionview/actionview.gemspec index 70efe7e8c2..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.4' + 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/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index ec32bb8efc..e8dfc33915 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -196,10 +196,8 @@ module Rails def rails_gemfile_entry if options.dev? [GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH), - GemfileEntry.github('rails-dom-testing', 'rails/rails-dom-testing')] elsif options.edge? [GemfileEntry.github('rails', 'rails/rails'), - GemfileEntry.github('rails-dom-testing', 'rails/rails-dom-testing')] else [GemfileEntry.version('rails', Rails::VERSION::STRING, -- cgit v1.2.3 From 25c85cb6f6d8715da3f7fae08b165d01e6b34348 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Tue, 25 Nov 2014 19:58:08 -0200 Subject: Use released arel --- Gemfile | 1 - activerecord/activerecord.gemspec | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/Gemfile b/Gemfile index e7b7913970..9f27acca6f 100644 --- a/Gemfile +++ b/Gemfile @@ -14,7 +14,6 @@ gem 'rack-cache', '~> 1.2' gem 'jquery-rails', '~> 4.0.0.beta2' gem 'coffee-rails', '~> 4.1.0' gem 'turbolinks' -gem 'arel', github: 'rails/arel' # require: false so bcrypt is loaded only when has_secure_password is used. # This is to avoid ActiveModel (and by extension the entire framework) diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec index bc10e96244..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.beta2', '< 6.1' + s.add_dependency 'arel', '~> 6.0' end -- cgit v1.2.3 From ac0432cf351d11f9cfaf2eb879388eb8bcf09cd7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Tue, 25 Nov 2014 20:15:46 -0200 Subject: Fix syntax error :bomb: --- railties/lib/rails/generators/app_base.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index e8dfc33915..be79f37e94 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -195,9 +195,9 @@ module Rails def rails_gemfile_entry if options.dev? - [GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH), + [GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH)] elsif options.edge? - [GemfileEntry.github('rails', 'rails/rails'), + [GemfileEntry.github('rails', 'rails/rails')] else [GemfileEntry.version('rails', Rails::VERSION::STRING, -- cgit v1.2.3 From 323334a775bb35d901742e4cc39f6fe7b5e53c8f Mon Sep 17 00:00:00 2001 From: Derek Prior Date: Mon, 24 Nov 2014 21:25:15 -0500 Subject: Generators add foreign keys on references If you run a generator such as: ``` rails generate model accounts supplier:references ``` The resulting migration will now add the corresponding foreign key constraint unless the reference was specified to be polymorphic. --- .../migration/templates/create_table_migration.rb | 3 +++ .../active_record/migration/templates/migration.rb | 6 +++++ railties/CHANGELOG.md | 5 +++++ .../test/generators/migration_generator_test.rb | 26 +++++++++++++++++++++- railties/test/generators/model_generator_test.rb | 21 +++++++++++++++++ 5 files changed, 60 insertions(+), 1 deletion(-) 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 @@ -14,6 +14,9 @@ class <%= migration_class_name %> < ActiveRecord::Migration end <% 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/railties/CHANGELOG.md b/railties/CHANGELOG.md index aa6b142932..ff6dcac465 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -1,3 +1,8 @@ +* Generated migrations add the appropriate foreign key constraints to + references. + + *Derek Prior* + * Deprecate different default for `log_level` in production. *Godfrey Chan*, *Matthew Draper* 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) -- cgit v1.2.3 From 2f8be7ebafcf7815f9f3ec7983789157525a60fa Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Tue, 25 Nov 2014 15:57:00 -0700 Subject: Fix warning in AV tests Originally caused by #17771 --- actionview/lib/action_view/renderer/partial_renderer.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/actionview/lib/action_view/renderer/partial_renderer.rb b/actionview/lib/action_view/renderer/partial_renderer.rb index 338ae270d2..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 - @object = options[:object] if options.has_key?(:object) + @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 defined?(@object) || @collection + keys << @variable if @has_object || @collection if @collection keys << @variable_counter keys << @variable_iteration -- cgit v1.2.3 From 7f864ccd65212834beb3464bcd4917db8e57aa4d Mon Sep 17 00:00:00 2001 From: Genadi Samokovarov Date: Wed, 26 Nov 2014 00:04:25 +0200 Subject: Use web_console 2.0 for 4.2.0.rc1 release This one replaces the notable web-console mentions in guide and the default Gemfile. --- guides/source/upgrading_ruby_on_rails.md | 2 +- railties/lib/rails/generators/rails/app/templates/Gemfile | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/guides/source/upgrading_ruby_on_rails.md b/guides/source/upgrading_ruby_on_rails.md index cf6bdd0d0f..4ce61c282d 100644 --- a/guides/source/upgrading_ruby_on_rails.md +++ b/guides/source/upgrading_ruby_on_rails.md @@ -52,7 +52,7 @@ Upgrading from Rails 4.1 to Rails 4.2 ### Web Console -First, add `gem 'web-console', '~> 2.0.0.beta4'` 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. +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. ### Responders diff --git a/railties/lib/rails/generators/rails/app/templates/Gemfile b/railties/lib/rails/generators/rails/app/templates/Gemfile index 5961f7515c..7027312aa9 100644 --- a/railties/lib/rails/generators/rails/app/templates/Gemfile +++ b/railties/lib/rails/generators/rails/app/templates/Gemfile @@ -32,7 +32,7 @@ group :development, :test do <%- 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' -- cgit v1.2.3 From 75eacb00e0a5b23dca4f067dacafecddcb41b04a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Tue, 25 Nov 2014 22:34:10 -0200 Subject: Use jquery-rails 4.0.0 --- Gemfile | 2 +- railties/lib/rails/generators/app_base.rb | 10 ++-------- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/Gemfile b/Gemfile index 9f27acca6f..99e2cb9f58 100644 --- a/Gemfile +++ b/Gemfile @@ -11,7 +11,7 @@ gem 'rake', '>= 10.3' gem 'mocha', '~> 0.14', require: false gem 'rack-cache', '~> 1.2' -gem 'jquery-rails', '~> 4.0.0.beta2' +gem 'jquery-rails', '~> 4.0' gem 'coffee-rails', '~> 4.1.0' gem 'turbolinks' diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index be79f37e94..0823b0cc46 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -276,14 +276,8 @@ module Rails [] else gems = [coffee_gemfile_entry, javascript_runtime_gemfile_entry] - - 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") - end + gems << GemfileEntry.version("#{options[:javascript]}-rails", nil, + "Use #{options[:javascript]} as the JavaScript library") unless options[:skip_turbolinks] gems << GemfileEntry.version("turbolinks", nil, -- cgit v1.2.3 From fc20bfd4f16bab3dc207923c343f3e9bb5a924cb Mon Sep 17 00:00:00 2001 From: Zachary Scott Date: Tue, 25 Nov 2014 16:54:30 -0800 Subject: Clarify where result goes, and supported formats of generate task. [ci skip] --- guides/Rakefile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) 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]} -- cgit v1.2.3 From 5a9acfdfa039cc6002e235168e2ae0acec1ea8b9 Mon Sep 17 00:00:00 2001 From: dilpreet92 Date: Wed, 26 Nov 2014 12:32:12 +0530 Subject: getting the location of the server --- actionpack/lib/action_controller/base.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 7bbf938987..2e9121167a 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -44,10 +44,10 @@ 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 - # + # # == Parameters # # All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params method -- cgit v1.2.3 From a882c69e7b0e5c41b2fea20f0c337107f6203b47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Wed, 26 Nov 2014 05:43:52 -0200 Subject: :scissors: --- actionpack/lib/action_controller/base.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 2e9121167a..5cb11bc479 100644 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -47,7 +47,7 @@ module ActionController # location = request.env["REMOTE_ADDR"] # render plain: "This server hosted at #{location}" # end - # + # # == Parameters # # All request parameters, whether they come from a GET or POST request, or from the URL, are available through the params method -- cgit v1.2.3 From 0a48d229de622874f3d4041a9cd76305c58d3150 Mon Sep 17 00:00:00 2001 From: Artur Cygan Date: Wed, 26 Nov 2014 09:51:41 +0100 Subject: Remove extra empty line --- actionpack/lib/action_controller/log_subscriber.rb | 1 - 1 file changed, 1 deletion(-) 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) -- cgit v1.2.3 From 35c5f47d9739ed46c0fb344279f68fe0fc2e98df Mon Sep 17 00:00:00 2001 From: Jon Atack Date: Wed, 26 Nov 2014 12:23:00 +0100 Subject: Active Record change log pass [skip ci] --- activerecord/CHANGELOG.md | 78 ++++++++++++++++++++++++----------------------- 1 file changed, 40 insertions(+), 38 deletions(-) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 2140b1ea83..a6ed8cdb06 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -7,7 +7,7 @@ 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 was synchronized. + NOTE: `test:prepare` runs before the schema is synchronized. Fixes #17171, #15787. @@ -29,12 +29,11 @@ *Yves Senn* -* Fix includes on association with a scope containing joins along with conditions - on the joined assoiciation. +* 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* @@ -95,7 +94,7 @@ *Yuki Nishijima* -* Fix regression causing `after_create` callbacks to run before associated +* Fix a regression causing `after_create` callbacks to run before associated records are autosaved. Fixes #17209. @@ -192,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* @@ -206,7 +205,7 @@ *Agis Anastasopoulos* -* Fixed `Relation#exists?` to work with polymorphic associations. +* Fix `Relation#exists?` to work with polymorphic associations. Fixes #15821. @@ -228,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. @@ -292,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. @@ -455,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* @@ -681,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* @@ -717,7 +716,7 @@ *arthurnn* -* Fixed serialization for records with an attribute named `format`. +* Fix serialization for records with an attribute named `format`. Fixes #15188. @@ -728,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. @@ -747,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. @@ -859,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. @@ -964,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. @@ -977,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. @@ -1038,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. @@ -1070,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. @@ -1106,7 +1107,7 @@ *arthurnn* -* Fixed error when using `with_options` with lambda. +* Fix error when using `with_options` with lambda. Fixes #9805. @@ -1144,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. @@ -1244,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* @@ -1252,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* @@ -1283,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. @@ -1299,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. -- cgit v1.2.3 From f2b17231bacbbc437f64b51b386b3eea06c65c84 Mon Sep 17 00:00:00 2001 From: Alexander Mankuta Date: Wed, 26 Nov 2014 13:47:09 +0200 Subject: Use absolute_path of caller_locations to infer engine root According to documentation `path` only returns file names. On MRI it's not the case but it's likely a bug in MRI. --- railties/lib/rails/engine.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/engine.rb b/railties/lib/rails/engine.rb index 023ea98145..4b7da32208 100644 --- a/railties/lib/rails/engine.rb +++ b/railties/lib/rails/engine.rb @@ -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+.*/, '') } -- cgit v1.2.3 From 9530c5786e621bcafa68a2eab3021ccd9a930e52 Mon Sep 17 00:00:00 2001 From: Bruno Sutic Date: Wed, 26 Nov 2014 13:28:59 +0100 Subject: Refactor nested if --- actionpack/lib/action_dispatch/routing/mapper.rb | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index be54d43172..a8be77f46d 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -244,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 -- cgit v1.2.3 From 3766015f07c026e1a22d1b7732f52d25d8b8d6c5 Mon Sep 17 00:00:00 2001 From: Juan Ignacio Pumarino Date: Wed, 26 Nov 2014 10:36:54 -0300 Subject: Provide support for SQL Server connections with dbconsole using sqsh --- railties/lib/rails/commands/dbconsole.rb | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/railties/lib/rails/commands/dbconsole.rb b/railties/lib/rails/commands/dbconsole.rb index 1a2613a8d0..b01cdce6ea 100644 --- a/railties/lib/rails/commands/dbconsole.rb +++ b/railties/lib/rails/commands/dbconsole.rb @@ -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 -- cgit v1.2.3 From 3e30c5d4222f816cdffd5241d56ef9442f6d1903 Mon Sep 17 00:00:00 2001 From: Recursive Madman Date: Wed, 19 Nov 2014 12:34:25 +0100 Subject: Add #record attribute to RecordNotFound and RecordDestroyed exceptions. This allows these exceptions to be handled generically in conjunction with RecordInvalid. --- activerecord/lib/active_record/errors.rb | 19 +++++++++++++++++++ activerecord/lib/active_record/persistence.rb | 4 ++-- activerecord/test/cases/callbacks_test.rb | 6 ++++-- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb index 5b3fdf16f5..ca4fede7a2 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. diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index ee3b7b6163..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 @@ -181,7 +181,7 @@ module ActiveRecord # and destroy! 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 diff --git a/activerecord/test/cases/callbacks_test.rb b/activerecord/test/cases/callbacks_test.rb index 5e07f8a03c..e3c3c2fcdf 100644 --- a/activerecord/test/cases/callbacks_test.rb +++ b/activerecord/test/cases/callbacks_test.rb @@ -443,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 @@ -477,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) -- cgit v1.2.3 From 59190c037999d302dd95b1f53f7049c2cec3f7b9 Mon Sep 17 00:00:00 2001 From: Recursive Madman Date: Wed, 26 Nov 2014 15:05:34 +0100 Subject: various error classes: added newlines & removed :nodoc: flag from public attribute. --- activerecord/lib/active_record/errors.rb | 2 ++ activerecord/lib/active_record/validations.rb | 7 ++++--- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb index ca4fede7a2..14819aab54 100644 --- a/activerecord/lib/active_record/errors.rb +++ b/activerecord/lib/active_record/errors.rb @@ -196,6 +196,7 @@ module ActiveRecord # offending attribute. class AttributeAssignmentError < ActiveRecordError attr_reader :exception, :attribute + def initialize(message, exception, attribute) super(message) @exception = exception @@ -208,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/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")) -- cgit v1.2.3 From 2a4e14db981e38611667d407a975600ee720ada7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Wed, 26 Nov 2014 16:17:51 -0200 Subject: Test against rack master --- Gemfile | 2 ++ railties/lib/rails/generators/app_base.rb | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Gemfile b/Gemfile index 99e2cb9f58..f1650ce7d3 100644 --- a/Gemfile +++ b/Gemfile @@ -2,6 +2,8 @@ source 'https://rubygems.org' gemspec +gem 'rack', github: 'rack/rack' + # We need a newish Rake since Active Job sets its test tasks' descriptions. gem 'rake', '>= 10.3' diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index 0823b0cc46..b410363f2f 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -195,9 +195,9 @@ module Rails def rails_gemfile_entry if options.dev? - [GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH)] + [GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH), GemfileEntry.github('rack', 'rack/rack')] elsif options.edge? - [GemfileEntry.github('rails', 'rails/rails')] + [GemfileEntry.github('rails', 'rails/rails'), GemfileEntry.github('rack', 'rack/rack')] else [GemfileEntry.version('rails', Rails::VERSION::STRING, -- cgit v1.2.3 From 3b48938948ba33da6f5d50e28f78658322202322 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Thu, 27 Nov 2014 01:20:57 +0100 Subject: pass over the release notes --- guides/source/4_2_release_notes.md | 222 ++++++++++++++++++++----------------- 1 file changed, 118 insertions(+), 104 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 87a4f8b463..822a28bcd6 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -3,15 +3,15 @@ Ruby on Rails 4.2 Release Notes Highlights in Rails 4.2: -* Active Job, Action Mailer #deliver_later +* Active Job, Action Mailer's `deliver_later` * Adequate Record * Web Console * Foreign key support -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/4-2-stable) in the main Rails -repository on GitHub. +These release notes cover only the major changes. To learn about other +features, bug fixes, and changes, please refer to the changelogs or check out +the [list of commits](https://github.com/rails/rails/commits/4-2-stable) in +the main Rails repository on GitHub. -------------------------------------------------------------------------------- @@ -22,32 +22,37 @@ If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 4.1 in case you haven't and make sure your application still runs as expected before attempting to upgrade to Rails 4.2. A list of things to watch out for when upgrading is -available in the guide: [Upgrading Ruby on -Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-4-1-to-rails-4-2) +available in the guide [Upgrading Ruby on +Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-4-1-to-rails-4-2). Major Features -------------- -### Active Job, Action Mailer #deliver_later +### Active Job, Action Mailer's `deliver_later` -Active Job is a new framework in Rails 4.2. It is an adapter layer on top of +Active Job is a new framework in Rails 4.2. It is a common interface on top of queuing systems like [Resque](https://github.com/resque/resque), [Delayed Job](https://github.com/collectiveidea/delayed_job), [Sidekiq](https://github.com/mperham/sidekiq), and more. -You can write your jobs with the Active Job API, and it'll run on all these -queues with no changes (it comes pre-configured with an inline runner). +Jobs written with the Active Job API run on any of the supported queues thanks +to their respective adapters. Active Job comes pre-configured with an inline +runner that executes jobs right away. -Building on top of Active Job, Action Mailer now comes with a `#deliver_later` -method, which adds your email to be sent as a job to a queue, so it doesn't -bog down the controller or model. +Building on top of Active Job, Action Mailer now comes with a `deliver_later` +method that sends the email asynchronously via a job in a queue, so it doesn't +block 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 -Active Record object, and the object will be serialized using GlobalID, and -then deserialized again at run time. +The new [Global ID](https://github.com/rails/globalid) library makes it easy +to pass Active Record objects to jobs. The library stores a glogal URI that +uniquely represents the model without serializing its state. This means you no +longer have to manually pack and unpack your Active Records by passing ids. +Just give the job the Active Record object, its global ID will be stored, and +then the object transparently loaded for you from it. + +See the [Active Job Basics](active_job_basics.html) guide for more +information. ### Adequate Record @@ -56,39 +61,44 @@ common `find` and `find_by` calls and some association queries up to 2x faster. 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). +calls. For more details, please refer to [Aaron Patterson's blog +post](http://tenderlovemaking.com/2014/02/19/adequaterecord-pro-like-activerecord.html). -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: +Active Record will automatically take advantage of this feature on the +supported operations without any user involvement or code changes. Here are +some examples of the supported operations: ```ruby -Post.find 1 # First call will generate and cache the prepared statement -Post.find 2 # Second call will reuse the cached statement +Post.find(1) # First call generates and cache the prepared statement +Post.find(2) # Subsequent calls reuse the cached prepared statement -Post.find_by_title 'first post' -Post.find_by_title 'second post' +Post.find_by_title('first post') +Post.find_by_title('second post') post.comments post.comments(true) ``` +It's important to highlight that, as the examples above suggest, the prepared +statements do not cache the values passed in the method calls, they rather +have placeholders for them. + The caching is not used in the following scenarios: - The model has a default scope -- The model uses single table inheritance to inherit from another model -- `find` with a list of ids. eg: +- The model uses single table inheritance +- `find` with a list of ids, e.g.: ```ruby - Post.find(1,2,3) - OR - Post.find [1,2] + # not cached + Post.find(1, 2, 3) + Post.find([1,2]) ``` - `find_by` with SQL fragments: ```ruby - Post.find_by "published_at < ?", 2.weeks.ago + Post.find_by('published_at < ?', 2.weeks.ago) ``` ### Web Console @@ -96,11 +106,11 @@ The caching is not used in the following scenarios: 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 and a `console` view and controller +Web Console is a set of debugging tools for your Rails application. It adds an +interactive console on every error page and a `console` view and controller helper. -The interactive console on the error pages let you execute code where the +The interactive console on the error pages lets you execute code where the exception originated. It's quite handy being able to introspect the state that led to the error. @@ -110,7 +120,7 @@ the view where it is invoked. The `console` controller helper spawns an interactive console within the context of the controller action it was invoked in. -### Foreign key support +### Foreign Key Support The migration DSL now supports adding and removing foreign keys. They are dumped to `schema.rb` as well. At this time, only the `mysql`, `mysql2` and `postgresql` @@ -145,18 +155,18 @@ individual components for new deprecations in this release. The following changes may require immediate action upon upgrade. -### `render` with a String argument +### `render` with a String Argument -Previously, calling `render "foo/bar"` in a controller action is equivalent to +Previously, calling `render "foo/bar"` in a controller action was equivalent to `render file: "foo/bar"`. In Rails 4.2, this has been changed to mean `render template: "foo/bar"` instead. If you need to render a file, please change your code to use the explicit form (`render file: "foo/bar"`) instead. ### `respond_with` / class-level `respond_to` -`respond_with` and the corresponding class-level `respond_to` have been moved to -the `responders` gem. To use the following, add `gem 'responders', '~> 2.0'` to -your Gemfile: +`respond_with` and the corresponding class-level `respond_to` have been moved +to the [responders](https://github.com/plataformatec/responders) gem. Add +`gem 'responders', '~> 2.0'` to your Gemfile to use it: ```ruby # app/controllers/users_controller.rb @@ -187,17 +197,18 @@ class UsersController < ApplicationController end ``` -### Default host for `rails server` +### Default Host for `rails server` 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. -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. +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 +is in a virtual machine and you would like to access it from the host machine. +In such cases, please 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. @@ -205,28 +216,29 @@ trusted machines on your network can access your development server. ### HTML Sanitizer The HTML sanitizer has been replaced with a new, more robust, implementation -built upon Loofah and Nokogiri. The new sanitizer is more secure and its -sanitization is more powerful and flexible. +built upon [Loofah](https://github.com/flavorjones/loofah) and +[Nokogiri](https://github.com/sparklemotion/nokogiri). The new sanitizer is +more secure and its sanitization is more powerful and flexible. -With a new sanitization algorithm, the sanitized output will change for certain -pathological inputs. +Due to the new algorithm, sanitized output changes for certain pathological +inputs. -If you have particular need for the exact output of the old sanitizer, you can -add `rails-deprecated_sanitizer` to your Gemfile, and it will automatically -replace the new implementation. Because it is opt-in, the legacy gem will not -give deprecation warnings. +If you have a particular need for the exact output of the old sanitizer, you +can add the [rails-deprecated_sanitizer](https://github.com/kaspth/rails-deprecated_sanitizer) +gem to the `Gemfile`, to have the old behavior. The gem does not issue +deprecation warnings because it is opt-in. `rails-deprecated_sanitizer` will be supported for Rails 4.2 only; it will not be maintained for Rails 5.0. -See [the blog post](http://blog.plataformatec.com.br/2014/07/the-new-html-sanitizer-in-rails-4-2/) -for more detail on the changes in the new sanitizer. +See [this blog post](http://blog.plataformatec.com.br/2014/07/the-new-html-sanitizer-in-rails-4-2/) +for more details on the changes in the new sanitizer. ### `assert_select` -`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: +`assert_select` is now based on [Nokogiri](https://github.com/sparklemotion/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. @@ -347,15 +359,15 @@ Please refer to the [Changelog][railties] for detailed changes. ([Pull Request](https://github.com/rails/rails/pull/16129)) -* Introduce a `--skip-turbolinks` option in the app generator to not generate - any turbolinks integration. +* Introduced a `--skip-turbolinks` option in the app generator to not generate + turbolinks integration. ([Commit](https://github.com/rails/rails/commit/bf17c8a531bc8059d50ad731398002a3e7162a7d)) -* Introduced a `bin/setup` script to enable automated setup code when +* Introduced a `bin/setup` script as a convention for automated setup code when bootstrapping an application. ([Pull Request](https://github.com/rails/rails/pull/15189)) -* Changed default value for `config.assets.digest` to `true` in development. +* Changed the default value for `config.assets.digest` to `true` in development. ([Pull Request](https://github.com/rails/rails/pull/15155)) * Introduced an API to register new extensions for `rake notes`. @@ -376,7 +388,7 @@ Please refer to the [Changelog][action-pack] for detailed changes. ### Removals -* `respond_with` and the class-level `respond_to` were removed from Rails and +* `respond_with` and the class-level `respond_to` have been 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), @@ -396,7 +408,7 @@ Please refer to the [Changelog][action-pack] for detailed changes. ([Commit](https://github.com/rails/rails-dom-testing/commit/b12850bc5ff23ba4b599bf2770874dd4f11bf750)) * Deprecated support for setting the `:to` option of a router to a symbol or a - string that does not contain a `#` character: + string that does not contain a "#" character: ```ruby get '/posts', to: MyRackApp => (No change necessary) @@ -407,21 +419,22 @@ Please refer to the [Changelog][action-pack] for detailed changes. ([Commit](https://github.com/rails/rails/commit/cc26b6b7bccf0eea2e2c1a9ebdcc9d30ca7390d9)) -* Deprecated support for String keys in URL helpers: +* Deprecated support for string keys in URL helpers: ```ruby # bad - Rails.application.routes.url_helpers.root_path('controller' => 'posts', 'action' => 'index') + root_path('controller' => 'posts', 'action' => 'index') + # good - Rails.application.routes.url_helpers.root_path(controller: 'posts', action: 'index') + root_path(controller: 'posts', action: 'index') ``` ([Pull Request](https://github.com/rails/rails/pull/17743)) ### Notable changes -* The `*_filter` family methods have been removed from the documentation. Their - usage is discouraged in favor of the `*_action` family methods: +* The `*_filter` family of methods have been removed from the documentation. Their + usage is discouraged in favor of the `*_action` family of methods: ``` after_filter => after_action @@ -450,19 +463,18 @@ Please refer to the [Changelog][action-pack] for detailed changes. 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. +* Rails now automatically includes 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 +* Added the HTTP method `MKCALENDAR` from [RFC 4791](https://tools.ietf.org/html/rfc4791). ([Pull Request](https://github.com/rails/rails/pull/15121)) * `*_fragment.action_controller` notifications now include the controller @@ -484,7 +496,7 @@ Please refer to the [Changelog][action-pack] for detailed changes. ([Pull Request](https://github.com/rails/rails/pull/16466)) Action View -------------- +----------- Please refer to the [Changelog][action-view] for detailed changes. @@ -511,8 +523,8 @@ Please refer to the [Changelog][action-view] for detailed changes. * 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. + current state of the iteration via the `index`, `size`, `first?` and + `last?` methods. ([Pull Request](https://github.com/rails/rails/pull/7698)) * Placeholder I18n follows the same convention as `label` I18n. @@ -534,6 +546,10 @@ Please refer to the [Changelog][action-mailer] for detailed changes. ### Notable changes +* `link_to` and `url_for` generate absolute URLs by default in templates, + it is no longer needed to pass `only_path: false`. + ([Commit](https://github.com/rails/rails/commit/9685080a7677abfa5d288a81c3e078368c6bb67c)) + * Introduced `deliver_later` which enqueues a job on the application's queue to deliver emails asynchronously. ([Pull Request](https://github.com/rails/rails/pull/16485)) @@ -562,7 +578,7 @@ Please refer to the [Changelog][active-record] for detailed changes. * Removed unused `:timestamp` type. Transparently alias it to `:datetime` in all cases. Fixes inconsistencies when column types are sent outside of - `ActiveRecord`, such as for XML serialization. + Active Record, such as for XML serialization. ([Pull Request](https://github.com/rails/rails/pull/15184)) ### Deprecations @@ -577,20 +593,18 @@ Please refer to the [Changelog][active-record] for detailed changes. ([Pull Request](https://github.com/rails/rails/pull/15754)) * Deprecated passing Active Record objects to `.find` or `.exists?`. Call - `#id` on the objects first. + `id` on the objects first. (Commit [1](https://github.com/rails/rails/commit/d92ae6ccca3bcfd73546d612efaea011270bd270), [2](https://github.com/rails/rails/commit/d35f0033c7dec2b8d8b52058fb8db495d49596f7)) * Deprecated half-baked support for PostgreSQL range values with excluding beginnings. We currently map PostgreSQL ranges to Ruby ranges. This conversion - is not fully possible because the Ruby range does not support excluded - beginnings. + is not fully possible because Ruby ranges do not support excluded beginnings. The current solution of incrementing the beginning is not correct and is now deprecated. For subtypes where we don't know how to increment - (e.g. `#succ` is not defined) it will raise an `ArgumentError` for ranges + (e.g. `succ` is not defined) it will raise an `ArgumentError` for ranges with excluding beginnings. - ([Commit](https://github.com/rails/rails/commit/91949e48cf41af9f3e4ffba3e5eecf9b0a08bfc3)) * Deprecated calling `DatabaseTasks.load_schema` without a connection. Use @@ -598,7 +612,7 @@ Please refer to the [Changelog][active-record] for detailed changes. ([Commit](https://github.com/rails/rails/commit/f15cef67f75e4b52fd45655d7c6ab6b35623c608)) * Deprecated `sanitize_sql_hash_for_conditions` without replacement. Using a - `Relation` for performing queries and updates is the prefered API. + `Relation` for performing queries and updates is the preferred API. ([Commit](https://github.com/rails/rails/commit/d5902c9e)) * Deprecated `Reflection#source_macro` without replacement as it is no longer @@ -613,7 +627,7 @@ Please refer to the [Changelog][active-record] for detailed changes. ([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 + that depend 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)) @@ -624,62 +638,62 @@ Please refer to the [Changelog][active-record] for detailed changes. ([Pull Request](https://github.com/rails/rails/pull/16056)) * `ActiveRecord::Dirty` now detects in-place changes to mutable values. - Serialized attributes on Active Record models will no longer save when + Serialized attributes on Active Record models are no longer saved 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)) -* Introduced the `bin/rake db:purge` task to empty the database for the +* Introduced the `db:purge` Rake 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 +* Introduced `ActiveRecord::Base#validate!` that raises `ActiveRecord::RecordInvalid` if the record is invalid. ([Pull Request](https://github.com/rails/rails/pull/8639)) -* Introduced `#validate` as an alias for `#valid?`. +* 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. +* `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+. +* 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 +* The 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. +* Added support for the `citext` column type in the PostgreSQL adapter. ([Pull Request](https://github.com/rails/rails/pull/12523)) -* Added support for user-created range types in PostgreSQL adapter. +* Added support for user-created range types in the 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). + `some/path`. This behavior was deprecated on Rails 4.1). ([Pull Request](https://github.com/rails/rails/pull/14569)) * 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 `#pretty_print` in `ActiveRecord::Base` objects. +* Added `ActiveRecord::Base#pretty_print` to pretty print models. ([Pull Request](https://github.com/rails/rails/pull/15172)) * `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. + `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. +* `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 +* 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)) @@ -699,12 +713,12 @@ Please refer to the [Changelog][active-model] for detailed changes. ([Pull Request](https://github.com/rails/rails/pull/16180)) * Deprecated `ActiveModel::Dirty#reset_changes` in favor of - `#clear_changes_information`. + `clear_changes_information`. ([Pull Request](https://github.com/rails/rails/pull/16180)) ### Notable changes -* Introduced `#validate` as an alias for `#valid?`. +* 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 @@ -750,12 +764,12 @@ Please refer to the [Changelog][active-support] for detailed changes. ### Notable changes -* Introduced new configuration option `active_support.test_order` for +* Introduced a new configuration option `active_support.test_order` for specifying the order test cases are executed. This option currently defaults 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. +* `Object#try` and `Object#try!` can now be used without an explicit receiver in the block. ([Commit](https://github.com/rails/rails/commit/5e51bdda59c9ba8e5faf86294e3e431bd45f1830), [Pull Request](https://github.com/rails/rails/pull/17361)) @@ -766,7 +780,7 @@ Please refer to the [Changelog][active-support] for detailed changes. (Commit [1](https://github.com/rails/rails/commit/702ad710b57bef45b081ebf42e6fa70820fdd810), [2](https://github.com/rails/rails/commit/64d91122222c11ad3918cc8e2e3ebc4b0a03448a)) -* `Object#with_options` can now be used without an explicit receiver. +* `Object#with_options` can now be used without an explicit receiver in the block. ([Pull Request](https://github.com/rails/rails/pull/16339)) * Introduced `String#truncate_words` to truncate a string by a number of words. -- cgit v1.2.3 From 1154879e2f88f2c1e1523f413161c9fd175ff398 Mon Sep 17 00:00:00 2001 From: Felipe Zavan Date: Thu, 27 Nov 2014 00:23:55 -0200 Subject: Fix typo in Rails 4.2 release notes --- guides/source/4_2_release_notes.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 822a28bcd6..330db52e34 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -45,7 +45,7 @@ method that sends the email asynchronously via a job in a queue, so it doesn't block the controller or model. The new [Global ID](https://github.com/rails/globalid) library makes it easy -to pass Active Record objects to jobs. The library stores a glogal URI that +to pass Active Record objects to jobs. The library stores a global URI that uniquely represents the model without serializing its state. This means you no longer have to manually pack and unpack your Active Records by passing ids. Just give the job the Active Record object, its global ID will be stored, and -- cgit v1.2.3 From b4b6c556a7135f490720b55a916126ee88e326a6 Mon Sep 17 00:00:00 2001 From: Leandro Facchinetti Date: Wed, 26 Nov 2014 23:39:02 -0500 Subject: Fix format "Form Helpers" guide The `"_tag"` was interpreted as the start of a italics. --- guides/source/form_helpers.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/form_helpers.md b/guides/source/form_helpers.md index 9ced77dfd7..55244cae7a 100644 --- a/guides/source/form_helpers.md +++ b/guides/source/form_helpers.md @@ -96,7 +96,7 @@ form_tag({controller: "people", action: "search"}, method: "get", class: "nifty_ ### Helpers for Generating Form Elements -Rails provides a series of helpers for generating form elements such as checkboxes, text fields, and radio buttons. These basic helpers, with names ending in "_tag" (such as `text_field_tag` and `check_box_tag`), generate just a single `` element. The first parameter to these is always the name of the input. When the form is submitted, the name will be passed along with the form data, and will make its way to the `params` hash in the controller with the value entered by the user for that field. For example, if the form contains `<%= text_field_tag(:query) %>`, then you would be able to get the value of this field in the controller with `params[:query]`. +Rails provides a series of helpers for generating form elements such as checkboxes, text fields, and radio buttons. These basic helpers, with names ending in `_tag` (such as `text_field_tag` and `check_box_tag`), generate just a single `` element. The first parameter to these is always the name of the input. When the form is submitted, the name will be passed along with the form data, and will make its way to the `params` hash in the controller with the value entered by the user for that field. For example, if the form contains `<%= text_field_tag(:query) %>`, then you would be able to get the value of this field in the controller with `params[:query]`. When naming inputs, Rails uses certain conventions that make it possible to submit parameters with non-scalar values such as arrays or hashes, which will also be accessible in `params`. You can read more about them in [chapter 7 of this guide](#understanding-parameter-naming-conventions). For details on the precise usage of these helpers, please refer to the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html). -- cgit v1.2.3 From ec8edeca1d0778998e35a022464ec0f4348bd86e Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Thu, 27 Nov 2014 09:18:01 +0100 Subject: edits in the release notes for 4.2 --- guides/source/4_2_release_notes.md | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 330db52e34..329665d859 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -3,7 +3,8 @@ Ruby on Rails 4.2 Release Notes Highlights in Rails 4.2: -* Active Job, Action Mailer's `deliver_later` +* Active Job +* Asynchronous Mails * Adequate Record * Web Console * Foreign key support @@ -29,7 +30,7 @@ Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-4-1-to-rails-4-2). Major Features -------------- -### Active Job, Action Mailer's `deliver_later` +### Active Job Active Job is a new framework in Rails 4.2. It is a common interface on top of queuing systems like [Resque](https://github.com/resque/resque), [Delayed @@ -40,20 +41,25 @@ Jobs written with the Active Job API run on any of the supported queues thanks to their respective adapters. Active Job comes pre-configured with an inline runner that executes jobs right away. -Building on top of Active Job, Action Mailer now comes with a `deliver_later` -method that sends the email asynchronously via a job in a queue, so it doesn't -block the controller or model. - -The new [Global ID](https://github.com/rails/globalid) library makes it easy -to pass Active Record objects to jobs. The library stores a global URI that -uniquely represents the model without serializing its state. This means you no -longer have to manually pack and unpack your Active Records by passing ids. -Just give the job the Active Record object, its global ID will be stored, and -then the object transparently loaded for you from it. +Jobs often need to take Active Record objects as arguments, but we can't pass +fully-marshaled Ruby objects through many queueing systems. Active Job passes +object references as URIs (uniform resource identifiers) instead of marshaling +the object itself. The new [Global ID](https://github.com/rails/globalid) +library builds URIs and looks up the objects they reference. Passing Active +Record objects as job arguments "just works:" Active Job passes a reference to +the object, then looks up the object from its reference. See the [Active Job Basics](active_job_basics.html) guide for more information. +### Asynchronous Mails + +Building on top of Active Job, Action Mailer now comes with a `deliver_later` +method that sends emails via the queue, so it doesn't block the controller or +model if the queue is asynchronous (the default inline queue blocks). + +Sending emails right away is still possible with `deliver_now`. + ### Adequate Record Adequate Record is a set of performance improvements in Active Record that makes @@ -554,6 +560,10 @@ Please refer to the [Changelog][action-mailer] for detailed changes. to deliver emails asynchronously. ([Pull Request](https://github.com/rails/rails/pull/16485)) +* Introduced `deliver_now` to send emails right away, without going through + the application's queue. + ([Commit](https://github.com/rails/rails/commit/f4ee114746ddc68db606f63e17e6de28274fc2bd)) + * Added the `show_previews` configuration option for enabling mailer previews outside of the development environment. ([Pull Request](https://github.com/rails/rails/pull/15970)) -- cgit v1.2.3 From 71dc93be15823c5e8cf5fd8e62ad3eeef988495f Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Thu, 27 Nov 2014 09:21:38 +0100 Subject: removes double mention of deliver_now --- guides/source/4_2_release_notes.md | 4 ---- 1 file changed, 4 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 329665d859..c3803aa856 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -560,10 +560,6 @@ Please refer to the [Changelog][action-mailer] for detailed changes. to deliver emails asynchronously. ([Pull Request](https://github.com/rails/rails/pull/16485)) -* Introduced `deliver_now` to send emails right away, without going through - the application's queue. - ([Commit](https://github.com/rails/rails/commit/f4ee114746ddc68db606f63e17e6de28274fc2bd)) - * Added the `show_previews` configuration option for enabling mailer previews outside of the development environment. ([Pull Request](https://github.com/rails/rails/pull/15970)) -- cgit v1.2.3 From 4eefa1a0ac098c0391f305323fb1cf1c7495c907 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Thu, 27 Nov 2014 00:45:16 -0800 Subject: rails -> bin/rails in index.html --- railties/lib/rails/templates/rails/welcome/index.html.erb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/templates/rails/welcome/index.html.erb b/railties/lib/rails/templates/rails/welcome/index.html.erb index 89792066d5..6726c23fc9 100644 --- a/railties/lib/rails/templates/rails/welcome/index.html.erb +++ b/railties/lib/rails/templates/rails/welcome/index.html.erb @@ -237,7 +237,7 @@
  1. -

    Use rails generate to create your models and controllers

    +

    Use bin/rails generate to create your models and controllers

    To see all available options, run it without parameters.

  2. -- cgit v1.2.3 From 9e6733d5f7867717c760c1cf4b70c36318c28d67 Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Thu, 27 Nov 2014 21:27:34 +0900 Subject: Refactor `SchemaCreation#visit_AddColumn` --- .../active_record/connection_adapters/abstract/schema_creation.rb | 4 +--- .../connection_adapters/postgresql/schema_statements.rb | 6 ------ 2 files changed, 1 insertion(+), 9 deletions(-) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb index 6bab260f5a..792d49da6f 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb @@ -15,9 +15,7 @@ module ActiveRecord end def visit_AddColumn(o) - sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale) - sql = "ADD #{quote_column_name(o.name)} #{sql_type}" - add_column_options!(sql, column_options(o)) + "ADD #{accept(o)}" end private 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 193c950261..dba905ed56 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -4,12 +4,6 @@ module ActiveRecord class SchemaCreation < AbstractAdapter::SchemaCreation private - def visit_AddColumn(o) - sql_type = type_to_sql(o.type, o.limit, o.precision, o.scale) - sql = "ADD COLUMN #{quote_column_name(o.name)} #{sql_type}" - add_column_options!(sql, column_options(o)) - end - def visit_ColumnDefinition(o) sql = super if o.primary_key? && o.type != :primary_key -- cgit v1.2.3 From fd8cbcef731476fc5902a2d8be973bc51e11f828 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Thu, 27 Nov 2014 13:40:27 +0100 Subject: updates some pointers in the guides welcome section [ci skip] --- guides/source/_welcome.html.erb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/_welcome.html.erb b/guides/source/_welcome.html.erb index f2315bfe22..614d69ecdd 100644 --- a/guides/source/_welcome.html.erb +++ b/guides/source/_welcome.html.erb @@ -15,5 +15,5 @@

    <% end %>

    - The guides for earlier releases: Rails 4.1.6, Rails 4.0.10, Rails 3.2.19 and Rails 2.3.11. + The guides for earlier releases: Rails 4.1.8, Rails 4.0.12, Rails 3.2.21 and Rails 2.3.11.

    -- cgit v1.2.3 From 07f4bd5b60d062bda58a45ca5f832a0a6bcdc713 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Thu, 27 Nov 2014 13:50:10 -0200 Subject: StatementCache is private API It should not be used in applications --- activerecord/lib/active_record/statement_cache.rb | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/activerecord/lib/active_record/statement_cache.rb b/activerecord/lib/active_record/statement_cache.rb index aece446384..767c7561cf 100644 --- a/activerecord/lib/active_record/statement_cache.rb +++ b/activerecord/lib/active_record/statement_cache.rb @@ -13,10 +13,10 @@ module ActiveRecord # # The relation returned by the block is cached, and for each +execute+ call the cached relation gets duped. # Database is queried when +to_a+ is called on the relation. - class StatementCache - class Substitute; end + class StatementCache # :nodoc: + class Substitute; end # :nodoc: - class Query + class Query # :nodoc: def initialize(sql) @sql = sql end @@ -26,7 +26,7 @@ module ActiveRecord end end - class PartialQuery < Query + class PartialQuery < Query # :nodoc: def initialize values @values = values @indexes = values.each_with_index.find_all { |thing,i| @@ -51,11 +51,11 @@ module ActiveRecord PartialQuery.new collected end - class Params + class Params # :nodoc: def bind; Substitute.new; end end - class BindMap + class BindMap # :nodoc: def initialize(bind_values) @indexes = [] @bind_values = bind_values -- cgit v1.2.3 From e2cce6cd4138848bbfbac0ea3e48ee9388f966e1 Mon Sep 17 00:00:00 2001 From: Jon Atack Date: Thu, 27 Nov 2014 17:36:15 +0100 Subject: Action Mailer change log pass [skip ci] --- actionmailer/CHANGELOG.md | 43 +++++++++++++++++++++---------------------- 1 file changed, 21 insertions(+), 22 deletions(-) diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md index 9fdda52f77..8d4164ee62 100644 --- a/actionmailer/CHANGELOG.md +++ b/actionmailer/CHANGELOG.md @@ -1,44 +1,42 @@ -* MailerGenerator now generates layouts by default. HTML mailer layout will - include `` and `` tags which will help to reduce spam score in - some spam detection engines. Mailers will now inherit from `ApplicationMailer` +* `MailerGenerator` now generates layouts by default. The HTML mailer layout + now includes `` and `` tags which improve the spam rating in + some spam detection engines. Mailers 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`. +* `link_to` and `url_for` now generate URLs by default in templates. + Passing `only_path: false` is longer needed. Fixes #16497 and #16589. *Xavier Noria*, *Richard Schneeman* -* Attachments can be added while rendering the mail template. +* Attachments can now be added while rendering the mail template. Fixes #16974. *Christian Felder* -* Added `#deliver_later`, `#deliver_now` and deprecate `#deliver` in favour of - `#deliver_now`. `#deliver_later` will enqueue a job to render and deliver - the mail instead of delivering it right at that moment. The job is enqueued - using the new Active Job framework in Rails, and will use whatever queue is - configured for Rails. +* Add `#deliver_later` and `#deliver_now` methods and deprecate `#deliver` in + favor of `#deliver_now`. `#deliver_later` will enqueue a job to render and + deliver the mail instead of delivering it immediately. The job is enqueued + using the new Active Job framework in Rails and will use the queue that you + have configured in Rails. *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 - are called. +* `ActionMailer::Previews` are now class methods instead of instance methods. *Cristian Bica* -* Deprecate `*_path` helpers in email views. When used they generate - non-working links and are not the intention of most developers. Instead - we recommend to use `*_url` helper. +* Deprecate `*_path` helpers in email views. They generated broken + links and were not the intention of most developers. The `*_url` + helper is recommended instead. *Richard Schneeman* -* Raise an exception when attachments are added after `mail` was called. +* Raise an exception when attachments are added after `mail` is called. This is a safeguard to prevent invalid emails. Fixes #16163. @@ -47,10 +45,10 @@ * Add `config.action_mailer.show_previews` configuration option. - This config option can be used to enable the mail preview in environments - other than development (such as staging). + This configuration option can be used to enable the mail preview in + environments other than development (such as staging). - Defaults to `true` in development and false elsewhere. + Defaults to `true` in development and `false` elsewhere. *Leonard Garvey* @@ -61,4 +59,5 @@ *Yves Senn* -Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/actionmailer/CHANGELOG.md) for previous changes. +Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/actionmailer/CHANGELOG.md) +for previous changes. -- cgit v1.2.3 From 8fc7eb5f21e42f1bc484c496a6431c284b9ee805 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Thu, 27 Nov 2014 14:40:19 -0200 Subject: Update the StatementCache documentation --- activerecord/lib/active_record/statement_cache.rb | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/activerecord/lib/active_record/statement_cache.rb b/activerecord/lib/active_record/statement_cache.rb index 767c7561cf..c68990bf99 100644 --- a/activerecord/lib/active_record/statement_cache.rb +++ b/activerecord/lib/active_record/statement_cache.rb @@ -1,18 +1,29 @@ module ActiveRecord # Statement cache is used to cache a single statement in order to avoid creating the AST again. - # Initializing the cache is done by passing the statement in the initialization block: + # Initializing the cache is done by passing the statement in the create block: # - # cache = ActiveRecord::StatementCache.new do - # Book.where(name: "my book").limit(100) + # cache = StatementCache.create(Book.connection) do |params| + # Book.where(name: "my book").where("author_id > 3") # end # # The cached statement is executed by using the +execute+ method: # - # cache.execute + # cache.execute([], Book, Book.connection) # # The relation returned by the block is cached, and for each +execute+ call the cached relation gets duped. # Database is queried when +to_a+ is called on the relation. + # + # If you want to cache the statement without the values you can use the +bind+ method of the + # block parameter. + # + # cache = StatementCache.create(Book.connection) do |params| + # Book.where(name: params.bind) + # end + # + # And pass the bind values as the first argument of +execute+ call. + # + # cache.execute(["my book"], Book, Book.connection) class StatementCache # :nodoc: class Substitute; end # :nodoc: -- cgit v1.2.3 From e2a01aef4227525eece03a922a3d37f6785376ed Mon Sep 17 00:00:00 2001 From: Zachary Scott Date: Thu, 27 Nov 2014 08:43:37 -0800 Subject: Fix CHANGELOG typo introduced in e2cce6cd [ci skip] --- actionmailer/CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md index 8d4164ee62..968a21ea32 100644 --- a/actionmailer/CHANGELOG.md +++ b/actionmailer/CHANGELOG.md @@ -6,7 +6,7 @@ *Andy Jeffries* * `link_to` and `url_for` now generate URLs by default in templates. - Passing `only_path: false` is longer needed. + Passing `only_path: false` is no longer needed. Fixes #16497 and #16589. -- cgit v1.2.3 From d21d8f903ddd4c655a74909ef4d12fbcdeaa006e Mon Sep 17 00:00:00 2001 From: Jon Atack Date: Thu, 27 Nov 2014 17:46:56 +0100 Subject: Follow-up to e2cce6c [skip ci] --- actionmailer/CHANGELOG.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md index 968a21ea32..c8b969c59a 100644 --- a/actionmailer/CHANGELOG.md +++ b/actionmailer/CHANGELOG.md @@ -30,8 +30,8 @@ *Cristian Bica* -* Deprecate `*_path` helpers in email views. They generated broken - links and were not the intention of most developers. The `*_url` +* Deprecate `*_path` helpers in email views. They generated broken links in + email views and were not the intention of most developers. The `*_url` helper is recommended instead. *Richard Schneeman* -- cgit v1.2.3 From 263e9e468172b0f7ab6d048af260b0b50c2afa1c Mon Sep 17 00:00:00 2001 From: Aaron Huang Date: Fri, 28 Nov 2014 01:34:33 +0800 Subject: [ci skip] Remove outdate note of :dependent --- guides/source/association_basics.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/guides/source/association_basics.md b/guides/source/association_basics.md index 61490ceb54..a12f5638e3 100644 --- a/guides/source/association_basics.md +++ b/guides/source/association_basics.md @@ -1532,8 +1532,6 @@ Controls what happens to the associated objects when their owner is destroyed: * `:restrict_with_exception` causes an exception to be raised if there are any associated records * `:restrict_with_error` causes an error to be added to the owner if there are any associated objects -NOTE: This option is ignored when you use the `:through` option on the association. - ##### `:foreign_key` By convention, Rails assumes that the column used to hold the foreign key on the other model is the name of this model with the suffix `_id` added. The `:foreign_key` option lets you set the name of the foreign key directly: -- cgit v1.2.3 From 2e4c9c2ee53c29602d3b5c6bc83403d3b48b3f13 Mon Sep 17 00:00:00 2001 From: Abdelkader Boudih Date: Thu, 27 Nov 2014 18:21:43 +0000 Subject: Merge pull request #17803 from sadfuzzy/patch-2 Update cookies.rb Conflicts: actionpack/lib/action_dispatch/middleware/cookies.rb --- actionpack/lib/action_dispatch/middleware/cookies.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index 9037bf0e0a..c9fff081d6 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -71,11 +71,13 @@ module ActionDispatch # restrict to the domain level. If you use a schema like www.example.com # and want to share session with user.example.com set :domain # to :all. Make sure to specify the :domain option with - # :all again when deleting cookies. + # :all or Array again when deleting cookies. # # domain: nil # Does not sets cookie domain. (default) # domain: :all # Allow the cookie for the top most level # # domain and subdomains. + # domain: %w(.example.com .example.org) # Allow the cookie + # # for concrete domain names. # # * :expires - The time at which this cookie expires, as a \Time object. # * :secure - Whether this cookie is only transmitted to HTTPS servers. -- cgit v1.2.3 From 31815d7167404557524712c665dda83505c094be Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Thu, 27 Nov 2014 16:53:27 -0200 Subject: Revert "Test against rack master" This reverts commit 2a4e14db981e38611667d407a975600ee720ada7. --- Gemfile | 2 -- railties/lib/rails/generators/app_base.rb | 4 ++-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Gemfile b/Gemfile index f1650ce7d3..99e2cb9f58 100644 --- a/Gemfile +++ b/Gemfile @@ -2,8 +2,6 @@ source 'https://rubygems.org' gemspec -gem 'rack', github: 'rack/rack' - # We need a newish Rake since Active Job sets its test tasks' descriptions. gem 'rake', '>= 10.3' diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index b410363f2f..0823b0cc46 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -195,9 +195,9 @@ module Rails def rails_gemfile_entry if options.dev? - [GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH), GemfileEntry.github('rack', 'rack/rack')] + [GemfileEntry.path('rails', Rails::Generators::RAILS_DEV_PATH)] elsif options.edge? - [GemfileEntry.github('rails', 'rails/rails'), GemfileEntry.github('rack', 'rack/rack')] + [GemfileEntry.github('rails', 'rails/rails')] else [GemfileEntry.version('rails', Rails::VERSION::STRING, -- cgit v1.2.3 From 5ac824ecb7bf20f332cbb1c50ab7d9185c124f8c Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Thu, 27 Nov 2014 16:54:44 -0200 Subject: Bump to rack 1.6.0.beta2 --- actionpack/actionpack.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index 1e68d1870d..0a49a653d9 100644 --- a/actionpack/actionpack.gemspec +++ b/actionpack/actionpack.gemspec @@ -21,7 +21,7 @@ Gem::Specification.new do |s| s.add_dependency 'activesupport', version - s.add_dependency 'rack', '~> 1.6.0.beta' + s.add_dependency 'rack', '~> 1.6.0.beta2' 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.5' -- cgit v1.2.3 From 8fb239633108210506241c4aa45827b63c20d97f Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Thu, 27 Nov 2014 22:17:30 +0100 Subject: release notes: iteration over the description of Global ID [ci skip] --- guides/source/4_2_release_notes.md | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index c3803aa856..01981e5741 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -41,13 +41,23 @@ Jobs written with the Active Job API run on any of the supported queues thanks to their respective adapters. Active Job comes pre-configured with an inline runner that executes jobs right away. -Jobs often need to take Active Record objects as arguments, but we can't pass -fully-marshaled Ruby objects through many queueing systems. Active Job passes +Jobs often need to take Active Record objects as arguments. Active Job passes object references as URIs (uniform resource identifiers) instead of marshaling the object itself. The new [Global ID](https://github.com/rails/globalid) library builds URIs and looks up the objects they reference. Passing Active -Record objects as job arguments "just works:" Active Job passes a reference to -the object, then looks up the object from its reference. +Record objects as job arguments just works by using Global ID internally. + +For example, if `trashable` is an AR this job runs just fine + +```ruby +class TrashableCleanupJob < ActiveJob::Base + def perform(trashable, depth) + trashable.cleanup(depth) + end +end +``` + +with no serialization involved. See the [Active Job Basics](active_job_basics.html) guide for more information. -- cgit v1.2.3 From bba5a709dfa453f8bf941d277941bdbacdfbcf12 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Thu, 27 Nov 2014 14:54:09 -0800 Subject: release notes: edit pass [ci skip] --- guides/source/4_2_release_notes.md | 36 +++++++++++++++++------------------- 1 file changed, 17 insertions(+), 19 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 01981e5741..848a125bbc 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -4,7 +4,7 @@ Ruby on Rails 4.2 Release Notes Highlights in Rails 4.2: * Active Job -* Asynchronous Mails +* Asynchronous mails * Adequate Record * Web Console * Foreign key support @@ -119,22 +119,15 @@ The caching is not used in the following scenarios: ### Web Console -New applications generated from Rails 4.2 now come with the Web Console gem by -default. +New applications generated from Rails 4.2 now come with the [Web +Console](https://github.com/rails/web-console) gem by default. Web Console adds +an interactive Ruby console on every error page and provides a `console` view +and controller helpers. -Web Console is a set of debugging tools for your Rails application. It adds 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 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. - -The `console` controller helper spawns an interactive console within the -context of the controller action it was invoked in. +The interactive console on error pages lets you execute code in the context of +the place where the exception originated. The `console` helper, if called +anywhere in a view or controller, launches an interactive console with the final +context, once rendering has completed. ### Foreign Key Support @@ -178,7 +171,7 @@ Previously, calling `render "foo/bar"` in a controller action was equivalent to instead. If you need to render a file, please change your code to use the explicit form (`render file: "foo/bar"`) instead. -### `respond_with` / class-level `respond_to` +### `respond_with` / Class-Level `respond_to` `respond_with` and the corresponding class-level `respond_to` have been moved to the [responders](https://github.com/plataformatec/responders) gem. Add @@ -260,8 +253,13 @@ application is using any of these spellings, you will need to update them: non-alphanumeric characters. ``` - a[href=/] => a[href="/"] - a[href$=/] => a[href$="/"] + # before + a[href=/] + a[href$=/] + + # now + a[href="/"] + a[href$="/"] ``` * DOMs built from HTML source containing invalid HTML with improperly -- cgit v1.2.3 From 5142d5411481c893f817c1431b0869be3745060f Mon Sep 17 00:00:00 2001 From: Yuki Nishijima Date: Thu, 27 Nov 2014 17:44:36 -0800 Subject: Fix a bug where AR::RecordNotSaved loses error messages Since 3e30c5d, it started ignoring the given error message. This commit changes the behavior of AR::RecordNotSaved#initialize so that it no longer loses the given error message. --- activerecord/lib/active_record/errors.rb | 4 ++-- activerecord/lib/active_record/persistence.rb | 2 +- .../cases/associations/has_many_associations_test.rb | 17 +++++++++++++---- .../associations/has_many_through_associations_test.rb | 7 +++++-- .../cases/associations/has_one_associations_test.rb | 13 ++++++++++--- 5 files changed, 31 insertions(+), 12 deletions(-) diff --git a/activerecord/lib/active_record/errors.rb b/activerecord/lib/active_record/errors.rb index 14819aab54..fc28ab585f 100644 --- a/activerecord/lib/active_record/errors.rb +++ b/activerecord/lib/active_record/errors.rb @@ -54,9 +54,9 @@ module ActiveRecord class RecordNotSaved < ActiveRecordError attr_reader :record - def initialize(record) + def initialize(message, record = nil) @record = record - super() + super(message) end end diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb index 8d84a3acae..99e104598b 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, self) + create_or_update || raise(RecordNotSaved.new(nil, self)) end # Deletes the record in the database and freezes this instance to diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 8b7ab11570..9510d57de6 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -589,17 +589,21 @@ class HasManyAssociationsTest < ActiveRecord::TestCase end def test_create_with_bang_on_has_many_when_parent_is_new_raises - assert_raise(ActiveRecord::RecordNotSaved) do + error = assert_raise(ActiveRecord::RecordNotSaved) do firm = Firm.new firm.plain_clients.create! :name=>"Whoever" end + + assert_equal "You cannot call create unless the parent is saved", error.message end def test_regular_create_on_has_many_when_parent_is_new_raises - assert_raise(ActiveRecord::RecordNotSaved) do + error = assert_raise(ActiveRecord::RecordNotSaved) do firm = Firm.new firm.plain_clients.create :name=>"Whoever" end + + assert_equal "You cannot call create unless the parent is saved", error.message end def test_create_with_bang_on_has_many_raises_when_record_not_saved @@ -610,9 +614,11 @@ class HasManyAssociationsTest < ActiveRecord::TestCase end def test_create_with_bang_on_habtm_when_parent_is_new_raises - assert_raise(ActiveRecord::RecordNotSaved) do + error = assert_raise(ActiveRecord::RecordNotSaved) do Developer.new("name" => "Aredridel").projects.create! end + + assert_equal "You cannot call create unless the parent is saved", error.message end def test_adding_a_mismatch_class @@ -1353,10 +1359,13 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert !account.valid? assert !orig_accounts.empty? - assert_raise ActiveRecord::RecordNotSaved do + error = assert_raise ActiveRecord::RecordNotSaved do firm.accounts = [account] end + assert_equal orig_accounts, firm.accounts + assert_equal "Failed to replace accounts because one or more of the " \ + "new records could not be saved.", error.message end def test_replace_with_same_content 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 df4a30ae9b..d523ea4f07 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -615,8 +615,11 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase def test_create_on_new_record p = Post.new - assert_raises(ActiveRecord::RecordNotSaved) { p.people.create(:first_name => "mew") } - assert_raises(ActiveRecord::RecordNotSaved) { p.people.create!(:first_name => "snow") } + error = assert_raises(ActiveRecord::RecordNotSaved) { p.people.create(:first_name => "mew") } + assert_equal "You cannot call create unless the parent is saved", error.message + + error = assert_raises(ActiveRecord::RecordNotSaved) { p.people.create!(:first_name => "snow") } + assert_equal "You cannot call create unless the parent is saved", error.message end def test_associate_with_create_and_invalid_options diff --git a/activerecord/test/cases/associations/has_one_associations_test.rb b/activerecord/test/cases/associations/has_one_associations_test.rb index 2ecfcb521d..1a6d25f7d0 100644 --- a/activerecord/test/cases/associations/has_one_associations_test.rb +++ b/activerecord/test/cases/associations/has_one_associations_test.rb @@ -410,9 +410,11 @@ class HasOneAssociationsTest < ActiveRecord::TestCase pirate = pirates(:redbeard) new_ship = Ship.new - assert_raise(ActiveRecord::RecordNotSaved) do + error = assert_raise(ActiveRecord::RecordNotSaved) do pirate.ship = new_ship end + + assert_equal "Failed to save the new associated ship.", error.message assert_nil pirate.ship assert_nil new_ship.pirate_id end @@ -422,20 +424,25 @@ class HasOneAssociationsTest < ActiveRecord::TestCase pirate.ship.name = nil assert !pirate.ship.valid? - assert_raise(ActiveRecord::RecordNotSaved) do + error = assert_raise(ActiveRecord::RecordNotSaved) do pirate.ship = ships(:interceptor) end + assert_equal ships(:black_pearl), pirate.ship assert_equal pirate.id, pirate.ship.pirate_id + assert_equal "Failed to remove the existing associated ship. " + + "The record failed to save after its foreign key was set to nil.", error.message end def test_replacement_failure_due_to_new_record_should_raise_error pirate = pirates(:blackbeard) new_ship = Ship.new - assert_raise(ActiveRecord::RecordNotSaved) do + error = assert_raise(ActiveRecord::RecordNotSaved) do pirate.ship = new_ship end + + assert_equal "Failed to save the new associated ship.", error.message assert_equal ships(:black_pearl), pirate.ship assert_equal pirate.id, pirate.ship.pirate_id assert_equal pirate.id, ships(:black_pearl).reload.pirate_id -- cgit v1.2.3 From 91fca372b14b553a8029d81213ff51c8f3cde39b Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Thu, 27 Nov 2014 21:56:44 +0900 Subject: Refactor `add_column_options!`, to move the quoting of default value for :uuid in `quote_value`. --- .../connection_adapters/postgresql/schema_statements.rb | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) 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 193c950261..89b7f0a6b7 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -19,14 +19,22 @@ module ActiveRecord sql end + def column_options(o) + column_options = super + column_options[:array] = o.array + column_options + end + def add_column_options!(sql, options) - if options[:array] || options[:column].try(:array) + if options[:array] sql << '[]' end + super + end - column = options.fetch(:column) { return super } - if column.type == :uuid && options[:default] =~ /\(\)/ - sql << " DEFAULT #{options[:default]}" + def quote_value(value, column) + if column.type == :uuid && value =~ /\(\)/ + value else super end -- cgit v1.2.3 From 66cc7ce67c4f48f62377ad1a972581c35bcc8373 Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Fri, 28 Nov 2014 17:30:55 +0900 Subject: Rename to `quote_default_expression` from `quote_value` --- .../lib/active_record/connection_adapters/abstract/schema_creation.rb | 4 ++-- .../active_record/connection_adapters/postgresql/schema_statements.rb | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb index 6bab260f5a..6a684a33f8 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_creation.rb @@ -83,7 +83,7 @@ module ActiveRecord end def add_column_options!(sql, options) - sql << " DEFAULT #{quote_value(options[:default], options[:column])}" if options_include_default?(options) + sql << " DEFAULT #{quote_default_expression(options[:default], options[:column])}" if options_include_default?(options) # must explicitly check for :null to allow change_column to work on migrations if options[:null] == false sql << " NOT NULL" @@ -94,7 +94,7 @@ module ActiveRecord sql end - def quote_value(value, column) + def quote_default_expression(value, column) column.sql_type ||= type_to_sql(column.type, column.limit, column.precision, column.scale) column.cast_type ||= type_for_column(column) 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 89b7f0a6b7..009b7cd682 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb @@ -32,7 +32,7 @@ module ActiveRecord super end - def quote_value(value, column) + def quote_default_expression(value, column) if column.type == :uuid && value =~ /\(\)/ value else -- cgit v1.2.3 From 6c83d4bfd5e33bde5d659fcbe6f28bfe80d8eb4a Mon Sep 17 00:00:00 2001 From: Yves Senn Date: Fri, 28 Nov 2014 11:03:52 +0100 Subject: docs, AR no longer makes use of `test:prepare`. [ci skip] Change originated from https://github.com/rails/rails/pull/17739#issuecomment-64829088 /cc @metaskills --- railties/lib/rails/test_unit/testing.rake | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/railties/lib/rails/test_unit/testing.rake b/railties/lib/rails/test_unit/testing.rake index 0d0cfa3c6b..254ea9ecf6 100644 --- a/railties/lib/rails/test_unit/testing.rake +++ b/railties/lib/rails/test_unit/testing.rake @@ -10,7 +10,8 @@ end namespace :test do task :prepare do - # Placeholder task for other Railtie and plugins to enhance. See Active Record for an example. + # Placeholder task for other Railtie and plugins to enhance. + # If used with Active Record, this task runs before the database schema is synchronized. end Rails::TestTask.new(:run) do |t| -- cgit v1.2.3 From 075b8bd9d27f714f1f2a528ab3abde3a00d63ead Mon Sep 17 00:00:00 2001 From: Iain Beeston Date: Fri, 28 Nov 2014 11:24:37 +0000 Subject: Removed ecosystem link from the header of the guides pages --- guides/source/layout.html.erb | 1 - 1 file changed, 1 deletion(-) diff --git a/guides/source/layout.html.erb b/guides/source/layout.html.erb index 0513066f5a..69440d9d7a 100644 --- a/guides/source/layout.html.erb +++ b/guides/source/layout.html.erb @@ -36,7 +36,6 @@
  3. Code
  4. Screencasts
  5. Documentation
  6. -
  7. Ecosystem
  8. Community
  9. Blog
  10. -- cgit v1.2.3 From 6405a03c1303c4c2da7029cf9199bd17451fec4d Mon Sep 17 00:00:00 2001 From: Thorsten Ball Date: Fri, 28 Nov 2014 13:34:38 +0100 Subject: Adds preloaded_records method to NullPreloader This fixes a regression where preloading association throws an exception if one of the associations in the preloading hash doesn't exist for one record. Fixes #16070 --- activerecord/lib/active_record/associations/preloader.rb | 1 + activerecord/test/cases/associations/eager_test.rb | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/activerecord/lib/active_record/associations/preloader.rb b/activerecord/lib/active_record/associations/preloader.rb index 46bccbf15a..4358f3b581 100644 --- a/activerecord/lib/active_record/associations/preloader.rb +++ b/activerecord/lib/active_record/associations/preloader.rb @@ -178,6 +178,7 @@ module ActiveRecord class NullPreloader def self.new(klass, owners, reflection, preload_scope); self; end def self.run(preloader); end + def self.preloaded_records; []; end end def preloader_for(reflection, owners, rhs_klass) diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index dd4f530791..f968a34886 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -270,6 +270,14 @@ class EagerAssociationTest < ActiveRecord::TestCase end end + def test_three_level_nested_preloading_does_not_raise_exception_when_association_does_not_exist + post_id = Comment.where(author_id: nil).where.not(post_id: nil).first.post_id + + assert_nothing_raised do + Post.preload(:comments => [{:author => :essays}]).find(post_id) + end + end + def test_nested_loading_through_has_one_association aa = AuthorAddress.all.merge!(:includes => {:author => :posts}).find(author_addresses(:david_address).id) assert_equal aa.author.posts.count, aa.author.posts.length -- cgit v1.2.3 From acbc7a0d46b3a0e0736c9938609fb437c8978e93 Mon Sep 17 00:00:00 2001 From: Jon Atack Date: Fri, 28 Nov 2014 14:18:44 +0100 Subject: 4.2 release notes pass [skip ci] --- guides/source/4_2_release_notes.md | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/guides/source/4_2_release_notes.md b/guides/source/4_2_release_notes.md index 848a125bbc..737922c283 100644 --- a/guides/source/4_2_release_notes.md +++ b/guides/source/4_2_release_notes.md @@ -47,7 +47,8 @@ the object itself. The new [Global ID](https://github.com/rails/globalid) library builds URIs and looks up the objects they reference. Passing Active Record objects as job arguments just works by using Global ID internally. -For example, if `trashable` is an AR this job runs just fine +For example, if `trashable` is an Active Record object, then this job runs +just fine with no serialization involved: ```ruby class TrashableCleanupJob < ActiveJob::Base @@ -57,8 +58,6 @@ class TrashableCleanupJob < ActiveJob::Base end ``` -with no serialization involved. - See the [Active Job Basics](active_job_basics.html) guide for more information. @@ -80,9 +79,9 @@ 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). -Active Record will automatically take advantage of this feature on the +Active Record will automatically take advantage of this feature on supported operations without any user involvement or code changes. Here are -some examples of the supported operations: +some examples of supported operations: ```ruby Post.find(1) # First call generates and cache the prepared statement @@ -96,10 +95,10 @@ post.comments(true) ``` It's important to highlight that, as the examples above suggest, the prepared -statements do not cache the values passed in the method calls, they rather +statements do not cache the values passed in the method calls; rather, they have placeholders for them. -The caching is not used in the following scenarios: +Caching is not used in the following scenarios: - The model has a default scope - The model uses single table inheritance @@ -119,7 +118,7 @@ The caching is not used in the following scenarios: ### Web Console -New applications generated from Rails 4.2 now come with the [Web +New applications generated with Rails 4.2 now come with the [Web Console](https://github.com/rails/web-console) gem by default. Web Console adds an interactive Ruby console on every error page and provides a `console` view and controller helpers. @@ -167,9 +166,9 @@ The following changes may require immediate action upon upgrade. ### `render` with a String Argument Previously, calling `render "foo/bar"` in a controller action was equivalent to -`render file: "foo/bar"`. In Rails 4.2, this has been changed to mean `render template: "foo/bar"` -instead. If you need to render a file, please change your code to use the -explicit form (`render file: "foo/bar"`) instead. +`render file: "foo/bar"`. In Rails 4.2, this has been changed to mean +`render template: "foo/bar"` instead. If you need to render a file, please +change your code to use the explicit form (`render file: "foo/bar"`) instead. ### `respond_with` / Class-Level `respond_to` @@ -210,8 +209,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 will continue to work as before on your own machine. +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. 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 @@ -229,8 +229,8 @@ built upon [Loofah](https://github.com/flavorjones/loofah) and [Nokogiri](https://github.com/sparklemotion/nokogiri). The new sanitizer is more secure and its sanitization is more powerful and flexible. -Due to the new algorithm, sanitized output changes for certain pathological -inputs. +Due to the new algorithm, the sanitized output may be different for certain +pathological inputs. If you have a particular need for the exact output of the old sanitizer, you can add the [rails-deprecated_sanitizer](https://github.com/kaspth/rails-deprecated_sanitizer) @@ -663,8 +663,8 @@ Please refer to the [Changelog][active-record] for detailed changes. current environment. ([Commit](https://github.com/rails/rails/commit/e2f232aba15937a4b9d14bd91e0392c6d55be58d)) -* Introduced `ActiveRecord::Base#validate!` that raises `ActiveRecord::RecordInvalid` if the - record is invalid. +* Introduced `ActiveRecord::Base#validate!` that raises + `ActiveRecord::RecordInvalid` if the record is invalid. ([Pull Request](https://github.com/rails/rails/pull/8639)) * Introduced `validate` as an alias for `valid?`. @@ -704,8 +704,8 @@ Please refer to the [Changelog][active-record] for detailed changes. `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)) +* `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`). -- cgit v1.2.3 From f25ad07f5ade46eb978fa82658463232d0247c65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Fri, 28 Nov 2014 15:00:06 -0200 Subject: Start Rails 5 development :tada: We will support only Ruby >= 2.1. But right now we don't accept pull requests with syntax changes to drop support to Ruby 1.9. --- .travis.yml | 6 - RAILS_VERSION | 2 +- actionmailer/CHANGELOG.md | 64 +- actionmailer/lib/action_mailer/gem_version.rb | 6 +- actionpack/CHANGELOG.md | 411 +------ actionpack/lib/action_pack/gem_version.rb | 6 +- actionview/CHANGELOG.md | 219 +--- actionview/lib/action_view/gem_version.rb | 6 +- activejob/CHANGELOG.md | 2 +- activejob/lib/active_job/gem_version.rb | 6 +- activemodel/CHANGELOG.md | 62 +- activemodel/lib/active_model/gem_version.rb | 6 +- activerecord/CHANGELOG.md | 1337 +---------------------- activerecord/lib/active_record/gem_version.rb | 6 +- activesupport/CHANGELOG.md | 389 +------ activesupport/lib/active_support/gem_version.rb | 6 +- guides/CHANGELOG.md | 28 +- railties/CHANGELOG.md | 209 +--- railties/lib/rails/gem_version.rb | 6 +- version.rb | 6 +- 20 files changed, 37 insertions(+), 2746 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2823a5456f..7adde8971e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,18 +16,12 @@ env: - "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 - env: "GEM=ar:mysql" - - rvm: 2.0.0 - env: "GEM=ar:mysql" - rvm: ruby-head env: "GEM=ar:mysql" - rvm: rbx-2 diff --git a/RAILS_VERSION b/RAILS_VERSION index b86dc8c0c6..2b915d7d5c 100644 --- a/RAILS_VERSION +++ b/RAILS_VERSION @@ -1 +1 @@ -4.2.0.beta4 +5.0.0.alpha diff --git a/actionmailer/CHANGELOG.md b/actionmailer/CHANGELOG.md index c8b969c59a..88b0962e8c 100644 --- a/actionmailer/CHANGELOG.md +++ b/actionmailer/CHANGELOG.md @@ -1,63 +1 @@ -* `MailerGenerator` now generates layouts by default. The HTML mailer layout - now includes `` and `` tags which improve the spam rating in - some spam detection engines. Mailers now inherit from `ApplicationMailer` - which sets the default layout. - - *Andy Jeffries* - -* `link_to` and `url_for` now generate URLs by default in templates. - Passing `only_path: false` is no longer needed. - - Fixes #16497 and #16589. - - *Xavier Noria*, *Richard Schneeman* - -* Attachments can now be added while rendering the mail template. - - Fixes #16974. - - *Christian Felder* - -* Add `#deliver_later` and `#deliver_now` methods and deprecate `#deliver` in - favor of `#deliver_now`. `#deliver_later` will enqueue a job to render and - deliver the mail instead of delivering it immediately. The job is enqueued - using the new Active Job framework in Rails and will use the queue that you - have configured in Rails. - - *DHH*, *Abdelkader Boudih*, *Cristian Bica* - -* `ActionMailer::Previews` are now class methods instead of instance methods. - - *Cristian Bica* - -* Deprecate `*_path` helpers in email views. They generated broken links in - email views and were not the intention of most developers. The `*_url` - helper is recommended instead. - - *Richard Schneeman* - -* Raise an exception when attachments are added after `mail` is called. - This is a safeguard to prevent invalid emails. - - Fixes #16163. - - *Yves Senn* - -* Add `config.action_mailer.show_previews` configuration option. - - This configuration option can be used to enable the mail preview in - environments other than development (such as staging). - - Defaults to `true` in development and `false` elsewhere. - - *Leonard Garvey* - -* Allow preview interceptors to be registered through - `config.action_mailer.preview_interceptors`. - - See #15739. - - *Yves Senn* - -Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/actionmailer/CHANGELOG.md) -for previous changes. +Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/actionmailer/CHANGELOG.md) for previous changes. diff --git a/actionmailer/lib/action_mailer/gem_version.rb b/actionmailer/lib/action_mailer/gem_version.rb index e568b8f6f2..ac79788cf0 100644 --- a/actionmailer/lib/action_mailer/gem_version.rb +++ b/actionmailer/lib/action_mailer/gem_version.rb @@ -5,10 +5,10 @@ module ActionMailer end module VERSION - MAJOR = 4 - MINOR = 2 + MAJOR = 5 + MINOR = 0 TINY = 0 - PRE = "beta4" + PRE = "alpha" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index 07063c953a..556545c0d8 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -1,410 +1 @@ -* 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: - - status, headers, body = response - - But it also means `response + response` works and `[response].flatten` - cascades down to the Rack body. Nonsense behavior. Instead, rely on - explicit conversion and splatting with `#to_a`: - - status, header, body = *response - - *Jeremy Kemper* - -* Don't rescue `IPAddr::InvalidAddressError`. - - `IPAddr::InvalidAddressError` does not exist in Ruby 1.9.3 - and fails for JRuby in 1.9 mode. - - *Peter Suschlik* - -* Fix bug where the router would ignore any constraints added to redirect - routes. - - Fixes #16605. - - *Agis Anastasopoulos* - -* Allow `config.action_dispatch.trusted_proxies` to accept an IPAddr object. - - Example: - - # config/environments/production.rb - config.action_dispatch.trusted_proxies = IPAddr.new('4.8.15.0/16') - - *Sam Aarons* - -* Avoid duplicating routes for HEAD requests. - - Instead of duplicating the routes, we will first match the HEAD request to - HEAD routes. If no match is found, we will then map the HEAD request to - GET routes. - - *Guo Xiang Tan*, *Andrew White* - -* Requests that hit `ActionDispatch::Static` can now take advantage - of gzipped assets on disk. By default a gzip asset will be served if - the client supports gzip and a compressed file is on disk. - - *Richard Schneeman* - -* `ActionController::Parameters` will stop inheriting from `Hash` and - `HashWithIndifferentAccess` in the next major release. If you use any method - that is not available on `ActionController::Parameters` you should consider - calling `#to_h` to convert it to a `Hash` first before calling that method. - - *Prem Sichanugrist* - -* `ActionController::Parameters#to_h` now returns a `Hash` with unpermitted - keys removed. This change is to reflect on a security concern where some - method performed on an `ActionController::Parameters` may yield a `Hash` - object which does not maintain `permitted?` status. If you would like to - get a `Hash` with all the keys intact, duplicate and mark it as permitted - before calling `#to_h`. - - params = ActionController::Parameters.new({ - name: 'Senjougahara Hitagi', - oddity: 'Heavy stone crab' - }) - params.to_h - # => {} - - unsafe_params = params.dup.permit! - unsafe_params.to_h - # => {"name"=>"Senjougahara Hitagi", "oddity"=>"Heavy stone crab"} - - safe_params = params.permit(:name) - safe_params.to_h - # => {"name"=>"Senjougahara Hitagi"} - - This change is consider a stopgap as we cannot change the code to stop - `ActionController::Parameters` to inherit from `HashWithIndifferentAccess` - in the next minor release. - - *Prem Sichanugrist* - -* Deprecated `TagAssertions`. - - *Kasper Timm Hansen* - -* Use the Active Support JSON encoder for cookie jars using the `:json` or - `:hybrid` serializer. This allows you to serialize custom Ruby objects into - cookies by defining the `#as_json` hook on such objects. - - Fixes #16520. - - *Godfrey Chan* - -* Add `config.action_dispatch.cookies_digest` option for setting custom - digest. The default remains the same - 'SHA1'. - - *Łukasz Strzałkowski* - -* Move `respond_with` (and the class-level `respond_to`) to - the `responders` gem. - - *José Valim* - -* When your templates change, browser caches bust automatically. - - New default: the template digest is automatically included in your ETags. - When you call `fresh_when @post`, the digest for `posts/show.html.erb` - is mixed in so future changes to the HTML will blow HTTP caches for you. - This makes it easy to HTTP-cache many more of your actions. - - If you render a different template, you can now pass the `:template` - option to include its digest instead: - - fresh_when @post, template: 'widgets/show' - - Pass `template: false` to skip the lookup. To turn this off entirely, set: - - config.action_controller.etag_with_template_digest = false - - *Jeremy Kemper* - -* Remove deprecated `AbstractController::Helpers::ClassMethods::MissingHelperError` - in favor of `AbstractController::Helpers::MissingHelperError`. - - *Yves Senn* - -* Fix `assert_template` not being able to assert that no files were rendered. - - *Guo Xiang Tan* - -* Extract source code for the entire exception stack trace for - better debugging and diagnosis. - - *Ryan Dao* - -* Allows ActionDispatch::Request::LOCALHOST to match any IPv4 127.0.0.0/8 - loopback address. - - *Earl St Sauver*, *Sven Riedel* - -* Preserve original path in `ShowExceptions` middleware by stashing it as - `env["action_dispatch.original_path"]` - - `ActionDispatch::ShowExceptions` overwrites `PATH_INFO` with the status code - for the exception defined in `ExceptionWrapper`, so the path - the user was visiting when an exception occurred was not previously - available to any custom exceptions_app. The original `PATH_INFO` is now - stashed in `env["action_dispatch.original_path"]`. - - *Grey Baker* - -* Use `String#bytesize` instead of `String#size` when checking for cookie - overflow. - - *Agis Anastasopoulos* - -* `render nothing: true` or rendering a `nil` body no longer add a single - space to the response body. - - The old behavior was added as a workaround for a bug in an early version of - Safari, where the HTTP headers are not returned correctly if the response - body has a 0-length. This is been fixed since and the workaround is no - longer necessary. - - Use `render body: ' '` if the old behavior is desired. - - See #14883 for details. - - *Godfrey Chan* - -* Prepend a JS comment to JSONP callbacks. Addresses CVE-2014-4671 - ("Rosetta Flash"). - - *Greg Campbell* - -* Because URI paths may contain non US-ASCII characters we need to force - the encoding of any unescaped URIs to UTF-8 if they are US-ASCII. - This essentially replicates the functionality of the monkey patch to - URI.parser.unescape in active_support/core_ext/uri.rb. - - Fixes #16104. - - *Karl Entwistle* - -* Generate shallow paths for all children of shallow resources. - - Fixes #15783. - - *Seb Jacobs* - -* JSONP responses are now rendered with the `text/javascript` content type - when rendering through a `respond_to` block. - - Fixes #15081. - - *Lucas Mazza* - -* Add `config.action_controller.always_permitted_parameters` to configure which - parameters are permitted globally. The default value of this configuration is - `['controller', 'action']`. - - *Gary S. Weaver*, *Rafael Chacon* - -* Fix env['PATH_INFO'] missing leading slash when a rack app mounted at '/'. - - Fixes #15511. - - *Larry Lv* - -* ActionController::Parameters#require now accepts `false` values. - - Fixes #15685. - - *Sergio Romano* - -* With authorization header `Authorization: Token token=`, `authenticate` now - recognize token as nil, instead of "token". - - Fixes #14846. - - *Larry Lv* - -* Ensure the controller is always notified as soon as the client disconnects - during live streaming, even when the controller is blocked on a write. - - *Nicholas Jakobsen*, *Matthew Draper* - -* Routes specifying 'to:' must be a string that contains a "#" or a rack - application. Use of a symbol should be replaced with `action: symbol`. - Use of a string without a "#" should be replaced with `controller: string`. - - *Aaron Patterson* - -* Fix URL generation with `:trailing_slash` such that it does not add - a trailing slash after `.:format` - - *Dan Langevin* - -* Build full URI as string when processing path in integration tests for - performance reasons. - - *Guo Xiang Tan* - -* Fix `'Stack level too deep'` when rendering `head :ok` in an action method - called 'status' in a controller. - - Fixes #13905. - - *Christiaan Van den Poel* - -* Add MKCALENDAR HTTP method (RFC 4791). - - *Sergey Karpesh* - -* Instrument fragment cache metrics. - - Adds `:controller`: and `:action` keys to the instrumentation payload - for the `*_fragment.action_controller` notifications. This allows tracking - e.g. the fragment cache hit rates for each controller action. - - *Daniel Schierbeck* - -* Always use the provided port if the protocol is relative. - - Fixes #15043. - - *Guilherme Cavalcanti*, *Andrew White* - -* Moved `params[request_forgery_protection_token]` into its own method - and improved tests. - - Fixes #11316. - - *Tom Kadwill* - -* Added verification of route constraints given as a Proc or an object responding - to `:matches?`. Previously, when given an non-complying object, it would just - silently fail to enforce the constraint. It will now raise an `ArgumentError` - when setting up the routes. - - *Xavier Defrang* - -* Properly treat the entire IPv6 User Local Address space as private for - purposes of remote IP detection. Also handle uppercase private IPv6 - addresses. - - Fixes #12638. - - *Caleb Spare* - -* Fixed an issue with migrating legacy json cookies. - - Previously, the `VerifyAndUpgradeLegacySignedMessage` assumes all incoming - cookies are marshal-encoded. This is not the case when `secret_token` is - used in conjunction with the `:json` or `:hybrid` serializer. - - In those case, when upgrading to use `secret_key_base`, this would cause a - `TypeError: incompatible marshal file format` and a 500 error for the user. - - Fixes #14774. - - *Godfrey Chan* - -* Make URL escaping more consistent: - - 1. Escape '%' characters in URLs - only unescaped data should be passed to URL helpers - 2. Add an `escape_segment` helper to `Router::Utils` that escapes '/' characters - 3. Use `escape_segment` rather than `escape_fragment` in optimized URL generation - 4. Use `escape_segment` rather than `escape_path` in URL generation - - For point 4 there are two exceptions. Firstly, when a route uses wildcard segments - (e.g. `*foo`) then we use `escape_path` as the value may contain '/' characters. This - means that wildcard routes can't be optimized. Secondly, if a `:controller` segment - is used in the path then this uses `escape_path` as the controller may be namespaced. - - Fixes #14629, #14636 and #14070. - - *Andrew White*, *Edho Arief* - -* Add alias `ActionDispatch::Http::UploadedFile#to_io` to - `ActionDispatch::Http::UploadedFile#tempfile`. - - *Tim Linquist* - -* Returns null type format when format is not know and controller is using `any` - format block. - - Fixes #14462. - - *Rafael Mendonça França* - -* Improve routing error page with fuzzy matching search. - - *Winston* - -* Only make deeply nested routes shallow when parent is shallow. - - Fixes #14684. - - *Andrew White*, *James Coglan* - -* Append link to bad code to backtrace when exception is `SyntaxError`. - - *Boris Kuznetsov* - -* Swapped the parameters of assert_equal in `assert_select` so that the - proper values were printed correctly. - - Fixes #14422. - - *Vishal Lal* - -* The method `shallow?` returns false if the parent resource is a singleton so - we need to check if we're not inside a nested scope before copying the :path - and :as options to their shallow equivalents. - - Fixes #14388. - - *Andrew White* - -* Make logging of CSRF failures optional (but on by default) with the - `log_warning_on_csrf_failure` configuration setting in - `ActionController::RequestForgeryProtection`. - - *John Barton* - -* Fix URL generation in controller tests with request-dependent - `default_url_options` methods. - - *Tony Wooster* - -Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/actionpack/CHANGELOG.md) for previous changes. +Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/actionpack/CHANGELOG.md) for previous changes. diff --git a/actionpack/lib/action_pack/gem_version.rb b/actionpack/lib/action_pack/gem_version.rb index 9b3ea30f69..255ac9f4ed 100644 --- a/actionpack/lib/action_pack/gem_version.rb +++ b/actionpack/lib/action_pack/gem_version.rb @@ -5,10 +5,10 @@ module ActionPack end module VERSION - MAJOR = 4 - MINOR = 2 + MAJOR = 5 + MINOR = 0 TINY = 0 - PRE = "beta4" + PRE = "alpha" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md index de65543137..729717608f 100644 --- a/actionview/CHANGELOG.md +++ b/actionview/CHANGELOG.md @@ -1,218 +1 @@ -* 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 - to `render file: "foo/bar"`. In Rails 4.2, this has been changed to mean - `render template: "foo/bar"` instead. If you need to render a file, please - change your code to use the explicit form (`render file: "foo/bar"`) instead. - - *Jeremy Jackson* - -* Add support for ARIA attributes in tags. - - Example: - - <%= f.text_field :name, aria: { required: "true", hidden: "false" } %> - - now generates: - - - - *Paola Garcia Casadiego* - -* Provide a `builder` object when using the `label` form helper in block form. - - The new `builder` object responds to `translation`, allowing I18n fallback support - when you want to customize how a particular label is presented. - - *Alex Robbin* - -* Add I18n support for input/textarea placeholder text. - - Placeholder I18n follows the same convention as `label` I18n. - - *Alex Robbin* - -* Fix that render layout: 'messages/layout' should also be added to the dependency tracker tree. - - *DHH* - -* Add `PartialIteration` object used when rendering collections. - - The iteration object is available as the local variable - `#{template_name}_iteration` when rendering partials with collections. - - It gives access to the `size` of the collection being iterated over, - the current `index` and two convenience methods `first?` and `last?`. - - *Joel Junström*, *Lucas Uyezu* - -* Return an absolute instead of relative path from an asset url in the case - of the `asset_host` proc returning nil. - - *Jolyon Pawlyn* - -* Fix `html_escape_once` to properly handle hex escape sequences (e.g. ᨫ). - - *John F. Douthat* - -* Added String support for min and max properties for date field helpers. - - *Todd Bealmear* - -* The `highlight` helper now accepts a block to be used instead of the `highlighter` - option. - - *Lucas Mazza* - -* The `except` and `highlight` helpers now accept regular expressions. - - *Jan Szumiec* - -* Flatten the array parameter in `safe_join`, so it behaves consistently with - `Array#join`. - - *Paul Grayson* - -* Honor `html_safe` on array elements in tag values, as we do for plain string - values. - - *Paul Grayson* - -* Add `ActionView::Template::Handler.unregister_template_handler`. - - It performs the opposite of `ActionView::Template::Handler.register_template_handler`. - - *Zuhao Wan* - -* Bring `cache_digest` rake tasks up-to-date with the latest API changes. - - *Jiri Pospisil* - -* Allow custom `:host` option to be passed to `asset_url` helper that - overwrites `config.action_controller.asset_host` for particular asset. - - *Hubert Łępicki* - -* Deprecate `AbstractController::Base.parent_prefixes`. - Override `AbstractController::Base.local_prefixes` when you want to change - where to find views. - - *Nick Sutterer* - -* Take label values into account when doing I18n lookups for model attributes. - - The following: - - # form.html.erb - <%= form_for @post do |f| %> - <%= f.label :type, value: "long" %> - <% end %> - - # en.yml - en: - activerecord: - attributes: - post/long: "Long-form Post" - - Used to simply return "long", but now it will return "Long-form - Post". - - *Joshua Cody* - -* Change `asset_path` to use File.join to create proper paths: - - Before: - - https://some.host.com//assets/some.js - - After: - - https://some.host.com/assets/some.js - - *Peter Schröder* - -* Change `favicon_link_tag` default mimetype from `image/vnd.microsoft.icon` to - `image/x-icon`. - - Before: - - # => favicon_link_tag 'myicon.ico' - - - After: - - # => favicon_link_tag 'myicon.ico' - - - *Geoffroy Lorieux* - -* Remove wrapping div with inline styles for hidden form fields. - - We are dropping HTML 4.01 and XHTML strict compliance since input tags directly - inside a form are valid HTML5, and the absence of inline styles help in validating - for Content Security Policy. - - *Joost Baaij* - -* `collection_check_boxes` respects `:index` option for the hidden field name. - - Fixes #14147. - - *Vasiliy Ermolovich* - -* `date_select` helper with option `with_css_classes: true` does not overwrite other classes. - - *Izumi Wong-Horiuchi* - -* `number_to_percentage` does not crash with `Float::NAN` or `Float::INFINITY` - as input. - - Fixes #14405. - - *Yves Senn* - -* Add `include_hidden` option to `collection_check_boxes` helper. - - *Vasiliy Ermolovich* - -* Fixed a problem where the default options for the `button_tag` helper are not - applied correctly. - - Fixes #14254. - - *Sergey Prikhodko* - -* Take variants into account when calculating template digests in ActionView::Digestor. - - The arguments to ActionView::Digestor#digest are now being passed as a hash - to support variants and allow more flexibility in the future. The support for - regular (required) arguments is deprecated and will be removed in Rails 5.0 or later. - - *Piotr Chmolowski, Łukasz Strzałkowski* - -Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/actionview/CHANGELOG.md) for previous changes. +Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/actionview/CHANGELOG.md) for previous changes. diff --git a/actionview/lib/action_view/gem_version.rb b/actionview/lib/action_view/gem_version.rb index 752eafee3c..4f45f5b8c8 100644 --- a/actionview/lib/action_view/gem_version.rb +++ b/actionview/lib/action_view/gem_version.rb @@ -5,10 +5,10 @@ module ActionView end module VERSION - MAJOR = 4 - MINOR = 2 + MAJOR = 5 + MINOR = 0 TINY = 0 - PRE = "beta4" + PRE = "alpha" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/activejob/CHANGELOG.md b/activejob/CHANGELOG.md index b04883413e..f9c481998e 100644 --- a/activejob/CHANGELOG.md +++ b/activejob/CHANGELOG.md @@ -1 +1 @@ -* Started project. \ No newline at end of file +Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activejob/CHANGELOG.md) for previous changes. diff --git a/activejob/lib/active_job/gem_version.rb b/activejob/lib/active_job/gem_version.rb index ac364f77d1..27a5de93f4 100644 --- a/activejob/lib/active_job/gem_version.rb +++ b/activejob/lib/active_job/gem_version.rb @@ -5,10 +5,10 @@ module ActiveJob end module VERSION - MAJOR = 4 - MINOR = 2 + MAJOR = 5 + MINOR = 0 TINY = 0 - PRE = "beta4" + PRE = "alpha" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/activemodel/CHANGELOG.md b/activemodel/CHANGELOG.md index 5588699d9b..b86e988841 100644 --- a/activemodel/CHANGELOG.md +++ b/activemodel/CHANGELOG.md @@ -1,61 +1 @@ -* Passwords with spaces only allowed in `ActiveModel::SecurePassword`. - - Presence validation can be used to restore old behavior. - - *Yevhene Shemet* - -* Validate options passed to `ActiveModel::Validations.validate`. - - Preventing, in many cases, the simple mistake of using `validate` instead of `validates`. - - *Sonny Michaud* - -* Deprecate `reset_#{attribute}` in favor of `restore_#{attribute}`. - - These methods may cause confusion with the `reset_changes`, which has - different behaviour. - - *Rafael Mendonça França* - -* Deprecate `ActiveModel::Dirty#reset_changes` in favor of `#clear_changes_information`. - - Method's name is causing confusion with the `reset_#{attribute}` methods. - While `reset_name` sets the value of the name attribute to previous value - `reset_changes` only discards the changes. - - *Rafael Mendonça França* - -* Added `restore_attributes` method to `ActiveModel::Dirty` API which restores - the value of changed attributes to previous value. - - *Igor G.* - -* Allow proc and symbol as values for `only_integer` of `NumericalityValidator` - - *Robin Mehner* - -* `has_secure_password` now verifies that the given password is less than 72 - characters if validations are enabled. - - Fixes #14591. - - *Akshay Vishnoi* - -* Remove deprecated `Validator#setup` without replacement. - - See #10716. - - *Kuldeep Aggarwal* - -* Add plural and singular form for length validator's default messages. - - *Abd ar-Rahman Hamid* - -* Introduce `validate` as an alias for `valid?`. - - This is more intuitive when you want to run validations but don't care about - the return value. - - *Henrik Nyh* - -Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/activemodel/CHANGELOG.md) for previous changes. +Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activemodel/CHANGELOG.md) for previous changes. diff --git a/activemodel/lib/active_model/gem_version.rb b/activemodel/lib/active_model/gem_version.rb index 932fe3e5a9..2403242ce6 100644 --- a/activemodel/lib/active_model/gem_version.rb +++ b/activemodel/lib/active_model/gem_version.rb @@ -5,10 +5,10 @@ module ActiveModel end module VERSION - MAJOR = 4 - MINOR = 2 + MAJOR = 5 + MINOR = 0 TINY = 0 - PRE = "beta4" + PRE = "alpha" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index a6ed8cdb06..38c5583708 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,1336 +1 @@ -* 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. - - *Simon Eskildsen* - -* Add a truncate method to the connection. - - *Aaron Patterson* - -* Don't autosave unchanged has_one through records. - - *Alan Kennedy*, *Steve Parrington* - -* Do not dump foreign keys for ignored tables. - - *Yves Senn* - -* PostgreSQL adapter correctly dumps foreign keys targeting tables - outside the schema search path. - - Fixes #16907. - - *Matthew Draper*, *Yves Senn* - -* When a thread is killed, rollback the active transaction, instead of - committing it during the stack unwind. Previously, we could commit half- - completed work. This fix only works for Ruby 2.0+; on 1.9, we can't - distinguish a thread kill from an ordinary non-local (block) return, so must - default to committing. - - *Chris Hanks* - -* A `NullRelation` should represent nothing. This fixes a bug where - `Comment.where(post_id: Post.none)` returned a non-empty result. - - Fixes #15176. - - *Matthew Draper*, *Yves Senn* - -* Include default column limits in schema.rb. Allows defaults to be changed - in the future without affecting old migrations that assumed old defaults. - - *Jeremy Kemper* - -* MySQL: schema.rb now includes TEXT and BLOB column limits. - - *Jeremy Kemper* - -* MySQL: correct LONGTEXT and LONGBLOB limits from 2GB to their true 4GB. - - *Jeremy Kemper* - -* SQLite3Adapter now checks for views in `table_exists?`. Fixes #14041. - - *Girish Sonawane* - -* Introduce `connection.supports_views?` to check whether the current adapter - has support for SQL views. Connection adapters should define this method. - - *Yves Senn* - -* Allow included modules to override association methods. - - Fixes #16684. - - *Yves Senn* - -* Schema loading rake tasks (like `db:schema:load` and `db:setup`) maintain - the database connection to the current environment. - - Fixes #16757. - - *Joshua Cody*, *Yves Senn* - -* MySQL: set the connection collation along with the charset. - - Sets the connection collation to the database collation configured in - database.yml. Otherwise, `SET NAMES utf8mb4` will use the default - collation for that charset (utf8mb4_general_ci) when you may have chosen - a different collation, like utf8mb4_unicode_ci. - - This only applies to literal string comparisons, not column values, so it - is unlikely to affect you. - - *Jeremy Kemper* - -* `default_sequence_name` from the PostgreSQL adapter returns a `String`. - - *Yves Senn* - -* Fix a regression where whitespaces were stripped from DISTINCT queries in - PostgreSQL. - - *Agis Anastasopoulos* - - Fixes #16623. - -* Fix has_many :through relation merging failing when dynamic conditions are - passed as a lambda with an arity of one. - - Fixes #16128. - - *Agis Anastasopoulos* - -* Fix `Relation#exists?` to work with polymorphic associations. - - Fixes #15821. - - *Kassio Borges* - -* Currently, Active Record rescues any errors raised within - `after_rollback`/`after_create` callbacks and prints them to the logs. - Future versions of Rails will not rescue these errors anymore and - just bubble them up like the other callbacks. - - This commit adds an opt-in flag to enable not rescuing the errors. - - Example: - - # Do not swallow errors in after_commit/after_rollback callbacks. - config.active_record.raise_in_transactional_callbacks = true - - Fixes #13460. - - *arthurnn* - -* 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. - - Fixes #16288. - - *Godfrey Chan* - -* `*_was` and `changes` now work correctly for in-place attribute changes as - well. - - *Sean Griffin* - -* Fix regression on `after_commit` that did not fire with nested transactions. - - Fixes #16425. - - *arthurnn* - -* Do not try to write timestamps when a table has no timestamps columns. - - Fixes #8813. - - *Sergey Potapov* - -* `index_exists?` with `:name` option does verify specified columns. - - Example: - - add_index :articles, :title, name: "idx_title" - - # Before: - index_exists? :articles, :title, name: "idx_title" # => `true` - index_exists? :articles, :body, name: "idx_title" # => `true` - - # After: - index_exists? :articles, :title, name: "idx_title" # => `true` - index_exists? :articles, :body, name: "idx_title" # => `false` - - *Yves Senn*, *Matthew Draper* - -* When calling `update_columns` on a record that is not persisted, the error - message now reflects whether that object is a new record or has been - destroyed. - - *Lachlan Sylvester* - -* Define `id_was` to get the previous value of the primary key. - - Currently when we call `id_was` and we have a custom primary key name, - Active Record will return the current value of the primary key. This - makes it impossible to correctly do an update operation if you change the - id. - - Fixes #16413. - - *Rafael Mendonça França* - -* Deprecate `DatabaseTasks.load_schema` to act on the current connection. - Use `.load_schema_current` instead. In the future `load_schema` will - require the `configuration` to act on as an argument. - - *Yves Senn* - -* Fix automatic maintaining test schema to properly handle sql structure - schema format. - - Fixes #15394. - - *Wojciech Wnętrzak* - -* Fix type casting to Decimal from Float with large precision. - - *Tomohiro Hashidate* - -* Deprecate `Reflection#source_macro` - - `Reflection#source_macro` is no longer needed in Active Record - source so it has been deprecated. Code that used `source_macro` - was removed in #16353. - - *Eileen M. Uchtitelle*, *Aaron Patterson* - -* No verbose backtrace by `db:drop` when database does not exist. - - Fixes #16295. - - *Kenn Ejima* - -* Add support for PostgreSQL JSONB. - - Example: - - create_table :posts do |t| - t.jsonb :meta_data - end - - *Philippe Creux*, *Chris Teague* - -* `db:purge` with MySQL respects `Rails.env`. - - *Yves Senn* - -* `change_column_default :table, :column, nil` with PostgreSQL will issue a - `DROP DEFAULT` instead of a `DEFAULT NULL` query. - - Fixes #16261. - - *Matthew Draper*, *Yves Senn* - -* Allow to specify a type for the foreign key column in `references` - and `add_reference`. - - Example: - - change_table :vehicle do |t| - t.references :station, type: :uuid - end - - *Andrey Novikov*, *Łukasz Sarnacki* - -* `create_join_table` removes a common prefix when generating the join table. - This matches the existing behavior of HABTM associations. - - Fixes #13683. - - *Stefan Kanev* - -* Do not swallow errors on `compute_type` when having a bad `alias_method` on - a class. - - *arthurnn* - -* PostgreSQL invalid `uuid` are convert to nil. - - *Abdelkader Boudih* - -* Restore 4.0 behavior for using serialize attributes with `JSON` as coder. - - With 4.1.x, `serialize` started returning a string when `JSON` was passed as - the second attribute. It will now return a hash as per previous versions. - - Example: - - class Post < ActiveRecord::Base - serialize :comment, JSON - end - - class Comment - include ActiveModel::Model - attr_accessor :category, :text - end - - post = Post.create! - post.comment = Comment.new(category: "Animals", text: "This is a comment about squirrels.") - post.save! - - # 4.0 - post.comment # => {"category"=>"Animals", "text"=>"This is a comment about squirrels."} - - # 4.1 before - post.comment # => "#" - - # 4.1 after - post.comment # => {"category"=>"Animals", "text"=>"This is a comment about squirrels."} - - When using `JSON` as the coder in `serialize`, Active Record will use the - new `ActiveRecord::Coders::JSON` coder which delegates its `dump/load` to - `ActiveSupport::JSON.encode/decode`. This ensures special objects are dumped - correctly using the `#as_json` hook. - - To keep the previous behaviour, supply a custom coder instead - ([example](https://gist.github.com/jenncoop/8c4142bbe59da77daa63)). - - Fixes #15594. - - *Jenn Cooper* - -* Do not use `RENAME INDEX` syntax for MariaDB 10.0. - - Fixes #15931. - - *Jeff Browning* - -* Calling `#empty?` on a `has_many` association would use the value from the - counter cache if one exists. - - *David Verhasselt* - -* Fix the schema dump generated for tables without constraints and with - primary key with default value of custom PostgreSQL function result. - - Fixes #16111. - - *Andrey Novikov* - -* Fix the SQL generated when a `delete_all` is run on an association to not - produce an `IN` statements. - - Before: - - UPDATE "categorizations" SET "category_id" = NULL WHERE - "categorizations"."category_id" = 1 AND "categorizations"."id" IN (1, 2) - - After: - - UPDATE "categorizations" SET "category_id" = NULL WHERE - "categorizations"."category_id" = 1 - - *Eileen M. Uchitelle, Aaron Patterson* - -* Avoid type casting boolean and `ActiveSupport::Duration` values to numeric - values for string columns. Otherwise, in some database, the string column - values will be coerced to a numeric allowing false or 0.seconds match any - string starting with a non-digit. - - Example: - - App.where(apikey: false) # => SELECT * FROM users WHERE apikey = '0' - - *Dylan Thacker-Smith* - -* Add a `:required` option to singular associations, providing a nicer - API for presence validations on associations. - - *Sean Griffin* - -* Fix an error in `reset_counters` when associations have `select` scope. - (Call to `count` generated invalid SQL.) - - *Cade Truitt* - -* After a successful `reload`, `new_record?` is always false. - - Fixes #12101. - - *Matthew Draper* - -* PostgreSQL renaming table doesn't attempt to rename non existent sequences. - - *Abdelkader Boudih* - -* Move 'dependent: :destroy' handling for `belongs_to` - from `before_destroy` to `after_destroy` callback chain - - Fixes #12380. - - *Ivan Antropov* - -* Detect in-place modifications on String attributes. - - Before this change, an attribute modified in-place had to be marked as - changed in order for it to be persisted in the database. Now it is no longer - required. - - Before: - - user = User.first - user.name << ' Griffin' - user.name_will_change! - user.save - user.reload.name # => "Sean Griffin" - - After: - - user = User.first - user.name << ' Griffin' - user.save - user.reload.name # => "Sean Griffin" - - *Sean Griffin* - -* Add `ActiveRecord::Base#validate!` that raises `RecordInvalid` if the record - is invalid. - - *Bogdan Gusiev*, *Marc Schütz* - -* Support for adding and removing foreign keys. Foreign keys are now - a part of `schema.rb`. This is supported by Mysql2Adapter, MysqlAdapter - and PostgreSQLAdapter. - - Many thanks to *Matthew Higgins* for laying the foundation with his work on - [foreigner](https://github.com/matthuhiggins/foreigner). - - Example: - - # within your migrations: - add_foreign_key :articles, :authors - remove_foreign_key :articles, :authors - - *Yves Senn* - -* Fix subtle bugs regarding attribute assignment on models with no primary - key. `'id'` will no longer be part of the attributes hash. - - *Sean Griffin* - -* Deprecate automatic counter caches on `has_many :through`. The behavior was - broken and inconsistent. - - *Sean Griffin* - -* `preload` preserves readonly flag for associations. - - See #15853. - - *Yves Senn* - -* Assume numeric types have changed if they were assigned to a value that - would fail numericality validation, regardless of the old value. Previously - this would only occur if the old value was 0. - - Example: - - model = Model.create!(number: 5) - model.number = '5wibble' - model.number_changed? # => true - - Fixes #14731. - - *Sean Griffin* - -* `reload` no longer merges with the existing attributes. - The attribute hash is fully replaced. The record is put into the same state - as it would be with `Model.find(model.id)`. - - *Sean Griffin* - -* The object returned from `select_all` must respond to `column_types`. - If this is not the case a `NoMethodError` is raised. - - *Sean Griffin* - -* Detect in-place modifications of PG array types - - *Sean Griffin* - -* Add `bin/rake db:purge` task to empty the current database. - - *Yves Senn* - -* Deprecate `serialized_attributes` without replacement. - - *Sean Griffin* - -* Correctly extract IPv6 addresses from `DATABASE_URI`: the square brackets - are part of the URI structure, not the actual host. - - Fixes #15705. - - *Andy Bakun*, *Aaron Stone* - -* Ensure both parent IDs are set on join records when both sides of a - through association are new. - - *Sean Griffin* - -* `ActiveRecord::Dirty` now detects in-place changes to mutable values. - Serialized attributes on ActiveRecord models will no longer save when - unchanged. - - Fixes #8328. - - *Sean Griffin* - -* `Pluck` now works when selecting columns from different tables with the same - name. - - Fixes #15649. - - *Sean Griffin* - -* Remove `cache_attributes` and friends. All attributes are cached. - - *Sean Griffin* - -* Remove deprecated method `ActiveRecord::Base.quoted_locking_column`. - - *Akshay Vishnoi* - -* `ActiveRecord::FinderMethods.find` with block can handle proc parameter as - `Enumerable#find` does. - - Fixes #15382. - - *James Yang* - -* Make timezone aware attributes work with PostgreSQL array columns. - - Fixes #13402. - - *Kuldeep Aggarwal*, *Sean Griffin* - -* `ActiveRecord::SchemaMigration` has no primary key regardless of the - `primary_key_prefix_type` configuration. - - Fixes #15051. - - *JoseLuis Torres*, *Yves Senn* - -* `rake db:migrate:status` works with legacy migration numbers like `00018_xyz.rb`. - - Fixes #15538. - - *Yves Senn* - -* Baseclass becomes! subclass. - - Before this change, a record which changed its STI type, could not be - updated. - - Fixes #14785. - - *Matthew Draper*, *Earl St Sauver*, *Edo Balvers* - -* Remove deprecated `ActiveRecord::Migrator.proper_table_name`. Use the - `proper_table_name` instance method on `ActiveRecord::Migration` instead. - - *Akshay Vishnoi* - -* Fix regression on eager loading association based on SQL query rather than - existing column. - - Fixes #15480. - - *Lauro Caetano*, *Carlos Antonio da Silva* - -* Deprecate returning `nil` from `column_for_attribute` when no column exists. - It will return a null object in Rails 5.0 - - *Sean Griffin* - -* Implemented `ActiveRecord::Base#pretty_print` to work with PP. - - *Ethan* - -* Preserve type when dumping PostgreSQL point, bit, bit varying and money - columns. - - *Yves Senn* - -* New records remain new after YAML serialization. - - *Sean Griffin* - -* PostgreSQL support default values for enum types. Fixes #7814. - - *Yves Senn* - -* PostgreSQL `default_sequence_name` respects schema. Fixes #7516. - - *Yves Senn* - -* Fix `columns_for_distinct` of PostgreSQL adapter to work correctly - with orders without sort direction modifiers. - - *Nikolay Kondratyev* - -* PostgreSQL `reset_pk_sequence!` respects schemas. Fixes #14719. - - *Yves Senn* - -* Keep PostgreSQL `hstore` and `json` attributes as `Hash` in `@attributes`. - Fixes duplication in combination with `store_accessor`. - - Fixes #15369. - - *Yves Senn* - -* `rake railties:install:migrations` respects the order of railties. - - *Arun Agrawal* - -* Fix redefine a `has_and_belongs_to_many` inside inherited class - Fixing regression case, where redefining the same `has_and_belongs_to_many` - definition into a subclass would raise. - - Fixes #14983. - - *arthurnn* - -* Fix `has_and_belongs_to_many` public reflection. - When defining a `has_and_belongs_to_many`, internally we convert that to two has_many. - But as `reflections` is a public API, people expect to see the right macro. - - Fixes #14682. - - *arthurnn* - -* Fix serialization for records with an attribute named `format`. - - Fixes #15188. - - *Godfrey Chan* - -* When a `group` is set, `sum`, `size`, `average`, `minimum` and `maximum` - on a NullRelation should return a Hash. - - *Kuldeep Aggarwal* - -* Fix serialized fields returning serialized data after being updated with - `update_column`. - - *Simon Hørup Eskildsen* - -* Fix polymorphic eager loading when using a String as foreign key. - - Fixes #14734. - - *Lauro Caetano* - -* Change belongs_to touch to be consistent with timestamp updates - - If a model is set up with a belongs_to: touch relationship the parent - record will only be touched if the record was modified. This makes it - consistent with timestamp updating on the record itself. - - *Brock Trappitt* - -* Fix the inferred table name of a `has_and_belongs_to_many` auxiliary - table inside a schema. - - Fixes #14824. - - *Eric Chahin* - -* Remove unused `:timestamp` type. Transparently alias it to `:datetime` - in all cases. Fixes inconsistencies when column types are sent outside of - `ActiveRecord`, such as for XML Serialization. - - *Sean Griffin* - -* Fix bug that added `table_name_prefix` and `table_name_suffix` to - extension names in PostgreSQL when migrating. - - *Joao Carlos* - -* The `:index` option in migrations, which previously was only available for - `references`, now works with any column types. - - *Marc Schütz* - -* Add support for counter name to be passed as parameter on `CounterCache::ClassMethods#reset_counters`. - - *jnormore* - -* Restrict deletion of record when using `delete_all` with `uniq`, `group`, `having` - or `offset`. - - In these cases the generated query ignored them and that caused unintended - records to be deleted. - - Fixes #11985. - - *Leandro Facchinetti* - -* Floats with limit >= 25 that get turned into doubles in MySQL no longer have - their limit dropped from the schema. - - Fixes #14135. - - *Aaron Nelson* - -* Fix how to calculate associated class name when using namespaced `has_and_belongs_to_many` - association. - - Fixes #14709. - - *Kassio Borges* - -* `ActiveRecord::Relation::Merger#filter_binds` now compares equivalent symbols and - strings in column names as equal. - - This fixes a rare case in which more bind values are passed than there are - placeholders for them in the generated SQL statement, which can make PostgreSQL - throw a `StatementInvalid` exception. - - *Nat Budin* - -* Fix `stored_attributes` to correctly merge the details of stored - attributes defined in parent classes. - - Fixes #14672. - - *Brad Bennett*, *Jessica Yao*, *Lakshmi Parthasarathy* - -* `change_column_default` allows `[]` as argument to `change_column_default`. - - Fixes #11586. - - *Yves Senn* - -* Handle `name` and `"char"` column types in the PostgreSQL adapter. - - `name` and `"char"` are special character types used internally by - PostgreSQL and are used by internal system catalogs. These field types - can sometimes show up in structure-sniffing queries that feature internal system - structures or with certain PostgreSQL extensions. - - *J Smith*, *Yves Senn* - -* Fix `PostgreSQLAdapter::OID::Float#type_cast` to convert Infinity and - NaN PostgreSQL values into a native Ruby `Float::INFINITY` and `Float::NAN` - - Before: - - Point.create(value: 1.0/0) - Point.last.value # => 0.0 - - After: - - Point.create(value: 1.0/0) - Point.last.value # => Infinity - - *Innokenty Mikhailov* - -* Allow the PostgreSQL adapter to handle bigserial primary key types again. - - Fixes #10410. - - *Patrick Robertson* - -* Deprecate joining, eager loading and preloading of instance dependent - associations without replacement. These operations happen before instances - are created. The current behavior is unexpected and can result in broken - behavior. - - Fixes #15024. - - *Yves Senn* - -* 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. - - Fixes #14913, #14914. - - *Fred Wu* - -* Return a non zero status when running `rake db:migrate:status` and migration table does - not exist. - - *Paul B.* - -* Add support for module-level `table_name_suffix` in models. - - This makes `table_name_suffix` work the same way as `table_name_prefix` when - using namespaced models. - - *Jenner LaFave* - -* Revert the behaviour of `ActiveRecord::Relation#join` changed through 4.0 => 4.1 to 4.0. - - In 4.1.0 `Relation#join` is delegated to `Arel#SelectManager`. - In 4.0 series it is delegated to `Array#join`. - - *Bogdan Gusiev* - -* Log nil binary column values correctly. - - When an object with a binary column is updated with a nil value - in that column, the SQL logger would throw an exception when trying - to log that nil value. This only occurs when updating a record - that already has a non-nil value in that column since an initial nil - value isn't included in the SQL anyway (at least, when dirty checking - is enabled.) The column's new value will now be logged as `` - to parallel the existing `` for non-nil values. - - *James Coleman* - -* Rails will now pass a custom validation context through to autosave associations - in order to validate child associations with the same context. - - Fixes #13854. - - *Eric Chahin*, *Aaron Nelson*, *Kevin Casey* - -* Stringify all variables keys of MySQL connection configuration. - - When `sql_mode` variable for MySQL adapters set in configuration as `String` - was ignored and overwritten by strict mode option. - - Fixes #14895. - - *Paul Nikitochkin* - -* Ensure SQLite3 statements are closed on errors. - - Fixes #13631. - - *Timur Alperovich* - -* Give `ActiveRecord::PredicateBuilder` private methods the privacy they deserve. - - *Hector Satre* - -* When using a custom `join_table` name on a `habtm`, rails was not saving it - on Reflections. This causes a problem when rails loads fixtures, because it - uses the reflections to set database with fixtures. - - Fixes #14845. - - *Kassio Borges* - -* Reset the cache when modifying a Relation with cached Arel. - Additionally display a warning message to make the user aware. - - *Yves Senn* - -* PostgreSQL should internally use `:datetime` consistently for TimeStamp. Assures - different spellings of timestamps are treated the same. - - Example: - - mytimestamp.simplified_type('timestamp without time zone') - # => :datetime - mytimestamp.simplified_type('timestamp(6) without time zone') - # => also :datetime (previously would be :timestamp) - - See #14513. - - *Jefferson Lai* - -* `ActiveRecord::Base.no_touching` no longer triggers callbacks or start empty transactions. - - Fixes #14841. - - *Lucas Mazza* - -* Fix name collision with `Array#select!` with `Relation#select!`. - - Fixes #14752. - - *Earl St Sauver* - -* 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. - - Fixes #14537. - - *Jan Habermann* - -* `@destroyed` should always be set to `false` when an object is duped. - - *Kuldeep Aggarwal* - -* Enable `has_many` associations to support irregular inflections. - - Fixes #8928. - - *arthurnn*, *Javier Goizueta* - -* Fix `count` used with a grouping not returning a Hash. - - Fixes #14721. - - *Eric Chahin* - -* `sanitize_sql_like` helper method to escape a string for safe use in an SQL - LIKE statement. - - Example: - - class Article - def self.search(term) - where("title LIKE ?", sanitize_sql_like(term)) - end - end - - Article.search("20% _reduction_") - # => Query looks like "... title LIKE '20\% \_reduction\_' ..." - - *Rob Gilson*, *Yves Senn* - -* Do not quote uuid default value on `change_column`. - - Fixes #14604. - - *Eric Chahin* - -* The comparison between `Relation` and `CollectionProxy` should be consistent. - - Example: - - author.posts == Post.where(author_id: author.id) - # => true - Post.where(author_id: author.id) == author.posts - # => true - - Fixes #13506. - - *Lauro Caetano* - -* Calling `delete_all` on an unloaded `CollectionProxy` no longer - generates an SQL statement containing each id of the collection: - - Before: - - DELETE FROM `model` WHERE `model`.`parent_id` = 1 - AND `model`.`id` IN (1, 2, 3...) - - After: - - DELETE FROM `model` WHERE `model`.`parent_id` = 1 - - *Eileen M. Uchitelle*, *Aaron Patterson* - -* Fix invalid SQL when aggregate methods (`empty?`, `any?`, `count`) used - with `select`. - - Fixes #13648. - - *Simon Woker* - -* PostgreSQL adapter only warns once for every missing OID per connection. - - Fixes #14275. - - *Matthew Draper*, *Yves Senn* - -* PostgreSQL adapter automatically reloads it's type map when encountering - unknown OIDs. - - Fixes #14678. - - *Matthew Draper*, *Yves Senn* - -* Fix insertion of records via `has_many :through` association with scope. - - Fixes #3548. - - *Ivan Antropov* - -* Auto-generate stable fixture UUIDs on PostgreSQL. - - Fixes #11524. - - *Roderick van Domburg* - -* Fix a problem where an enum would overwrite values of another enum with the - same name in an unrelated class. - - Fixes #14607. - - *Evan Whalen* - -* PostgreSQL and SQLite string columns no longer have a default limit of 255. - - Fixes #13435, #9153. - - *Vladimir Sazhin*, *Toms Mikoss*, *Yves Senn* - -* Make possible to have an association called `records`. - - Fixes #11645. - - *prathamesh-sonpatki* - -* `to_sql` on an association now matches the query that is actually executed, where it - could previously have incorrectly accrued additional conditions (e.g. as a result of - a previous query). `CollectionProxy` now always defers to the association scope's - `arel` method so the (incorrect) inherited one should be entirely concealed. - - Fixes #14003. - - *Jefferson Lai* - -* Block a few default Class methods as scope name. - - For instance, this will raise: - - scope :public, -> { where(status: 1) } - - *arthurnn* - -* Fix error when using `with_options` with lambda. - - Fixes #9805. - - *Lauro Caetano* - -* Switch `sqlite3:///` URLs (which were temporarily - deprecated in 4.1) from relative to absolute. - - If you still want the previous interpretation, you should replace - `sqlite3:///my/path` with `sqlite3:my/path`. - - *Matthew Draper* - -* Treat blank UUID values as `nil`. - - Example: - - Sample.new(uuid_field: '') #=> - - *Dmitry Lavrov* - -* Enable support for materialized views on PostgreSQL >= 9.3. - - *Dave Lee* - -* The PostgreSQL adapter supports custom domains. Fixes #14305. - - *Yves Senn* - -* PostgreSQL `Column#type` is now determined through the corresponding OID. - The column types stay the same except for enum columns. They no longer have - `nil` as type but `enum`. - - See #7814. - - *Yves Senn* - -* Fix error when specifying a non-empty default value on a PostgreSQL array - column. - - Fixes #10613. - - *Luke Steensen* - -* 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. - - *Chris Finne* - -* Introduce `validate` as an alias for `valid?`. - - This is more intuitive when you want to run validations but don't care about the return value. - - *Henrik Nyh* - -* Create indexes inline in CREATE TABLE for MySQL. - - This is important, because adding an index on a temporary table after it has been created - would commit the transaction. - - It also allows creating and dropping indexed tables with fewer queries and fewer permissions - required. - - Example: - - create_table :temp, temporary: true, as: "SELECT id, name, zip FROM a_really_complicated_query" do |t| - t.index :zip - end - # => CREATE TEMPORARY TABLE temp (INDEX (zip)) AS SELECT id, name, zip FROM a_really_complicated_query - - *Cody Cutrer*, *Steve Rice*, *Rafael Mendonça Franca* - -* Use singular table name in generated migrations when - `ActiveRecord::Base.pluralize_table_names` is `false`. - - Fixes #13426. - - *Kuldeep Aggarwal* - -* `touch` accepts many attributes to be touched at once. - - Example: - - # touches :signed_at, :sealed_at, and :updated_at/on attributes. - Photo.last.touch(:signed_at, :sealed_at) - - *James Pinto* - -* `rake db:structure:dump` only dumps schema information if the schema - migration table exists. - - Fixes #14217. - - *Yves Senn* - -* Reap connections that were checked out by now-dead threads, instead - of waiting until they disconnect by themselves. Before this change, - a suitably constructed series of short-lived threads could starve - the connection pool, without ever having more than a couple alive at - the same time. - - *Matthew Draper* - -* `pk_and_sequence_for` now ensures that only the pg_depend entries - pointing to pg_class, and thus only sequence objects, are considered. - - *Josh Williams* - -* `where.not` adds `references` for `includes` like normal `where` calls do. - - Fixes #14406. - - *Yves Senn* - -* Extend fixture `$LABEL` replacement to allow string interpolation. - - Example: - - martin: - email: $LABEL@email.com - - users(:martin).email # => martin@email.com - - *Eric Steele* - -* Add support for `Relation` be passed as parameter on `QueryCache#select_all`. - - Fixes #14361. - - *arthurnn* - -* Passing an Active Record object to `find` or `exists?` is now deprecated. - Call `.id` on the object first. - - *Aaron Patterson* - -* Only use BINARY for MySQL case sensitive uniqueness check when column - has a case insensitive collation. - - *Ryuta Kamizono* - -* Support for MySQL 5.6 fractional seconds. - - *arthurnn*, *Tatsuhiko Miyagawa* - -* Support for PostgreSQL `citext` data type enabling case-insensitive - `where` values without needing to wrap in UPPER/LOWER sql functions. - - *Troy Kruthoff*, *Lachlan Sylvester* - -* Only save has_one associations if record has changes. - Previously after save related callbacks, such as `#after_commit`, were triggered when the has_one - object did not get saved to the db. - - *Alan Kennedy* - -* Allow strings to specify the `#order` value. - - Example: - - Model.order(id: 'asc').to_sql == Model.order(id: :asc).to_sql - - *Marcelo Casiraghi*, *Robin Dupret* - -* Dynamically register PostgreSQL enum OIDs. This prevents "unknown OID" - warnings on enum columns. - - *Dieter Komendera* - -* `includes` is able to detect the right preloading strategy when string - joins are involved. - - Fixes #14109. - - *Aaron Patterson*, *Yves Senn* - -* 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. - - *Vilius Luneckas* *Ahmed AbouElhamayed* - -* `before_add` callbacks are fired before the record is saved on - `has_and_belongs_to_many` associations *and* on `has_many :through` - associations. Before this change, `before_add` callbacks would be fired - before the record was saved on `has_and_belongs_to_many` associations, but - *not* on `has_many :through` associations. - - Fixes #14144. - -* Fix STI classes not defining an attribute method if there is a conflicting - private method defined on its ancestors. - - Fixes #11569. - - *Godfrey Chan* - -* Coerce strings when reading attributes. Fixes #10485. - - Example: - - book = Book.new(title: 12345) - book.save! - book.title # => "12345" - - *Yves Senn* - -* Deprecate half-baked support for PostgreSQL range values with excluding beginnings. - We currently map PostgreSQL ranges to Ruby ranges. This conversion is not fully - possible because the Ruby range does not support excluded beginnings. - - The current solution of incrementing the beginning is not correct and is now - deprecated. For subtypes where we don't know how to increment (e.g. `#succ` - is not defined) it will raise an `ArgumentException` for ranges with excluding - beginnings. - - *Yves Senn* - -* Support for user created range types in PostgreSQL. - - *Yves Senn* - -Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/activerecord/CHANGELOG.md) for previous changes. +Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activerecord/CHANGELOG.md) for previous changes. diff --git a/activerecord/lib/active_record/gem_version.rb b/activerecord/lib/active_record/gem_version.rb index e820835626..a388b529c9 100644 --- a/activerecord/lib/active_record/gem_version.rb +++ b/activerecord/lib/active_record/gem_version.rb @@ -5,10 +5,10 @@ module ActiveRecord end module VERSION - MAJOR = 4 - MINOR = 2 + MAJOR = 5 + MINOR = 0 TINY = 0 - PRE = "beta4" + PRE = "alpha" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/activesupport/CHANGELOG.md b/activesupport/CHANGELOG.md index ed30c7de70..810fc22cf5 100644 --- a/activesupport/CHANGELOG.md +++ b/activesupport/CHANGELOG.md @@ -1,388 +1 @@ -* 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* - -* Delegation now works with ruby reserved words passed to `:to` option. - - Fixes #16956. - - *Agis Anastasopoulos* - -* Added method `#eql?` to `ActiveSupport::Duration`, in addition to `#==`. - - Currently, the following returns `false`, contrary to expectation: - - 1.minute.eql?(1.minute) - - Adding method `#eql?` will make this behave like expected. Method `#eql?` is - just a bit stricter than `#==`, as it checks whether the argument is also a duration. Their - parts may be different though. - - 1.minute.eql?(60.seconds) # => true - 1.minute.eql?(60) # => false - - *Joost Lubach* - -* `Time#change` can now change nanoseconds (`:nsec`) as a higher-precision - alternative to microseconds (`:usec`). - - *Agis Anastasooulos* - -* `MessageVerifier.new` raises an appropriate exception if the secret is `nil`. - This prevents `MessageVerifier#generate` from raising a cryptic error later on. - - *Kostiantyn Kahanskyi* - -* Introduced new configuration option `active_support.test_order` for - specifying the order in which test cases are executed. This option currently defaults - to `:sorted` but will be changed to `:random` in Rails 5.0. - - *Akira Matsuda*, *Godfrey Chan* - -* 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 - the time has an offset other than UTC or local. - - *Agis Anastasopoulos* - -* `Method` objects now report themselves as not `duplicable?`. This allows - hashes and arrays containing `Method` objects to be `deep_dup`ed. - - *Peter Jaros* - -* `determine_constant_from_test_name` does no longer shadow `NameError`s - which happens during constant autoloading. - - Fixes #9933. - - *Guo Xiang Tan* - -* Added instance_eval version to Object#try and Object#try!, so you can do this: - - person.try { name.first } - - instead of: - - person.try { |person| person.name.first } - - *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 - internal value. - - *Robin Dupret* - -* 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. - - *Rafael Mendonça França* - -* Added Object#itself which returns the object itself. Useful when dealing with a chaining scenario, like Active Record scopes: - - Event.public_send(state.presence_in([ :trashed, :drafted ]) || :itself).order(:created_at) - - *DHH* - -* `Object#with_options` executes block in merging option context when - explicit receiver in not passed. - - *Pavel Pravosud* - -* Fixed a compatibility issue with the `Oj` gem when cherry-picking the file - `active_support/core_ext/object/json` without requiring `active_support/json`. - - Fixes #16131. - - *Godfrey Chan* - -* Make `Hash#with_indifferent_access` copy the default proc too. - - *arthurnn*, *Xanders* - -* Add `String#truncate_words` to truncate a string by a number of words. - - *Mohamed Osama* - -* Deprecate `capture` and `quietly`. - - These methods are not thread safe and may cause issues when used in threaded environments. - To avoid problems we are deprecating them. - - *Tom Meier* - -* `DateTime#to_f` now preserves the fractional seconds instead of always - rounding to `.0`. - - Fixes #15994. - - *John Paul Ashenfelter* - -* Add `Hash#transform_values` to simplify a common pattern where the values of a - hash must change, but the keys are left the same. - - *Sean Griffin* - -* Always instrument `ActiveSupport::Cache`. - - Since `ActiveSupport::Notifications` only instruments items when there - are attached subscribers, we don't need to disable instrumentation. - - *Peter Wagenet* - -* Make the `apply_inflections` method case-insensitive when checking - whether a word is uncountable or not. - - *Robin Dupret* - -* Make Dependencies pass a name to NameError error. - - *arthurnn* - -* Fixed `ActiveSupport::Cache::FileStore` exploding with long paths. - - *Adam Panzer*, *Michael Grosser* - -* Fixed `ActiveSupport::TimeWithZone#-` so precision is not unnecessarily lost - when working with objects with a nanosecond component. - - `ActiveSupport::TimeWithZone#-` should return the same result as if we were - using `Time#-`: - - Time.now.end_of_day - Time.now.beginning_of_day # => 86399.999999999 - - Before: - - Time.zone.now.end_of_day.nsec # => 999999999 - Time.zone.now.end_of_day - Time.zone.now.beginning_of_day # => 86400.0 - - After: - - Time.zone.now.end_of_day - Time.zone.now.beginning_of_day - # => 86399.999999999 - - *Gordon Chan* - -* Fixed precision error in NumberHelper when using Rationals. - - Before: - - ActiveSupport::NumberHelper.number_to_rounded Rational(1000, 3), precision: 2 - # => "330.00" - - After: - - ActiveSupport::NumberHelper.number_to_rounded Rational(1000, 3), precision: 2 - # => "333.33" - - See #15379. - - *Juanjo Bazán* - -* Removed deprecated `Numeric#ago` and friends - - Replacements: - - 5.ago => 5.seconds.ago - 5.until => 5.seconds.until - 5.since => 5.seconds.since - 5.from_now => 5.seconds.from_now - - See #12389 for the history and rationale behind this. - - *Godfrey Chan* - -* DateTime `advance` now supports partial days. - - Before: - - DateTime.now.advance(days: 1, hours: 12) - - After: - - DateTime.now.advance(days: 1.5) - - Fixes #12005. - - *Shay Davidson* - -* `Hash#deep_transform_keys` and `Hash#deep_transform_keys!` now transform hashes - in nested arrays. This change also applies to `Hash#deep_stringify_keys`, - `Hash#deep_stringify_keys!`, `Hash#deep_symbolize_keys` and - `Hash#deep_symbolize_keys!`. - - *OZAWA Sakuro* - -* Fixed confusing `DelegationError` in `Module#delegate`. - - See #15186. - - *Vladimir Yarotsky* - -* Fixed `ActiveSupport::Subscriber` so that no duplicate subscriber is created - when a subscriber method is redefined. - - *Dennis Schön* - -* Remove deprecated string based terminators for `ActiveSupport::Callbacks`. - - *Eileen M. Uchitelle* - -* Fixed an issue when using - `ActiveSupport::NumberHelper::NumberToDelimitedConverter` to - convert a value that is an `ActiveSupport::SafeBuffer` introduced - in 2da9d67. - - See #15064. - - *Mark J. Titorenko* - -* `TimeZone#parse` defaults the day of the month to '1' if any other date - components are specified. This is more consistent with the behavior of - `Time#parse`. - - *Ulysse Carion* - -* `humanize` strips leading underscores, if any. - - Before: - - '_id'.humanize # => "" - - After: - - '_id'.humanize # => "Id" - - *Xavier Noria* - -* Fixed backward compatibility issues introduced in 326e652. - - Empty Hash or Array should not be present in serialization result. - - {a: []}.to_query # => "" - {a: {}}.to_query # => "" - - For more info see #14948. - - *Bogdan Gusiev* - -* Add `Digest::UUID::uuid_v3` and `Digest::UUID::uuid_v5` to support stable - UUID fixtures on PostgreSQL. - - *Roderick van Domburg* - -* Fixed `ActiveSupport::Duration#eql?` so that `1.second.eql?(1.second)` is - true. - - This fixes the current situation of: - - 1.second.eql?(1.second) # => false - - `eql?` also requires that the other object is an `ActiveSupport::Duration`. - This requirement makes `ActiveSupport::Duration`'s behavior consistent with - the behavior of Ruby's numeric types: - - 1.eql?(1.0) # => false - 1.0.eql?(1) # => false - - 1.second.eql?(1) # => false (was true) - 1.eql?(1.second) # => false - - { 1 => "foo", 1.0 => "bar" } - # => { 1 => "foo", 1.0 => "bar" } - - { 1 => "foo", 1.second => "bar" } - # now => { 1 => "foo", 1.second => "bar" } - # was => { 1 => "bar" } - - And though the behavior of these hasn't changed, for reference: - - 1 == 1.0 # => true - 1.0 == 1 # => true - - 1 == 1.second # => true - 1.second == 1 # => true - - *Emily Dobervich* - -* `ActiveSupport::SafeBuffer#prepend` acts like `String#prepend` and modifies - instance in-place, returning self. `ActiveSupport::SafeBuffer#prepend!` is - deprecated. - - *Pavel Pravosud* - -* `HashWithIndifferentAccess` better respects `#to_hash` on objects it - receives. In particular, `.new`, `#update`, `#merge`, and `#replace` accept - objects which respond to `#to_hash`, even if those objects are not hashes - directly. - - *Peter Jaros* - -* Deprecate `Class#superclass_delegating_accessor`, use `Class#class_attribute` instead. - - *Akshay Vishnoi* - -* Ensure classes which `include Enumerable` get `#to_json` in addition to - `#as_json`. - - *Sammy Larbi* - -* Change the signature of `fetch_multi` to return a hash rather than an - array. This makes it consistent with the output of `read_multi`. - - *Parker Selbert* - -* Introduce `Concern#class_methods` as a sleek alternative to clunky - `module ClassMethods`. Add `Kernel#concern` to define at the toplevel - without chunky `module Foo; extend ActiveSupport::Concern` boilerplate. - - # app/models/concerns/authentication.rb - concern :Authentication do - included do - after_create :generate_private_key - end - - class_methods do - def authenticate(credentials) - # ... - end - end - - def generate_private_key - # ... - end - end - - # app/models/user.rb - class User < ActiveRecord::Base - include Authentication - end - - *Jeremy Kemper* - -Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/activesupport/CHANGELOG.md) for previous changes. +Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/activesupport/CHANGELOG.md) for previous changes. diff --git a/activesupport/lib/active_support/gem_version.rb b/activesupport/lib/active_support/gem_version.rb index bc7933e38b..7068f09d87 100644 --- a/activesupport/lib/active_support/gem_version.rb +++ b/activesupport/lib/active_support/gem_version.rb @@ -5,10 +5,10 @@ module ActiveSupport end module VERSION - MAJOR = 4 - MINOR = 2 + MAJOR = 5 + MINOR = 0 TINY = 0 - PRE = "beta4" + PRE = "alpha" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/guides/CHANGELOG.md b/guides/CHANGELOG.md index 2770fc73e7..afaa404ac1 100644 --- a/guides/CHANGELOG.md +++ b/guides/CHANGELOG.md @@ -1,27 +1 @@ -* Change Posts to Articles in Getting Started sample application in order to -better align with the actual guides. - - *John Kelly Ferguson* - -* Update all Rails 4.1.0 references to 4.1.1 within the guides and code. - - *John Kelly Ferguson* - -* Split up rows in the Explain Queries table of the ActiveRecord Querying section -in order to improve readability. - - *John Kelly Ferguson* - -* Change all non-HTTP method 'post' references to 'article'. - - *John Kelly Ferguson* - -* Updates the maintenance policy to match the latest versions of Rails - - *Matias Korhonen* - -* Switched the order of `Applying a default scope` and `Merging of scopes` subsections so default scopes are introduced first. - - *Alex Riabov* - -Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/guides/CHANGELOG.md) for previous changes. +Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/guides/CHANGELOG.md) for previous changes. diff --git a/railties/CHANGELOG.md b/railties/CHANGELOG.md index ff6dcac465..cd7f3b1e2f 100644 --- a/railties/CHANGELOG.md +++ b/railties/CHANGELOG.md @@ -1,208 +1 @@ -* 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. - - *Dan Olson* - -* Specify dummy app's db migrate path in plugin's test_helper.rb. - - Fixes #16877. - - *Yukio Mizuta* - -* Inject `Rack::Lock` if `config.eager_load` is false. - - Fixes #15089. - - *Xavier Noria* - -* Change the path of dummy app location in plugin's test_helper.rb for cases - you specify dummy_path option. - - *Yukio Mizuta* - -* Fix a bug in the `gem` method for Rails templates when non-String options - are used. - - Fixes #16709. - - *Yves Senn* - -* The [web-console](https://github.com/rails/web-console) gem is now - installed by default for new applications. It can help you debug - development exceptions by spawning an interactive console in its cause - binding. - - *Ryan Dao*, *Genadi Samokovarov*, *Guillermo Iguaran* - -* Add a `required` option to the model generator for associations - - *Sean Griffin* - -* Add `after_bundle` callbacks in Rails templates. Useful for allowing the - generated binstubs to be added to version control. - - Fixes #16292. - - *Stefan Kanev* - -* Pull in the custom configuration concept from dhh/custom_configuration, which allows you to - configure your own code through the Rails configuration object with custom configuration: - - # config/environments/production.rb - config.x.payment_processing.schedule = :daily - config.x.payment_processing.retries = 3 - config.x.super_debugger = true - - These configuration points are then available through the configuration object: - - Rails.configuration.x.payment_processing.schedule # => :daily - Rails.configuration.x.payment_processing.retries # => 3 - Rails.configuration.x.super_debugger # => true - - *DHH* - -* Scaffold generator `_form` partial adds `class="field"` for password - confirmation fields. - - *noinkling* - -* Add `Rails::Application.config_for` to load a configuration for the current - environment. - - # config/exception_notification.yml: - production: - url: http://127.0.0.1:8080 - namespace: my_app_production - development: - url: http://localhost:3001 - namespace: my_app_development - - # config/production.rb - Rails.application.configure do - config.middleware.use ExceptionNotifier, config_for(:exception_notification) - end - - *Rafael Mendonça França*, *DHH* - -* Deprecate `Rails::Rack::LogTailer` without replacement. - - *Rafael Mendonça França* - -* Add `--skip-turbolinks` option to the app generator. - - *Rafael Mendonça França* - -* Invalid `bin/rails generate` commands will now show spelling suggestions. - - *Richard Schneeman* - -* Add `bin/setup` script to bootstrap an application. - - *Yves Senn* - -* Replace double quotes with single quotes while adding an entry into Gemfile. - - *Alexander Belaev* - -* Default `config.assets.digest` to `true` in development. - - *Dan Kang* - -* Load database configuration from the first `database.yml` available in paths. - - *Pier-Olivier Thibault* - -* Reading name and email from git for plugin gemspec. - - Fixes #9589. - - *Arun Agrawal*, *Abd ar-Rahman Hamidi*, *Roman Shmatov* - -* Fix `console` and `generators` blocks defined at different environments. - - Fixes #14748. - - *Rafael Mendonça França* - -* Move configuration of asset precompile list and version to an initializer. - - *Matthew Draper* - -* Remove sqlite3 lines from `.gitignore` if the application is not using sqlite3. - - *Dmitrii Golub* - -* Add public API to register new extensions for `rake notes`. - - Example: - - config.annotations.register_extensions("scss", "sass") { |tag| /\/\/\s*(#{tag}):?\s*(.*)$/ } - - *Roberto Miranda* - -* Removed unnecessary `rails application` command. - - *Arun Agrawal* - -* Make the `rails:template` rake task load the application's initializers. - - Fixes #12133. - - *Robin Dupret* - -* Introduce `Rails.gem_version` as a convenience method to return - `Gem::Version.new(Rails.version)`, suggesting a more reliable way to perform - version comparison. - - Example: - - Rails.version #=> "4.1.2" - Rails.gem_version #=> # - - Rails.version > "4.1.10" #=> false - Rails.gem_version > Gem::Version.new("4.1.10") #=> true - Gem::Requirement.new("~> 4.1.2") =~ Rails.gem_version #=> true - - *Prem Sichanugrist* - -* Avoid namespacing routes inside engines. - - Mountable engines are namespaced by default so the generated routes - were too while they should not. - - Fixes #14079. - - *Yves Senn*, *Carlos Antonio da Silva*, *Robin Dupret* - -Please check [4-1-stable](https://github.com/rails/rails/blob/4-1-stable/railties/CHANGELOG.md) for previous changes. +Please check [4-2-stable](https://github.com/rails/rails/blob/4-2-stable/railties/CHANGELOG.md) for previous changes. diff --git a/railties/lib/rails/gem_version.rb b/railties/lib/rails/gem_version.rb index 8abed99f2c..7d74b1bfe5 100644 --- a/railties/lib/rails/gem_version.rb +++ b/railties/lib/rails/gem_version.rb @@ -5,10 +5,10 @@ module Rails end module VERSION - MAJOR = 4 - MINOR = 2 + MAJOR = 5 + MINOR = 0 TINY = 0 - PRE = "beta4" + PRE = "alpha" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end diff --git a/version.rb b/version.rb index 8abed99f2c..7d74b1bfe5 100644 --- a/version.rb +++ b/version.rb @@ -5,10 +5,10 @@ module Rails end module VERSION - MAJOR = 4 - MINOR = 2 + MAJOR = 5 + MINOR = 0 TINY = 0 - PRE = "beta4" + PRE = "alpha" STRING = [MAJOR, MINOR, TINY, PRE].compact.join(".") end -- cgit v1.2.3 From c6bd5284b3d0771e8b8790e5f5a03d21428c99e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Fri, 28 Nov 2014 15:14:35 -0200 Subject: We don't need to use sass-rails 5.0.0.beta --- railties/lib/rails/generators/app_base.rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/railties/lib/rails/generators/app_base.rb b/railties/lib/rails/generators/app_base.rb index 0823b0cc46..f5ae600bd8 100644 --- a/railties/lib/rails/generators/app_base.rb +++ b/railties/lib/rails/generators/app_base.rb @@ -240,8 +240,7 @@ module Rails gems << GemfileEntry.github('sass-rails', 'rails/sass-rails', 'Use SCSS for stylesheets') else - gems << GemfileEntry.version('sass-rails', - '~> 5.0.0.beta1', + gems << GemfileEntry.version('sass-rails', '~> 4.0', 'Use SCSS for stylesheets') end -- cgit v1.2.3 From 457fc61cec2b3ef2224ef673ae3e72d7d35c88ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Fri, 28 Nov 2014 17:10:32 -0200 Subject: Use jquery-rails master to resolve dependencies delayed_job_active_record doesn't allow Rails 5 yet --- Gemfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Gemfile b/Gemfile index 99e2cb9f58..e2cbce24c8 100644 --- a/Gemfile +++ b/Gemfile @@ -11,7 +11,7 @@ gem 'rake', '>= 10.3' gem 'mocha', '~> 0.14', require: false gem 'rack-cache', '~> 1.2' -gem 'jquery-rails', '~> 4.0' +gem 'jquery-rails', github: 'rails/jquery-rails' gem 'coffee-rails', '~> 4.1.0' gem 'turbolinks' @@ -47,7 +47,7 @@ group :job do gem 'backburner', require: false gem 'qu-rails', github: "bkeepers/qu", branch: "master", require: false gem 'qu-redis', require: false - gem 'delayed_job_active_record', require: false + # gem 'delayed_job_active_record', require: false gem 'sequel', require: false end -- cgit v1.2.3 From c05cf18a6a90a7326b7f07502f7c3a3d75567c9a Mon Sep 17 00:00:00 2001 From: bigtone1284 Date: Fri, 28 Nov 2014 14:23:51 -0500 Subject: fixed indent of end in jdom.rb --- activesupport/lib/active_support/xml_mini/jdom.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activesupport/lib/active_support/xml_mini/jdom.rb b/activesupport/lib/active_support/xml_mini/jdom.rb index 27c64c4dca..f303daa1a7 100644 --- a/activesupport/lib/active_support/xml_mini/jdom.rb +++ b/activesupport/lib/active_support/xml_mini/jdom.rb @@ -141,7 +141,7 @@ module ActiveSupport (0...attributes.length).each do |i| attribute_hash[CONTENT_KEY] ||= '' attribute_hash[attributes.item(i).name] = attributes.item(i).value - end + end attribute_hash end -- cgit v1.2.3 From e3cba67824499804065f385b9e6cc1f73596f5ee Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Fri, 28 Nov 2014 13:01:03 -0500 Subject: Prevent Numeric#to_s from allocating an array --- .../core_ext/big_decimal/conversions.rb | 13 +++++----- .../active_support/core_ext/numeric/conversions.rb | 28 +++++++++++++++------- 2 files changed, 25 insertions(+), 16 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb index 843c592669..234283e792 100644 --- a/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb +++ b/activesupport/lib/active_support/core_ext/big_decimal/conversions.rb @@ -3,14 +3,13 @@ require 'bigdecimal/util' class BigDecimal DEFAULT_STRING_FORMAT = 'F' - def to_formatted_s(*args) - if args[0].is_a?(Symbol) - super + alias_method :to_default_s, :to_s + + def to_s(format = nil, options = nil) + if format.is_a?(Symbol) + to_formatted_s(format, options || {}) else - format = args[0] || DEFAULT_STRING_FORMAT - _original_to_s(format) + to_default_s(format || DEFAULT_STRING_FORMAT) end end - alias_method :_original_to_s, :to_s - alias_method :to_s, :to_formatted_s end diff --git a/activesupport/lib/active_support/core_ext/numeric/conversions.rb b/activesupport/lib/active_support/core_ext/numeric/conversions.rb index 6d3635c69a..0c8ff79237 100644 --- a/activesupport/lib/active_support/core_ext/numeric/conversions.rb +++ b/activesupport/lib/active_support/core_ext/numeric/conversions.rb @@ -118,18 +118,28 @@ class Numeric end end - [Float, Fixnum, Bignum, BigDecimal].each do |klass| - klass.send(:alias_method, :to_default_s, :to_s) - - klass.send(:define_method, :to_s) do |*args| - if args[0].is_a?(Symbol) - format = args[0] - options = args[1] || {} + [Fixnum, Bignum].each do |klass| + klass.class_eval do + alias_method :to_default_s, :to_s + def to_s(base_or_format = 10, options = nil) + if base_or_format.is_a?(Symbol) + to_formatted_s(base_or_format, options || {}) + else + to_default_s(base_or_format) + end + end + end + end - self.to_formatted_s(format, options) + Float.class_eval do + alias_method :to_default_s, :to_s + def to_s(*args) + if args.empty? + to_default_s else - to_default_s(*args) + to_formatted_s(*args) end end end + end -- cgit v1.2.3 From 2a6b3e14cff61639978a55f47aea9ff4c8e72758 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Fri, 28 Nov 2014 18:42:14 -0200 Subject: Allow failures with Active Job --- .travis.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 7adde8971e..a8b07c7fb2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,7 +9,8 @@ env: matrix: - "GEM=railties" - "GEM=ap" - - "GEM=am,amo,as,av,aj" + - "GEM=aj" + - "GEM=am,amo,as,av" - "GEM=ar:mysql" - "GEM=ar:mysql2" - "GEM=ar:sqlite3" @@ -26,6 +27,7 @@ matrix: env: "GEM=ar:mysql" - rvm: rbx-2 - rvm: jruby + - env: "GEM=aj" fast_finish: true notifications: email: false -- cgit v1.2.3 From b599f99281d54047751e48789c44b73ccaec124c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafael=20Mendon=C3=A7a=20Fran=C3=A7a?= Date: Fri, 28 Nov 2014 18:44:00 -0200 Subject: Allow failures with Active Job integration tests --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index a8b07c7fb2..5352873d8f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,6 +28,7 @@ matrix: - rvm: rbx-2 - rvm: jruby - env: "GEM=aj" + - env: "GEM=aj:integration" fast_finish: true notifications: email: false -- cgit v1.2.3 From 61b39c0e39b23385a9b09565fde9a44f47efe2a5 Mon Sep 17 00:00:00 2001 From: yui-knk Date: Sat, 29 Nov 2014 10:06:40 +0900 Subject: [ci skip] fix class name --- guides/source/i18n.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/i18n.md b/guides/source/i18n.md index f6cbc1823a..75b5275245 100644 --- a/guides/source/i18n.md +++ b/guides/source/i18n.md @@ -626,7 +626,7 @@ entry[count == 1 ? 0 : 1] I.e. the translation denoted as `:one` is regarded as singular, the other is used as plural (including the count being zero). -If the lookup for the key does not return a Hash suitable for pluralization, an `18n::InvalidPluralizationData` exception is raised. +If the lookup for the key does not return a Hash suitable for pluralization, an `I18n::InvalidPluralizationData` exception is raised. ### Setting and Passing a Locale -- cgit v1.2.3 From 74dc57640d856b2a8d424db02b156ded62513eb9 Mon Sep 17 00:00:00 2001 From: claudiob Date: Fri, 28 Nov 2014 18:58:40 -0800 Subject: Remove a reference to Ruby 1.9 in Guides [ci skip] Now that Rails requires Ruby >= 2.0 there is no need to document Ruby 1.9. --- guides/source/active_support_core_extensions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/active_support_core_extensions.md b/guides/source/active_support_core_extensions.md index 616b813817..7b11092f3d 100644 --- a/guides/source/active_support_core_extensions.md +++ b/guides/source/active_support_core_extensions.md @@ -1447,7 +1447,7 @@ Returns the substring of the string starting at position `position`: "hello".from(0) # => "hello" "hello".from(2) # => "llo" "hello".from(-2) # => "lo" -"hello".from(10) # => "" if < 1.9, nil in 1.9 +"hello".from(10) # => nil ``` NOTE: Defined in `active_support/core_ext/string/access.rb`. -- cgit v1.2.3 From 96d0f751f97c7eebc63d02b5dab88eee3aa3a921 Mon Sep 17 00:00:00 2001 From: claudiob Date: Fri, 28 Nov 2014 18:04:19 -0800 Subject: Bump required Ruby version to 2.1.0 [This article](http://weblog.rubyonrails.org/2014/8/20/Rails-4-2-beta1/#maintenance-consequences-and-rails-5-0) states that: > Rails 5.0 is in most likelihood going to target Ruby 2.2. Before the exact minimum version is fully decided, @arthurnn [suggests](https://github.com/rails/rails/pull/17830#issuecomment-64940383) that **at least** version 2.1.0 **must** be required by the `gemspec` files. --- actionmailer/actionmailer.gemspec | 2 +- actionpack/actionpack.gemspec | 2 +- actionview/actionview.gemspec | 2 +- activejob/activejob.gemspec | 2 +- activemodel/activemodel.gemspec | 2 +- activerecord/activerecord.gemspec | 2 +- activesupport/activesupport.gemspec | 2 +- railties/lib/rails/ruby_version_check.rb | 6 +++--- railties/railties.gemspec | 2 +- 9 files changed, 11 insertions(+), 11 deletions(-) diff --git a/actionmailer/actionmailer.gemspec b/actionmailer/actionmailer.gemspec index b63f4e5c08..f3bddd8382 100644 --- a/actionmailer/actionmailer.gemspec +++ b/actionmailer/actionmailer.gemspec @@ -7,7 +7,7 @@ Gem::Specification.new do |s| s.summary = 'Email composition, delivery, and receiving framework (part of Rails).' s.description = 'Email on Rails. Compose, deliver, receive, and test emails using the familiar controller/view pattern. First-class support for multipart email and attachments.' - s.required_ruby_version = '>= 1.9.3' + s.required_ruby_version = '>= 2.1.0' s.license = 'MIT' diff --git a/actionpack/actionpack.gemspec b/actionpack/actionpack.gemspec index 0a49a653d9..0f5880c1a7 100644 --- a/actionpack/actionpack.gemspec +++ b/actionpack/actionpack.gemspec @@ -7,7 +7,7 @@ Gem::Specification.new do |s| s.summary = 'Web-flow and rendering framework putting the VC in MVC (part of Rails).' s.description = 'Web apps on Rails. Simple, battle-tested conventions for building and testing MVC web applications. Works with any Rack-compatible server.' - s.required_ruby_version = '>= 1.9.3' + s.required_ruby_version = '>= 2.1.0' s.license = 'MIT' diff --git a/actionview/actionview.gemspec b/actionview/actionview.gemspec index 28407521cc..fd4ffea33d 100644 --- a/actionview/actionview.gemspec +++ b/actionview/actionview.gemspec @@ -7,7 +7,7 @@ Gem::Specification.new do |s| s.summary = 'Rendering framework putting the V in MVC (part of Rails).' s.description = 'Simple, battle-tested conventions and helpers for building web pages.' - s.required_ruby_version = '>= 1.9.3' + s.required_ruby_version = '>= 2.1.0' s.license = 'MIT' diff --git a/activejob/activejob.gemspec b/activejob/activejob.gemspec index a9be2a8f00..f6c8bc1682 100644 --- a/activejob/activejob.gemspec +++ b/activejob/activejob.gemspec @@ -7,7 +7,7 @@ Gem::Specification.new do |s| s.summary = 'Job framework with pluggable queues.' s.description = 'Declare job classes that can be run by a variety of queueing backends.' - s.required_ruby_version = '>= 1.9.3' + s.required_ruby_version = '>= 2.1.0' s.license = 'MIT' diff --git a/activemodel/activemodel.gemspec b/activemodel/activemodel.gemspec index 36e565f692..73600b83fb 100644 --- a/activemodel/activemodel.gemspec +++ b/activemodel/activemodel.gemspec @@ -7,7 +7,7 @@ Gem::Specification.new do |s| s.summary = 'A toolkit for building modeling frameworks (part of Rails).' s.description = 'A toolkit for building modeling frameworks like Active Record. Rich support for attributes, callbacks, validations, serialization, internationalization, and testing.' - s.required_ruby_version = '>= 1.9.3' + s.required_ruby_version = '>= 2.1.0' s.license = 'MIT' diff --git a/activerecord/activerecord.gemspec b/activerecord/activerecord.gemspec index 834fffeb18..471769a962 100644 --- a/activerecord/activerecord.gemspec +++ b/activerecord/activerecord.gemspec @@ -7,7 +7,7 @@ Gem::Specification.new do |s| s.summary = 'Object-relational mapper framework (part of Rails).' s.description = 'Databases on Rails. Build a persistent domain model by mapping database tables to Ruby classes. Strong conventions for associations, validations, aggregations, migrations, and testing come baked-in.' - s.required_ruby_version = '>= 1.9.3' + s.required_ruby_version = '>= 2.1.0' s.license = 'MIT' diff --git a/activesupport/activesupport.gemspec b/activesupport/activesupport.gemspec index 80d1d35888..f86f5133fc 100644 --- a/activesupport/activesupport.gemspec +++ b/activesupport/activesupport.gemspec @@ -7,7 +7,7 @@ Gem::Specification.new do |s| s.summary = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework.' s.description = 'A toolkit of support libraries and Ruby core extensions extracted from the Rails framework. Rich support for multibyte strings, internationalization, time zones, and testing.' - s.required_ruby_version = '>= 1.9.3' + s.required_ruby_version = '>= 2.1.0' s.license = 'MIT' diff --git a/railties/lib/rails/ruby_version_check.rb b/railties/lib/rails/ruby_version_check.rb index df74643a59..edfe5cb786 100644 --- a/railties/lib/rails/ruby_version_check.rb +++ b/railties/lib/rails/ruby_version_check.rb @@ -1,13 +1,13 @@ -if RUBY_VERSION < '1.9.3' +if RUBY_VERSION < '2.1.0' desc = defined?(RUBY_DESCRIPTION) ? RUBY_DESCRIPTION : "ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE})" abort <<-end_message - Rails 4 prefers to run on Ruby 2.1 or newer. + Rails 5 requires to run on Ruby 2.1 or newer. You're running #{desc} - Please upgrade to Ruby 1.9.3 or newer to continue. + Please upgrade to Ruby 2.1.0 or newer to continue. end_message end diff --git a/railties/railties.gemspec b/railties/railties.gemspec index 56b8736800..09afcdec04 100644 --- a/railties/railties.gemspec +++ b/railties/railties.gemspec @@ -7,7 +7,7 @@ Gem::Specification.new do |s| s.summary = 'Tools for creating, working with, and running Rails applications.' s.description = 'Rails internals: application bootup, plugins, generators, and rake tasks.' - s.required_ruby_version = '>= 1.9.3' + s.required_ruby_version = '>= 2.1.0' s.license = 'MIT' -- cgit v1.2.3 From 56e47cf66d2e3009b4032d0cd2ceb1a6e5e42573 Mon Sep 17 00:00:00 2001 From: Xavier Noria Date: Sat, 29 Nov 2014 08:47:54 +0100 Subject: adds missing period in test.rb [ci skip] --- .../rails/generators/rails/app/templates/config/environments/test.rb.tt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt index 32756eb88b..03a3568fbe 100644 --- a/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt +++ b/railties/lib/rails/generators/rails/app/templates/config/environments/test.rb.tt @@ -31,7 +31,7 @@ Rails.application.configure do # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test - # Randomize the order test cases are executed + # Randomize the order test cases are executed. config.active_support.test_order = :random # Print deprecation notices to the stderr. -- cgit v1.2.3 From d1374f99bf3090f3e659687c112ed0c5c0865cfb Mon Sep 17 00:00:00 2001 From: Erik Michaels-Ober Date: Mon, 27 Oct 2014 17:28:53 +0100 Subject: Pass symbol as an argument instead of a block --- actionmailer/lib/action_mailer/base.rb | 4 +- actionpack/lib/abstract_controller/base.rb | 2 +- actionpack/lib/action_controller/metal/testing.rb | 2 +- actionpack/lib/action_dispatch/http/mime_type.rb | 2 +- .../journey/nfa/transition_table.rb | 2 +- .../lib/action_dispatch/journey/path/pattern.rb | 4 +- actionpack/lib/action_dispatch/journey/route.rb | 6 +- actionpack/lib/action_dispatch/journey/router.rb | 4 +- .../lib/action_dispatch/routing/inspector.rb | 4 +- .../lib/action_dispatch/routing/route_set.rb | 4 +- .../lib/action_dispatch/testing/test_request.rb | 2 +- actionpack/test/abstract_unit.rb | 2 +- actionpack/test/controller/filters_test.rb | 2 +- actionpack/test/controller/routing_test.rb | 8 +-- actionpack/test/dispatch/mime_type_test.rb | 4 +- actionview/lib/action_view/helpers/date_helper.rb | 2 +- .../lib/action_view/helpers/form_options_helper.rb | 4 +- actionview/lib/action_view/helpers/tag_helper.rb | 2 +- actionview/lib/action_view/layouts.rb | 2 +- actionview/lib/action_view/template/error.rb | 2 +- actionview/lib/action_view/template/handlers.rb | 2 +- actionview/lib/action_view/template/resolver.rb | 2 +- actionview/lib/action_view/template/types.rb | 2 +- actionview/test/abstract_unit.rb | 2 +- .../test/actionpack/controller/view_paths_test.rb | 2 +- actionview/test/template/erb_util_test.rb | 2 +- actionview/test/template/render_test.rb | 2 +- .../support/delayed_job/delayed/backend/test.rb | 4 +- .../test/support/integration/adapters/sidekiq.rb | 2 +- .../validations/numericality_validation_test.rb | 4 +- activemodel/test/cases/validations_test.rb | 2 +- activerecord/examples/performance.rb | 4 +- activerecord/lib/active_record/associations.rb | 2 +- .../associations/collection_association.rb | 10 ++-- .../associations/has_many_through_association.rb | 4 +- .../active_record/associations/join_dependency.rb | 2 +- .../associations/preloader/has_many_through.rb | 2 +- .../lib/active_record/attribute_assignment.rb | 2 +- .../lib/active_record/autosave_association.rb | 6 +- .../abstract/connection_pool.rb | 4 +- .../abstract/schema_statements.rb | 2 +- .../connection_adapters/abstract_mysql_adapter.rb | 4 +- .../connection_adapters/mysql_adapter.rb | 4 +- .../connection_adapters/schema_cache.rb | 4 +- .../connection_adapters/sqlite3_adapter.rb | 10 ++-- activerecord/lib/active_record/fixtures.rb | 6 +- activerecord/lib/active_record/inheritance.rb | 2 +- activerecord/lib/active_record/migration.rb | 2 +- activerecord/lib/active_record/model_schema.rb | 2 +- .../lib/active_record/railties/databases.rake | 2 +- .../lib/active_record/readonly_attributes.rb | 2 +- activerecord/lib/active_record/reflection.rb | 2 +- activerecord/lib/active_record/relation.rb | 8 +-- .../lib/active_record/relation/finder_methods.rb | 2 +- activerecord/lib/active_record/serialization.rb | 2 +- activerecord/lib/active_record/statement_cache.rb | 2 +- .../lib/active_record/validations/presence.rb | 2 +- .../test/cases/adapters/mysql/connection_test.rb | 4 +- .../cases/adapters/mysql/reserved_word_test.rb | 4 +- .../test/cases/adapters/mysql/schema_test.rb | 2 +- .../test/cases/adapters/mysql2/connection_test.rb | 4 +- .../cases/adapters/mysql2/reserved_word_test.rb | 4 +- .../test/cases/adapters/mysql2/schema_test.rb | 2 +- .../cases/adapters/postgresql/connection_test.rb | 4 +- .../test/cases/adapters/postgresql/schema_test.rb | 2 +- .../cases/adapters/sqlite3/sqlite3_adapter_test.rb | 8 +-- .../associations/eager_load_nested_include_test.rb | 4 +- activerecord/test/cases/associations/eager_test.rb | 20 +++---- .../has_and_belongs_to_many_associations_test.rb | 2 +- .../associations/has_many_associations_test.rb | 2 +- .../has_many_through_associations_test.rb | 2 +- .../associations/inner_join_association_test.rb | 2 +- .../test/cases/associations/join_model_test.rb | 6 +- activerecord/test/cases/associations_test.rb | 2 +- .../test/cases/autosave_association_test.rb | 22 ++++---- activerecord/test/cases/finder_test.rb | 8 +-- .../cases/migration/column_positioning_test.rb | 12 ++-- activerecord/test/cases/migrator_test.rb | 4 +- activerecord/test/cases/nested_attributes_test.rb | 12 ++-- activerecord/test/cases/persistence_test.rb | 4 +- activerecord/test/cases/pooled_connections_test.rb | 2 +- activerecord/test/cases/reflection_test.rb | 4 +- activerecord/test/cases/relations_test.rb | 8 +-- .../test/cases/scoping/default_scoping_test.rb | 64 +++++++++++----------- activerecord/test/cases/test_case.rb | 2 +- activerecord/test/cases/transactions_test.rb | 6 +- .../test/cases/validations_repair_helper.rb | 8 +-- activerecord/test/models/customer.rb | 2 +- activerecord/test/models/pirate.rb | 4 +- activerecord/test/models/ship.rb | 2 +- activesupport/bin/generate_tables | 2 +- .../active_support/core_ext/array/conversions.rb | 2 +- .../lib/active_support/core_ext/hash/keys.rb | 8 +-- .../lib/active_support/core_ext/object/deep_dup.rb | 2 +- .../core_ext/object/instance_variables.rb | 2 +- .../lib/active_support/core_ext/object/to_query.rb | 2 +- activesupport/lib/active_support/dependencies.rb | 2 +- .../number_helper/number_to_human_converter.rb | 2 +- .../lib/active_support/testing/assertions.rb | 2 +- .../lib/active_support/values/time_zone.rb | 2 +- activesupport/test/core_ext/enumerable_test.rb | 4 +- activesupport/test/core_ext/hash_ext_test.rb | 2 +- activesupport/test/core_ext/object/try_test.rb | 4 +- activesupport/test/core_ext/string_ext_test.rb | 8 +-- activesupport/test/multibyte_chars_test.rb | 2 +- activesupport/test/multibyte_conformance_test.rb | 2 +- activesupport/test/rescuable_test.rb | 4 +- ci/travis.rb | 2 +- guides/rails_guides/kindle.rb | 2 +- railties/lib/rails/application/routes_reloader.rb | 4 +- railties/lib/rails/commands/plugin.rb | 2 +- railties/lib/rails/generators.rb | 4 +- railties/lib/rails/generators/actions.rb | 2 +- railties/lib/rails/generators/base.rb | 2 +- railties/lib/rails/generators/named_base.rb | 4 +- .../rails/generators/rails/app/app_generator.rb | 4 +- railties/lib/rails/generators/resource_helpers.rb | 4 +- railties/lib/rails/info.rb | 4 +- railties/lib/rails/paths.rb | 10 ++-- railties/test/railties/engine_test.rb | 2 +- 120 files changed, 244 insertions(+), 276 deletions(-) diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index 23139bcbe8..a88e884ee8 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -859,7 +859,7 @@ module ActionMailer when user_content_type.present? user_content_type when m.has_attachments? - if m.attachments.detect { |a| a.inline? } + if m.attachments.detect(&:inline?) ["multipart", "related", params] else ["multipart", "mixed", params] @@ -914,7 +914,7 @@ module ActionMailer if templates.empty? raise ActionView::MissingTemplate.new(paths, name, paths, false, 'mailer') else - templates.uniq { |t| t.formats }.each(&block) + templates.uniq(&:formats).each(&block) end end diff --git a/actionpack/lib/abstract_controller/base.rb b/actionpack/lib/abstract_controller/base.rb index 4026dab2ce..51c661f735 100644 --- a/actionpack/lib/abstract_controller/base.rb +++ b/actionpack/lib/abstract_controller/base.rb @@ -82,7 +82,7 @@ module AbstractController # Except for public instance methods of Base and its ancestors internal_methods + # Be sure to include shadowed public instance methods of this class - public_instance_methods(false)).uniq.map { |x| x.to_s } - + public_instance_methods(false)).uniq.map(&:to_s) - # And always exclude explicitly hidden actions hidden_actions.to_a diff --git a/actionpack/lib/action_controller/metal/testing.rb b/actionpack/lib/action_controller/metal/testing.rb index dd8da4b5dc..d01927b7cb 100644 --- a/actionpack/lib/action_controller/metal/testing.rb +++ b/actionpack/lib/action_controller/metal/testing.rb @@ -24,7 +24,7 @@ module ActionController module ClassMethods def before_filters - _process_action_callbacks.find_all{|x| x.kind == :before}.map{|x| x.name} + _process_action_callbacks.find_all{|x| x.kind == :before}.map(&:name) end end end diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index b9d5009683..047a17937a 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -6,7 +6,7 @@ require 'active_support/core_ext/string/starts_ends_with' module Mime class Mimes < Array def symbols - @symbols ||= map { |m| m.to_sym } + @symbols ||= map(&:to_sym) end %w(<< concat shift unshift push pop []= clear compact! collect! diff --git a/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb b/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb index 66e414213a..e65f7238ab 100644 --- a/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb +++ b/actionpack/lib/action_dispatch/journey/nfa/transition_table.rb @@ -107,7 +107,7 @@ module ActionDispatch end def alphabet - inverted.values.flat_map(&:keys).compact.uniq.sort_by { |x| x.to_s } + inverted.values.flat_map(&:keys).compact.uniq.sort_by(&:to_s) end # Returns a set of NFA states reachable from some NFA state +s+ in set diff --git a/actionpack/lib/action_dispatch/journey/path/pattern.rb b/actionpack/lib/action_dispatch/journey/path/pattern.rb index 3af940a02f..dca83e806c 100644 --- a/actionpack/lib/action_dispatch/journey/path/pattern.rb +++ b/actionpack/lib/action_dispatch/journey/path/pattern.rb @@ -42,7 +42,7 @@ module ActionDispatch end def names - @names ||= spec.grep(Nodes::Symbol).map { |n| n.name } + @names ||= spec.grep(Nodes::Symbol).map(&:name) end def required_names @@ -52,7 +52,7 @@ module ActionDispatch def optional_names @optional_names ||= spec.grep(Nodes::Group).flat_map { |group| group.grep(Nodes::Symbol) - }.map { |n| n.name }.uniq + }.map(&:name).uniq end class RegexpOffsets < Journey::Visitors::Visitor # :nodoc: diff --git a/actionpack/lib/action_dispatch/journey/route.rb b/actionpack/lib/action_dispatch/journey/route.rb index 9f0a3af902..3b609a184d 100644 --- a/actionpack/lib/action_dispatch/journey/route.rb +++ b/actionpack/lib/action_dispatch/journey/route.rb @@ -60,7 +60,7 @@ module ActionDispatch end def parts - @parts ||= segments.map { |n| n.to_sym } + @parts ||= segments.map(&:to_sym) end alias :segment_keys :parts @@ -69,11 +69,11 @@ module ActionDispatch end def optional_parts - path.optional_names.map { |n| n.to_sym } + path.optional_names.map(&:to_sym) end def required_parts - @required_parts ||= path.required_names.map { |n| n.to_sym } + @required_parts ||= path.required_names.map(&:to_sym) end def required_default?(key) diff --git a/actionpack/lib/action_dispatch/journey/router.rb b/actionpack/lib/action_dispatch/journey/router.rb index 9131b65380..2b036796ab 100644 --- a/actionpack/lib/action_dispatch/journey/router.rb +++ b/actionpack/lib/action_dispatch/journey/router.rb @@ -68,8 +68,8 @@ module ActionDispatch def visualizer tt = GTG::Builder.new(ast).transition_table - groups = partitioned_routes.first.map(&:ast).group_by { |a| a.to_s } - asts = groups.values.map { |v| v.first } + groups = partitioned_routes.first.map(&:ast).group_by(&:to_s) + asts = groups.values.map(&:first) tt.visualizer(asts) end diff --git a/actionpack/lib/action_dispatch/routing/inspector.rb b/actionpack/lib/action_dispatch/routing/inspector.rb index cfe2237512..df5ebb6751 100644 --- a/actionpack/lib/action_dispatch/routing/inspector.rb +++ b/actionpack/lib/action_dispatch/routing/inspector.rb @@ -114,9 +114,7 @@ module ActionDispatch def collect_routes(routes) routes.collect do |route| RouteWrapper.new(route) - end.reject do |route| - route.internal? - end.collect do |route| + end.reject(&:internal?).collect do |route| collect_engine_routes(route) { name: route.name, diff --git a/actionpack/lib/action_dispatch/routing/route_set.rb b/actionpack/lib/action_dispatch/routing/route_set.rb index 6e3ae36a7f..c2cacbd288 100644 --- a/actionpack/lib/action_dispatch/routing/route_set.rb +++ b/actionpack/lib/action_dispatch/routing/route_set.rb @@ -543,7 +543,7 @@ module ActionDispatch path = conditions.delete :path_info ast = conditions.delete :parsed_path_info path = build_path(path, ast, requirements, anchor) - conditions = build_conditions(conditions, path.names.map { |x| x.to_sym }) + conditions = build_conditions(conditions, path.names.map(&:to_sym)) route = @set.add_route(app, path, conditions, defaults, name) named_routes[name] = route if name @@ -605,7 +605,7 @@ module ActionDispatch if name == :controller value elsif value.is_a?(Array) - value.map { |v| v.to_param }.join('/') + value.map(&:to_param).join('/') elsif param = value.to_param param end diff --git a/actionpack/lib/action_dispatch/testing/test_request.rb b/actionpack/lib/action_dispatch/testing/test_request.rb index de3dc5f924..4b9a088265 100644 --- a/actionpack/lib/action_dispatch/testing/test_request.rb +++ b/actionpack/lib/action_dispatch/testing/test_request.rb @@ -60,7 +60,7 @@ module ActionDispatch def accept=(mime_types) @env.delete('action_dispatch.request.accepts') - @env['HTTP_ACCEPT'] = Array(mime_types).collect { |mime_type| mime_type.to_s }.join(",") + @env['HTTP_ACCEPT'] = Array(mime_types).collect(&:to_s).join(",") end alias :rack_cookies :cookies diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 63c9ab04c9..57c076eac6 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -53,7 +53,7 @@ I18n.enforce_available_locales = false # Register danish language for testing I18n.backend.store_translations 'da', {} I18n.backend.store_translations 'pt-BR', {} -ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort +ORIGINAL_LOCALES = I18n.available_locales.map(&:to_s).sort FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures') FIXTURES = Pathname.new(FIXTURE_LOAD_PATH) diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb index b2b01b3fa9..38533dbf23 100644 --- a/actionpack/test/controller/filters_test.rb +++ b/actionpack/test/controller/filters_test.rb @@ -10,7 +10,7 @@ class ActionController::Base def before_actions filters = _process_action_callbacks.select { |c| c.kind == :before } - filters.map! { |c| c.raw_filter } + filters.map!(&:raw_filter) end end diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index f46b32e019..9caa5cbe57 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -884,13 +884,13 @@ class RouteSetTest < ActiveSupport::TestCase set.draw { get ':controller/(:action(/:id))' } path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") assert_equal "/foo/bar/15", path - assert_equal %w(that this), extras.map { |e| e.to_s }.sort + assert_equal %w(that this), extras.map(&:to_s).sort end def test_extra_keys set.draw { get ':controller/:action/:id' } extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") - assert_equal %w(that this), extras.map { |e| e.to_s }.sort + assert_equal %w(that this), extras.map(&:to_s).sort end def test_generate_extras_not_first @@ -900,7 +900,7 @@ class RouteSetTest < ActiveSupport::TestCase end path, extras = set.generate_extras(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") assert_equal "/foo/bar/15", path - assert_equal %w(that this), extras.map { |e| e.to_s }.sort + assert_equal %w(that this), extras.map(&:to_s).sort end def test_generate_not_first @@ -918,7 +918,7 @@ class RouteSetTest < ActiveSupport::TestCase get ':controller/:action/:id' end extras = set.extra_keys(:controller => "foo", :action => "bar", :id => 15, :this => "hello", :that => "world") - assert_equal %w(that this), extras.map { |e| e.to_s }.sort + assert_equal %w(that this), extras.map(&:to_s).sort end def test_draw diff --git a/actionpack/test/dispatch/mime_type_test.rb b/actionpack/test/dispatch/mime_type_test.rb index ad6335f132..3017a9c2d6 100644 --- a/actionpack/test/dispatch/mime_type_test.rb +++ b/actionpack/test/dispatch/mime_type_test.rb @@ -83,7 +83,7 @@ class MimeTypeTest < ActiveSupport::TestCase test "parse broken acceptlines" do accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/*,,*/*;q=0.5" expect = [Mime::HTML, Mime::XML, "image/*", Mime::TEXT, Mime::ALL] - assert_equal expect, Mime::Type.parse(accept).collect { |c| c.to_s } + assert_equal expect, Mime::Type.parse(accept).collect(&:to_s) end # Accept header send with user HTTP_USER_AGENT: Mozilla/4.0 @@ -91,7 +91,7 @@ class MimeTypeTest < ActiveSupport::TestCase test "parse other broken acceptlines" do accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, , pronto/1.00.00, sslvpn/1.00.00.00, */*" expect = ['image/gif', 'image/x-xbitmap', 'image/jpeg','image/pjpeg', 'application/x-shockwave-flash', 'application/vnd.ms-excel', 'application/vnd.ms-powerpoint', 'application/msword', 'pronto/1.00.00', 'sslvpn/1.00.00.00', Mime::ALL] - assert_equal expect, Mime::Type.parse(accept).collect { |c| c.to_s } + assert_equal expect, Mime::Type.parse(accept).collect(&:to_s) end test "custom type" do diff --git a/actionview/lib/action_view/helpers/date_helper.rb b/actionview/lib/action_view/helpers/date_helper.rb index bd7b36c352..4b4f0ae577 100644 --- a/actionview/lib/action_view/helpers/date_helper.rb +++ b/actionview/lib/action_view/helpers/date_helper.rb @@ -898,7 +898,7 @@ module ActionView def translated_date_order date_order = I18n.translate(:'date.order', :locale => @options[:locale], :default => []) - date_order = date_order.map { |element| element.to_sym } + date_order = date_order.map(&:to_sym) forbidden_elements = date_order - [:year, :month, :day] if forbidden_elements.any? diff --git a/actionview/lib/action_view/helpers/form_options_helper.rb b/actionview/lib/action_view/helpers/form_options_helper.rb index 83b07a00d4..bbfbf482a4 100644 --- a/actionview/lib/action_view/helpers/form_options_helper.rb +++ b/actionview/lib/action_view/helpers/form_options_helper.rb @@ -351,12 +351,12 @@ module ActionView return container if String === container selected, disabled = extract_selected_and_disabled(selected).map do |r| - Array(r).map { |item| item.to_s } + Array(r).map(&:to_s) end container.map do |element| html_attributes = option_html_attributes(element) - text, value = option_text_and_value(element).map { |item| item.to_s } + text, value = option_text_and_value(element).map(&:to_s) html_attributes[:selected] ||= option_value_selected?(value, selected) html_attributes[:disabled] ||= disabled && option_value_selected?(value, disabled) diff --git a/actionview/lib/action_view/helpers/tag_helper.rb b/actionview/lib/action_view/helpers/tag_helper.rb index b2038576a2..a87c223a71 100644 --- a/actionview/lib/action_view/helpers/tag_helper.rb +++ b/actionview/lib/action_view/helpers/tag_helper.rb @@ -18,7 +18,7 @@ module ActionView itemscope allowfullscreen default inert sortable truespeed typemustmatch).to_set - BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map {|attribute| attribute.to_sym }) + BOOLEAN_ATTRIBUTES.merge(BOOLEAN_ATTRIBUTES.map(&:to_sym)) TAG_PREFIXES = ['aria', 'data', :aria, :data].to_set diff --git a/actionview/lib/action_view/layouts.rb b/actionview/lib/action_view/layouts.rb index 9ee05bd816..0b5c0b9991 100644 --- a/actionview/lib/action_view/layouts.rb +++ b/actionview/lib/action_view/layouts.rb @@ -262,7 +262,7 @@ module ActionView def layout(layout, conditions = {}) include LayoutConditions unless conditions.empty? - conditions.each {|k, v| conditions[k] = Array(v).map {|a| a.to_s} } + conditions.each {|k, v| conditions[k] = Array(v).map(&:to_s) } self._layout_conditions = conditions self._layout = layout diff --git a/actionview/lib/action_view/template/error.rb b/actionview/lib/action_view/template/error.rb index 743ef6de0a..390bce98a2 100644 --- a/actionview/lib/action_view/template/error.rb +++ b/actionview/lib/action_view/template/error.rb @@ -75,7 +75,7 @@ module ActionView def sub_template_message if @sub_templates "Trace of template inclusion: " + - @sub_templates.collect { |template| template.inspect }.join(", ") + @sub_templates.collect(&:inspect).join(", ") else "" end diff --git a/actionview/lib/action_view/template/handlers.rb b/actionview/lib/action_view/template/handlers.rb index ff2feb5149..9e61ea4225 100644 --- a/actionview/lib/action_view/template/handlers.rb +++ b/actionview/lib/action_view/template/handlers.rb @@ -42,7 +42,7 @@ module ActionView #:nodoc: end def template_handler_extensions - @@template_handlers.keys.map {|key| key.to_s }.sort + @@template_handlers.keys.map(&:to_s).sort end def registered_template_handler(extension) diff --git a/actionview/lib/action_view/template/resolver.rb b/actionview/lib/action_view/template/resolver.rb index b65507f4a2..29d2e9ca90 100644 --- a/actionview/lib/action_view/template/resolver.rb +++ b/actionview/lib/action_view/template/resolver.rb @@ -139,7 +139,7 @@ module ActionView # resolver is fresher before returning it. def cached(key, path_info, details, locals) #:nodoc: name, prefix, partial = path_info - locals = locals.map { |x| x.to_s }.sort! + locals = locals.map(&:to_s).sort! if key @cache.cache(key, name, prefix, partial, locals) do diff --git a/actionview/lib/action_view/template/types.rb b/actionview/lib/action_view/template/types.rb index b84e0281ae..be45fcf742 100644 --- a/actionview/lib/action_view/template/types.rb +++ b/actionview/lib/action_view/template/types.rb @@ -9,7 +9,7 @@ module ActionView self.types = Set.new def self.register(*t) - types.merge(t.map { |type| type.to_s }) + types.merge(t.map(&:to_s)) end register :html, :text, :js, :css, :xml, :json diff --git a/actionview/test/abstract_unit.rb b/actionview/test/abstract_unit.rb index 7096d588b6..4aa56f60f7 100644 --- a/actionview/test/abstract_unit.rb +++ b/actionview/test/abstract_unit.rb @@ -46,7 +46,7 @@ I18n.enforce_available_locales = false # Register danish language for testing I18n.backend.store_translations 'da', {} I18n.backend.store_translations 'pt-BR', {} -ORIGINAL_LOCALES = I18n.available_locales.map {|locale| locale.to_s }.sort +ORIGINAL_LOCALES = I18n.available_locales.map(&:to_s).sort FIXTURE_LOAD_PATH = File.join(File.dirname(__FILE__), 'fixtures') FIXTURES = Pathname.new(FIXTURE_LOAD_PATH) diff --git a/actionview/test/actionpack/controller/view_paths_test.rb b/actionview/test/actionpack/controller/view_paths_test.rb index c6e7a523b9..7fba9ff8ff 100644 --- a/actionview/test/actionpack/controller/view_paths_test.rb +++ b/actionview/test/actionpack/controller/view_paths_test.rb @@ -39,7 +39,7 @@ class ViewLoadPathsTest < ActionController::TestCase def assert_paths(*paths) controller = paths.first.is_a?(Class) ? paths.shift : @controller - assert_equal expand(paths), controller.view_paths.map { |p| p.to_s } + assert_equal expand(paths), controller.view_paths.map(&:to_s) end def test_template_load_path_was_set_correctly diff --git a/actionview/test/template/erb_util_test.rb b/actionview/test/template/erb_util_test.rb index 3bb84cbc50..3e72be31de 100644 --- a/actionview/test/template/erb_util_test.rb +++ b/actionview/test/template/erb_util_test.rb @@ -84,7 +84,7 @@ class ErbUtilTest < ActiveSupport::TestCase end def test_rest_in_ascii - (0..127).to_a.map {|int| int.chr }.each do |chr| + (0..127).to_a.map(&:chr).each do |chr| next if %('"&<>).include?(chr) assert_equal chr, html_escape(chr) end diff --git a/actionview/test/template/render_test.rb b/actionview/test/template/render_test.rb index 85817119ba..4e502bede9 100644 --- a/actionview/test/template/render_test.rb +++ b/actionview/test/template/render_test.rb @@ -16,7 +16,7 @@ module RenderTestCases I18n.backend.store_translations 'pt-BR', {} # Ensure original are still the same since we are reindexing view paths - assert_equal ORIGINAL_LOCALES, I18n.available_locales.map {|l| l.to_s }.sort + assert_equal ORIGINAL_LOCALES, I18n.available_locales.map(&:to_s).sort end def test_render_without_options diff --git a/activejob/test/support/delayed_job/delayed/backend/test.rb b/activejob/test/support/delayed_job/delayed/backend/test.rb index b50ed36fc2..f80ec3a5a6 100644 --- a/activejob/test/support/delayed_job/delayed/backend/test.rb +++ b/activejob/test/support/delayed_job/delayed/backend/test.rb @@ -43,9 +43,7 @@ module Delayed end def self.create(attrs = {}) - new(attrs).tap do |o| - o.save - end + new(attrs).tap(&:save) end def self.create!(*args); create(*args); end diff --git a/activejob/test/support/integration/adapters/sidekiq.rb b/activejob/test/support/integration/adapters/sidekiq.rb index 3cc9a34993..bdc61a1462 100644 --- a/activejob/test/support/integration/adapters/sidekiq.rb +++ b/activejob/test/support/integration/adapters/sidekiq.rb @@ -48,7 +48,7 @@ module SidekiqJobsManager def can_run? begin - Sidekiq.redis { |conn| conn.connect } + Sidekiq.redis(&:connect) rescue return false end diff --git a/activemodel/test/cases/validations/numericality_validation_test.rb b/activemodel/test/cases/validations/numericality_validation_test.rb index 3834d327ea..12a22f9c40 100644 --- a/activemodel/test/cases/validations/numericality_validation_test.rb +++ b/activemodel/test/cases/validations/numericality_validation_test.rb @@ -59,7 +59,7 @@ class NumericalityValidationTest < ActiveModel::TestCase def test_validates_numericality_of_with_integer_only_and_proc_as_value Topic.send(:define_method, :allow_only_integers?, lambda { false }) - Topic.validates_numericality_of :approved, only_integer: Proc.new {|topic| topic.allow_only_integers? } + Topic.validates_numericality_of :approved, only_integer: Proc.new(&:allow_only_integers?) invalid!(NIL + BLANK + JUNK) valid!(FLOATS + INTEGERS + BIGDECIMAL + INFINITY) @@ -130,7 +130,7 @@ class NumericalityValidationTest < ActiveModel::TestCase def test_validates_numericality_with_proc Topic.send(:define_method, :min_approved, lambda { 5 }) - Topic.validates_numericality_of :approved, greater_than_or_equal_to: Proc.new {|topic| topic.min_approved } + Topic.validates_numericality_of :approved, greater_than_or_equal_to: Proc.new(&:min_approved) invalid!([3, 4]) valid!([5, 6]) diff --git a/activemodel/test/cases/validations_test.rb b/activemodel/test/cases/validations_test.rb index de71bb6f42..98e0266d7e 100644 --- a/activemodel/test/cases/validations_test.rb +++ b/activemodel/test/cases/validations_test.rb @@ -282,7 +282,7 @@ class ValidationsTest < ActiveModel::TestCase ActiveModel::Validations::FormatValidator, ActiveModel::Validations::LengthValidator, ActiveModel::Validations::PresenceValidator - ], validators.map { |v| v.class }.sort_by { |c| c.to_s } + ], validators.map(&:class).sort_by(&:to_s) end def test_list_of_validators_will_be_empty_when_empty diff --git a/activerecord/examples/performance.rb b/activerecord/examples/performance.rb index d3546ce948..a5a1f284a0 100644 --- a/activerecord/examples/performance.rb +++ b/activerecord/examples/performance.rb @@ -39,8 +39,8 @@ class Exhibit < ActiveRecord::Base where("notes IS NOT NULL") end - def self.look(exhibits) exhibits.each { |e| e.look } end - def self.feel(exhibits) exhibits.each { |e| e.feel } end + def self.look(exhibits) exhibits.each(&:look) end + def self.feel(exhibits) exhibits.each(&:feel) end end def progress_bar(int); print "." if (int%100).zero? ; end diff --git a/activerecord/lib/active_record/associations.rb b/activerecord/lib/active_record/associations.rb index d2bcdc55bf..eb21712f96 100644 --- a/activerecord/lib/active_record/associations.rb +++ b/activerecord/lib/active_record/associations.rb @@ -57,7 +57,7 @@ module ActiveRecord through_reflection = reflection.through_reflection source_reflection_names = reflection.source_reflection_names source_associations = reflection.through_reflection.klass._reflections.keys - super("Could not find the source association(s) #{source_reflection_names.collect{ |a| a.inspect }.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => '. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?") + super("Could not find the source association(s) #{source_reflection_names.collect(&:inspect).to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)} in model #{through_reflection.klass}. Try 'has_many #{reflection.name.inspect}, :through => #{through_reflection.name.inspect}, :source => '. Is it one of #{source_associations.to_sentence(:two_words_connector => ' or ', :last_word_connector => ', or ', :locale => :en)}?") end end diff --git a/activerecord/lib/active_record/associations/collection_association.rb b/activerecord/lib/active_record/associations/collection_association.rb index 2b7d39893d..7b6aefe345 100644 --- a/activerecord/lib/active_record/associations/collection_association.rb +++ b/activerecord/lib/active_record/associations/collection_association.rb @@ -62,9 +62,9 @@ module ActiveRecord # Implements the ids writer method, e.g. foo.item_ids= for Foo.has_many :items def ids_writer(ids) pk_type = reflection.primary_key_type - ids = Array(ids).reject { |id| id.blank? } + ids = Array(ids).reject(&:blank?) ids.map! { |i| pk_type.type_cast_from_user(i) } - replace(klass.find(ids).index_by { |r| r.id }.values_at(*ids)) + replace(klass.find(ids).index_by(&:id).values_at(*ids)) end def reset @@ -289,7 +289,7 @@ module ActiveRecord elsif !loaded? && !association_scope.group_values.empty? load_target.size elsif !loaded? && !association_scope.distinct_value && target.is_a?(Array) - unsaved_records = target.select { |r| r.new_record? } + unsaved_records = target.select(&:new_record?) unsaved_records.size + count_records else count_records @@ -506,7 +506,7 @@ module ActiveRecord def delete_or_destroy(records, method) records = records.flatten records.each { |record| raise_on_type_mismatch!(record) } - existing_records = records.reject { |r| r.new_record? } + existing_records = records.reject(&:new_record?) if existing_records.empty? remove_records(existing_records, records, method) @@ -609,7 +609,7 @@ module ActiveRecord # specified, then #find scans the entire collection. def find_by_scan(*args) expects_array = args.first.kind_of?(Array) - ids = args.flatten.compact.map{ |arg| arg.to_s }.uniq + ids = args.flatten.compact.map(&:to_s).uniq if ids.size == 1 id = ids.first 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 6329fdfe95..5cfedcc009 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -161,9 +161,7 @@ module ActiveRecord if scope.klass.primary_key count = scope.destroy_all.length else - scope.each do |record| - record._run_destroy_callbacks - end + scope.each(&:_run_destroy_callbacks) arel = scope.arel diff --git a/activerecord/lib/active_record/associations/join_dependency.rb b/activerecord/lib/active_record/associations/join_dependency.rb index 285d0ec9af..cf63430a97 100644 --- a/activerecord/lib/active_record/associations/join_dependency.rb +++ b/activerecord/lib/active_record/associations/join_dependency.rb @@ -20,7 +20,7 @@ module ActiveRecord end def columns - @tables.flat_map { |t| t.column_aliases } + @tables.flat_map(&:column_aliases) end # An array of [column_name, alias] pairs for the table diff --git a/activerecord/lib/active_record/associations/preloader/has_many_through.rb b/activerecord/lib/active_record/associations/preloader/has_many_through.rb index 7b37b5942d..2029871f39 100644 --- a/activerecord/lib/active_record/associations/preloader/has_many_through.rb +++ b/activerecord/lib/active_record/associations/preloader/has_many_through.rb @@ -8,7 +8,7 @@ module ActiveRecord records_by_owner = super if reflection_scope.distinct_value - records_by_owner.each_value { |records| records.uniq! } + records_by_owner.each_value(&:uniq!) end records_by_owner diff --git a/activerecord/lib/active_record/attribute_assignment.rb b/activerecord/lib/active_record/attribute_assignment.rb index 2887db3bf7..bf64830417 100644 --- a/activerecord/lib/active_record/attribute_assignment.rb +++ b/activerecord/lib/active_record/attribute_assignment.rb @@ -87,7 +87,7 @@ module ActiveRecord end end unless errors.empty? - error_descriptions = errors.map { |ex| ex.message }.join(",") + error_descriptions = errors.map(&:message).join(",") raise MultiparameterAssignmentErrors.new(errors), "#{errors.size} error(s) on assignment of multiparameter attributes [#{error_descriptions}]" end end diff --git a/activerecord/lib/active_record/autosave_association.rb b/activerecord/lib/active_record/autosave_association.rb index a0d70435fa..c39b045a5e 100644 --- a/activerecord/lib/active_record/autosave_association.rb +++ b/activerecord/lib/active_record/autosave_association.rb @@ -263,9 +263,9 @@ module ActiveRecord if new_record association && association.target elsif autosave - association.target.find_all { |record| record.changed_for_autosave? } + association.target.find_all(&:changed_for_autosave?) else - association.target.find_all { |record| record.new_record? } + association.target.find_all(&:new_record?) end end @@ -275,7 +275,7 @@ module ActiveRecord self.class._reflections.values.any? do |reflection| if reflection.options[:autosave] association = association_instance_get(reflection.name) - association && Array.wrap(association.target).any? { |a| a.changed_for_autosave? } + association && Array.wrap(association.target).any?(&:changed_for_autosave?) 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 46812b75bb..3a9db4a109 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb @@ -320,9 +320,7 @@ module ActiveRecord checkin conn conn.disconnect! if conn.requires_reloading? end - @connections.delete_if do |conn| - conn.requires_reloading? - end + @connections.delete_if(&:requires_reloading?) @available.clear @connections.each do |conn| @available.add conn 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 99fa9b7d29..aa7c406050 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb @@ -781,7 +781,7 @@ module ActiveRecord version = version.to_i sm_table = quote_table_name(ActiveRecord::Migrator.schema_migrations_table_name) - migrated = select_values("SELECT version FROM #{sm_table}").map { |v| v.to_i } + migrated = select_values("SELECT version FROM #{sm_table}").map(&:to_i) paths = migrations_paths.map {|p| "#{p}/[0-9]*_*.rb" } versions = Dir[*paths].map do |filename| filename.split('/').last.split('_').first.to_i 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 c824a7b11b..bf16804aa0 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract_mysql_adapter.rb @@ -398,7 +398,7 @@ module ActiveRecord sql << "LIKE #{quote(like)}" if like execute_and_free(sql, 'SCHEMA') do |result| - result.collect { |field| field.first } + result.collect(&:first) end end @@ -786,7 +786,7 @@ module ActiveRecord private def version - @version ||= full_version.scan(/^(\d+)\.(\d+)\.(\d+)/).flatten.map { |v| v.to_i } + @version ||= full_version.scan(/^(\d+)\.(\d+)\.(\d+)/).flatten.map(&:to_i) end def mariadb? diff --git a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb index 53ad71b445..23d8389abb 100644 --- a/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/mysql_adapter.rb @@ -423,9 +423,7 @@ module ActiveRecord cols = nil if metadata = stmt.result_metadata - cols = cache[:cols] ||= metadata.fetch_fields.map { |field| - field.name - } + cols = cache[:cols] ||= metadata.fetch_fields.map(&:name) metadata.free end diff --git a/activerecord/lib/active_record/connection_adapters/schema_cache.rb b/activerecord/lib/active_record/connection_adapters/schema_cache.rb index a10ce330c7..37ff4e4613 100644 --- a/activerecord/lib/active_record/connection_adapters/schema_cache.rb +++ b/activerecord/lib/active_record/connection_adapters/schema_cache.rb @@ -61,9 +61,7 @@ module ActiveRecord end def size - [@columns, @columns_hash, @primary_keys, @tables].map { |x| - x.size - }.inject :+ + [@columns, @columns_hash, @primary_keys, @tables].map(&:size).inject :+ end # Clear out internal caches for table with +table_name+. diff --git a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb index 0b8b6a2bf8..c3865a8fdd 100644 --- a/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb +++ b/activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb @@ -88,11 +88,11 @@ module ActiveRecord include Comparable def initialize(version_string) - @version = version_string.split('.').map { |v| v.to_i } + @version = version_string.split('.').map(&:to_i) end def <=>(version_string) - @version <=> version_string.split('.').map { |v| v.to_i } + @version <=> version_string.split('.').map(&:to_i) end end @@ -556,7 +556,7 @@ module ActiveRecord end copy_table_indexes(from, to, options[:rename] || {}) copy_table_contents(from, to, - @definition.columns.map {|column| column.name}, + @definition.columns.map(&:name), options[:rename] || {}) end @@ -569,7 +569,7 @@ module ActiveRecord name = name[1..-1] end - to_column_names = columns(to).map { |c| c.name } + to_column_names = columns(to).map(&:name) columns = index.columns.map {|c| rename[c] || c }.select do |column| to_column_names.include?(column) end @@ -586,7 +586,7 @@ module ActiveRecord def copy_table_contents(from, to, columns, rename = {}) #:nodoc: column_mappings = Hash[columns.map {|name| [name, name]}] rename.each { |a| column_mappings[a.last] = a.first } - from_columns = columns(from).collect {|col| col.name} + from_columns = columns(from).collect(&:name) columns = columns.find_all{|col| from_columns.include?(column_mappings[col])} quoted_columns = columns.map { |col| quote_column_name(col) } * ',' diff --git a/activerecord/lib/active_record/fixtures.rb b/activerecord/lib/active_record/fixtures.rb index 7c53ee0a9a..4732462b05 100644 --- a/activerecord/lib/active_record/fixtures.rb +++ b/activerecord/lib/active_record/fixtures.rb @@ -745,7 +745,7 @@ module ActiveRecord end def column_names - @column_names ||= @connection.columns(@table_name).collect { |c| c.name } + @column_names ||= @connection.columns(@table_name).collect(&:name) end def read_fixture_files(path, model_class) @@ -868,7 +868,7 @@ module ActiveRecord fixture_set_names = Dir["#{fixture_path}/{**,*}/*.{yml}"] fixture_set_names.map! { |f| f[(fixture_path.to_s.size + 1)..-5] } else - fixture_set_names = fixture_set_names.flatten.map { |n| n.to_s } + fixture_set_names = fixture_set_names.flatten.map(&:to_s) end self.fixture_table_names |= fixture_set_names @@ -908,7 +908,7 @@ module ActiveRecord def uses_transaction(*methods) @uses_transaction = [] unless defined?(@uses_transaction) - @uses_transaction.concat methods.map { |m| m.to_s } + @uses_transaction.concat methods.map(&:to_s) end def uses_transaction?(method) diff --git a/activerecord/lib/active_record/inheritance.rb b/activerecord/lib/active_record/inheritance.rb index f58145ab05..b91e9ac137 100644 --- a/activerecord/lib/active_record/inheritance.rb +++ b/activerecord/lib/active_record/inheritance.rb @@ -192,7 +192,7 @@ module ActiveRecord def type_condition(table = arel_table) sti_column = table[inheritance_column] - sti_names = ([self] + descendants).map { |model| model.sti_name } + sti_names = ([self] + descendants).map(&:sti_name) sti_column.in(sti_names) end diff --git a/activerecord/lib/active_record/migration.rb b/activerecord/lib/active_record/migration.rb index 92f2951f2d..3cac465440 100644 --- a/activerecord/lib/active_record/migration.rb +++ b/activerecord/lib/active_record/migration.rb @@ -647,7 +647,7 @@ module ActiveRecord end def method_missing(method, *arguments, &block) - arg_list = arguments.map{ |a| a.inspect } * ', ' + arg_list = arguments.map(&:inspect) * ', ' say_with_time "#{method}(#{arg_list})" do unless @connection.respond_to? :revert diff --git a/activerecord/lib/active_record/model_schema.rb b/activerecord/lib/active_record/model_schema.rb index adad7774b9..92ad9c9101 100644 --- a/activerecord/lib/active_record/model_schema.rb +++ b/activerecord/lib/active_record/model_schema.rb @@ -257,7 +257,7 @@ module ActiveRecord # Returns an array of column names as strings. def column_names - @column_names ||= columns.map { |column| column.name } + @column_names ||= columns.map(&:name) end # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count", diff --git a/activerecord/lib/active_record/railties/databases.rake b/activerecord/lib/active_record/railties/databases.rake index 21b1c3f721..6c09456c4d 100644 --- a/activerecord/lib/active_record/railties/databases.rake +++ b/activerecord/lib/active_record/railties/databases.rake @@ -366,7 +366,7 @@ namespace :railties do namespace :install do # desc "Copies missing migrations from Railties (e.g. engines). You can specify Railties to use with FROM=railtie1,railtie2" task :migrations => :'db:load_config' do - to_load = ENV['FROM'].blank? ? :all : ENV['FROM'].split(",").map {|n| n.strip } + to_load = ENV['FROM'].blank? ? :all : ENV['FROM'].split(",").map(&:strip) railties = {} Rails.application.migration_railties.each do |railtie| next unless to_load == :all || to_load.include?(railtie.railtie_name) diff --git a/activerecord/lib/active_record/readonly_attributes.rb b/activerecord/lib/active_record/readonly_attributes.rb index 85bbac43e4..ce78f1756d 100644 --- a/activerecord/lib/active_record/readonly_attributes.rb +++ b/activerecord/lib/active_record/readonly_attributes.rb @@ -11,7 +11,7 @@ module ActiveRecord # Attributes listed as readonly will be used to create a new record but update operations will # ignore these fields. def attr_readonly(*attributes) - self._attr_readonly = Set.new(attributes.map { |a| a.to_s }) + (self._attr_readonly || []) + self._attr_readonly = Set.new(attributes.map(&:to_s)) + (self._attr_readonly || []) end # Returns an array of all the attributes that have been specified as readonly. diff --git a/activerecord/lib/active_record/reflection.rb b/activerecord/lib/active_record/reflection.rb index 4219632596..96520d1d49 100644 --- a/activerecord/lib/active_record/reflection.rb +++ b/activerecord/lib/active_record/reflection.rb @@ -791,7 +791,7 @@ module ActiveRecord def source_reflection_name # :nodoc: return @source_reflection_name if @source_reflection_name - names = [name.to_s.singularize, name].collect { |n| n.to_sym }.uniq + names = [name.to_s.singularize, name].collect(&:to_sym).uniq names = names.find_all { |n| through_reflection.klass._reflect_on_association(n) } diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 561ed222d1..7e1994086f 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -400,7 +400,7 @@ module ActiveRecord if conditions where(conditions).destroy_all else - to_a.each {|object| object.destroy }.tap { reset } + to_a.each(&:destroy).tap { reset } end end @@ -644,7 +644,7 @@ module ActiveRecord preloader.preload @records, associations end - @records.each { |record| record.readonly! } if readonly_value + @records.each(&:readonly!) if readonly_value @loaded = true @records @@ -666,7 +666,7 @@ module ActiveRecord joined_tables += [table.name, table.table_alias] # always convert table names to downcase as in Oracle quoted table names are in uppercase - joined_tables = joined_tables.flatten.compact.map { |t| t.downcase }.uniq + joined_tables = joined_tables.flatten.compact.map(&:downcase).uniq (references_values - joined_tables).any? end @@ -675,7 +675,7 @@ module ActiveRecord return [] if string.blank? # always convert table names to downcase as in Oracle quoted table names are in uppercase # ignore raw_sql_ that is used by Oracle adapter as alias for limit/offset subqueries - string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map{ |s| s.downcase }.uniq - ['raw_sql_'] + string.scan(/([a-zA-Z_][.\w]+).?\./).flatten.map(&:downcase).uniq - ['raw_sql_'] end end end diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index eacae73ebb..5061940d82 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -415,7 +415,7 @@ module ActiveRecord end def using_limitable_reflections?(reflections) - reflections.none? { |r| r.collection? } + reflections.none?(&:collection?) end protected diff --git a/activerecord/lib/active_record/serialization.rb b/activerecord/lib/active_record/serialization.rb index bd9079b596..48c12dcf9f 100644 --- a/activerecord/lib/active_record/serialization.rb +++ b/activerecord/lib/active_record/serialization.rb @@ -11,7 +11,7 @@ module ActiveRecord #:nodoc: def serializable_hash(options = nil) options = options.try(:clone) || {} - options[:except] = Array(options[:except]).map { |n| n.to_s } + options[:except] = Array(options[:except]).map(&:to_s) options[:except] |= Array(self.class.inheritance_column) super(options) diff --git a/activerecord/lib/active_record/statement_cache.rb b/activerecord/lib/active_record/statement_cache.rb index c68990bf99..192a19f05d 100644 --- a/activerecord/lib/active_record/statement_cache.rb +++ b/activerecord/lib/active_record/statement_cache.rb @@ -79,7 +79,7 @@ module ActiveRecord end def bind(values) - bvs = @bind_values.map { |pair| pair.dup } + bvs = @bind_values.map(&:dup) @indexes.each_with_index { |offset,i| bvs[offset][1] = values[i] } bvs end diff --git a/activerecord/lib/active_record/validations/presence.rb b/activerecord/lib/active_record/validations/presence.rb index c7aa814ba8..61b30749d9 100644 --- a/activerecord/lib/active_record/validations/presence.rb +++ b/activerecord/lib/active_record/validations/presence.rb @@ -8,7 +8,7 @@ module ActiveRecord associated_records = Array.wrap(record.send(attribute)) # Superclass validates presence. Ensure present records aren't about to be destroyed. - if associated_records.present? && associated_records.all? { |r| r.marked_for_destruction? } + if associated_records.present? && associated_records.all?(&:marked_for_destruction?) record.errors.add(attribute, :blank, options) end end diff --git a/activerecord/test/cases/adapters/mysql/connection_test.rb b/activerecord/test/cases/adapters/mysql/connection_test.rb index 52eebe1886..ce01b16362 100644 --- a/activerecord/test/cases/adapters/mysql/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql/connection_test.rb @@ -47,9 +47,7 @@ class MysqlConnectionTest < ActiveRecord::TestCase assert !@connection.active? # Repair all fixture connections so other tests won't break. - @fixture_connections.each do |c| - c.verify! - end + @fixture_connections.each(&:verify!) end def test_successful_reconnection_after_timeout_with_manual_reconnect diff --git a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb index 61ae0abfd1..403f7cbc74 100644 --- a/activerecord/test/cases/adapters/mysql/reserved_word_test.rb +++ b/activerecord/test/cases/adapters/mysql/reserved_word_test.rb @@ -101,7 +101,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase gs = nil assert_nothing_raised { gs = Select.find(2).groups } assert_equal gs.length, 2 - assert(gs.collect{|x| x.id}.sort == [2, 3]) + assert(gs.collect(&:id).sort == [2, 3]) end # has_and_belongs_to_many with reserved-word table name @@ -110,7 +110,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase s = nil assert_nothing_raised { s = Distinct.find(1).selects } assert_equal s.length, 2 - assert(s.collect{|x|x.id}.sort == [1, 2]) + assert(s.collect(&:id).sort == [1, 2]) end # activerecord model introspection with reserved-word table and column names diff --git a/activerecord/test/cases/adapters/mysql/schema_test.rb b/activerecord/test/cases/adapters/mysql/schema_test.rb index 87c5277e64..ab547747df 100644 --- a/activerecord/test/cases/adapters/mysql/schema_test.rb +++ b/activerecord/test/cases/adapters/mysql/schema_test.rb @@ -81,7 +81,7 @@ module ActiveRecord table = 'key_tests' - indexes = @connection.indexes(table).sort_by {|i| i.name} + indexes = @connection.indexes(table).sort_by(&:name) assert_equal 3,indexes.size index_a = indexes.select{|i| i.name == index_a_name}[0] diff --git a/activerecord/test/cases/adapters/mysql2/connection_test.rb b/activerecord/test/cases/adapters/mysql2/connection_test.rb index 62c5abbf41..d261e2db55 100644 --- a/activerecord/test/cases/adapters/mysql2/connection_test.rb +++ b/activerecord/test/cases/adapters/mysql2/connection_test.rb @@ -44,9 +44,7 @@ class MysqlConnectionTest < ActiveRecord::TestCase assert !@connection.active? # Repair all fixture connections so other tests won't break. - @fixture_connections.each do |c| - c.verify! - end + @fixture_connections.each(&:verify!) end def test_successful_reconnection_after_timeout_with_manual_reconnect diff --git a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb index 799d927ee4..7f97b454bb 100644 --- a/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb +++ b/activerecord/test/cases/adapters/mysql2/reserved_word_test.rb @@ -100,7 +100,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase gs = nil assert_nothing_raised { gs = Select.find(2).groups } assert_equal gs.length, 2 - assert(gs.collect{|x| x.id}.sort == [2, 3]) + assert(gs.collect(&:id).sort == [2, 3]) end # has_and_belongs_to_many with reserved-word table name @@ -109,7 +109,7 @@ class MysqlReservedWordTest < ActiveRecord::TestCase s = nil assert_nothing_raised { s = Distinct.find(1).selects } assert_equal s.length, 2 - assert(s.collect{|x|x.id}.sort == [1, 2]) + assert(s.collect(&:id).sort == [1, 2]) end # activerecord model introspection with reserved-word table and column names diff --git a/activerecord/test/cases/adapters/mysql2/schema_test.rb b/activerecord/test/cases/adapters/mysql2/schema_test.rb index 1b7e60565d..47707b7d4f 100644 --- a/activerecord/test/cases/adapters/mysql2/schema_test.rb +++ b/activerecord/test/cases/adapters/mysql2/schema_test.rb @@ -51,7 +51,7 @@ module ActiveRecord table = 'key_tests' - indexes = @connection.indexes(table).sort_by {|i| i.name} + indexes = @connection.indexes(table).sort_by(&:name) assert_equal 3,indexes.size index_a = indexes.select{|i| i.name == index_a_name}[0] diff --git a/activerecord/test/cases/adapters/postgresql/connection_test.rb b/activerecord/test/cases/adapters/postgresql/connection_test.rb index 7d179944d4..ab7fd3c6d5 100644 --- a/activerecord/test/cases/adapters/postgresql/connection_test.rb +++ b/activerecord/test/cases/adapters/postgresql/connection_test.rb @@ -177,9 +177,7 @@ module ActiveRecord "successfully querying with the same connection pid." # Repair all fixture connections so other tests won't break. - @fixture_connections.each do |c| - c.verify! - end + @fixture_connections.each(&:verify!) end def test_set_session_variable_true diff --git a/activerecord/test/cases/adapters/postgresql/schema_test.rb b/activerecord/test/cases/adapters/postgresql/schema_test.rb index 350cb3e065..92c9a13ee3 100644 --- a/activerecord/test/cases/adapters/postgresql/schema_test.rb +++ b/activerecord/test/cases/adapters/postgresql/schema_test.rb @@ -412,7 +412,7 @@ class SchemaTest < ActiveRecord::TestCase def do_dump_index_tests_for_schema(this_schema_name, first_index_column_name, second_index_column_name, third_index_column_name, fourth_index_column_name) with_schema_search_path(this_schema_name) do - indexes = @connection.indexes(TABLE_NAME).sort_by {|i| i.name} + indexes = @connection.indexes(TABLE_NAME).sort_by(&:name) assert_equal 4,indexes.size do_dump_index_assertions_for_one_index(indexes[0], INDEX_A_NAME, first_index_column_name) diff --git a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb index d83c65cf0e..9d09ff49c7 100644 --- a/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb +++ b/activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb @@ -327,11 +327,11 @@ module ActiveRecord def test_columns with_example_table do - columns = @conn.columns('ex').sort_by { |x| x.name } + columns = @conn.columns('ex').sort_by(&:name) assert_equal 2, columns.length - assert_equal %w{ id number }.sort, columns.map { |x| x.name } - assert_equal [nil, nil], columns.map { |x| x.default } - assert_equal [true, true], columns.map { |x| x.null } + assert_equal %w{ id number }.sort, columns.map(&:name) + assert_equal [nil, nil], columns.map(&:default) + assert_equal [true, true], columns.map(&:null) end end diff --git a/activerecord/test/cases/associations/eager_load_nested_include_test.rb b/activerecord/test/cases/associations/eager_load_nested_include_test.rb index 0ff87d53ea..f571198079 100644 --- a/activerecord/test/cases/associations/eager_load_nested_include_test.rb +++ b/activerecord/test/cases/associations/eager_load_nested_include_test.rb @@ -70,9 +70,7 @@ class EagerLoadPolyAssocsTest < ActiveRecord::TestCase teardown do [Circle, Square, Triangle, PaintColor, PaintTexture, - ShapeExpression, NonPolyOne, NonPolyTwo].each do |c| - c.delete_all - end + ShapeExpression, NonPolyOne, NonPolyTwo].each(&:delete_all) end def generate_test_object_graphs diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb index f968a34886..4321a198ca 100644 --- a/activerecord/test/cases/associations/eager_test.rb +++ b/activerecord/test/cases/associations/eager_test.rb @@ -338,31 +338,31 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_association_loading_with_belongs_to_and_limit comments = Comment.all.merge!(:includes => :post, :limit => 5, :order => 'comments.id').to_a assert_equal 5, comments.length - assert_equal [1,2,3,5,6], comments.collect { |c| c.id } + assert_equal [1,2,3,5,6], comments.collect(&:id) end def test_eager_association_loading_with_belongs_to_and_limit_and_conditions comments = Comment.all.merge!(:includes => :post, :where => 'post_id = 4', :limit => 3, :order => 'comments.id').to_a assert_equal 3, comments.length - assert_equal [5,6,7], comments.collect { |c| c.id } + assert_equal [5,6,7], comments.collect(&:id) end def test_eager_association_loading_with_belongs_to_and_limit_and_offset comments = Comment.all.merge!(:includes => :post, :limit => 3, :offset => 2, :order => 'comments.id').to_a assert_equal 3, comments.length - assert_equal [3,5,6], comments.collect { |c| c.id } + assert_equal [3,5,6], comments.collect(&:id) end def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions comments = Comment.all.merge!(:includes => :post, :where => 'post_id = 4', :limit => 3, :offset => 1, :order => 'comments.id').to_a assert_equal 3, comments.length - assert_equal [6,7,8], comments.collect { |c| c.id } + assert_equal [6,7,8], comments.collect(&:id) end def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_conditions_array comments = Comment.all.merge!(:includes => :post, :where => ['post_id = ?',4], :limit => 3, :offset => 1, :order => 'comments.id').to_a assert_equal 3, comments.length - assert_equal [6,7,8], comments.collect { |c| c.id } + assert_equal [6,7,8], comments.collect(&:id) end def test_eager_association_loading_with_belongs_to_and_conditions_string_with_unquoted_table_name @@ -377,7 +377,7 @@ class EagerAssociationTest < ActiveRecord::TestCase comments = Comment.all.merge!(:includes => :post, :where => {:posts => {:id => 4}}, :limit => 3, :order => 'comments.id').to_a end assert_equal 3, comments.length - assert_equal [5,6,7], comments.collect { |c| c.id } + assert_equal [5,6,7], comments.collect(&:id) assert_no_queries do comments.first.post end @@ -406,13 +406,13 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_association_loading_with_belongs_to_and_limit_and_multiple_associations posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :order => 'posts.id').to_a assert_equal 1, posts.length - assert_equal [1], posts.collect { |p| p.id } + assert_equal [1], posts.collect(&:id) end def test_eager_association_loading_with_belongs_to_and_limit_and_offset_and_multiple_associations posts = Post.all.merge!(:includes => [:author, :very_special_comment], :limit => 1, :offset => 1, :order => 'posts.id').to_a assert_equal 1, posts.length - assert_equal [2], posts.collect { |p| p.id } + assert_equal [2], posts.collect(&:id) end def test_eager_association_loading_with_belongs_to_inferred_foreign_key_from_association_name @@ -545,13 +545,13 @@ class EagerAssociationTest < ActiveRecord::TestCase def test_eager_with_has_many_and_limit_and_conditions posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => "posts.body = 'hello'", :order => "posts.id").to_a assert_equal 2, posts.size - assert_equal [4,5], posts.collect { |p| p.id } + assert_equal [4,5], posts.collect(&:id) end def test_eager_with_has_many_and_limit_and_conditions_array posts = Post.all.merge!(:includes => [ :author, :comments ], :limit => 2, :where => [ "posts.body = ?", 'hello' ], :order => "posts.id").to_a assert_equal 2, posts.size - assert_equal [4,5], posts.collect { |p| p.id } + assert_equal [4,5], posts.collect(&:id) end def test_eager_with_has_many_and_limit_and_conditions_array_on_the_eagers 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 092e85949c..aea9207bfe 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 @@ -555,7 +555,7 @@ class HasAndBelongsToManyAssociationsTest < ActiveRecord::TestCase def test_dynamic_find_all_should_respect_readonly_access projects(:active_record).readonly_developers.each { |d| assert_raise(ActiveRecord::ReadOnlyRecord) { d.save! } if d.valid?} - projects(:active_record).readonly_developers.each { |d| d.readonly? } + projects(:active_record).readonly_developers.each(&:readonly?) end def test_new_with_values_in_collection diff --git a/activerecord/test/cases/associations/has_many_associations_test.rb b/activerecord/test/cases/associations/has_many_associations_test.rb index 9510d57de6..c075872617 100644 --- a/activerecord/test/cases/associations/has_many_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_associations_test.rb @@ -1219,7 +1219,7 @@ class HasManyAssociationsTest < ActiveRecord::TestCase assert !clients.empty?, "37signals has clients after load" destroyed = companies(:first_firm).clients_of_firm.destroy_all assert_equal clients.sort_by(&:id), destroyed.sort_by(&:id) - assert destroyed.all? { |client| client.frozen? }, "destroyed clients should be frozen" + assert destroyed.all?(&:frozen?), "destroyed clients should be frozen" assert companies(:first_firm).clients_of_firm.empty?, "37signals has no clients after destroy all" assert companies(:first_firm).clients_of_firm(true).empty?, "37signals has no clients after destroy all and refresh" 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 d523ea4f07..589a232bdb 100644 --- a/activerecord/test/cases/associations/has_many_through_associations_test.rb +++ b/activerecord/test/cases/associations/has_many_through_associations_test.rb @@ -41,7 +41,7 @@ class HasManyThroughAssociationsTest < ActiveRecord::TestCase def test_preload_sti_rhs_class developers = Developer.includes(:firms).all.to_a assert_no_queries do - developers.each { |d| d.firms } + developers.each(&:firms) end end diff --git a/activerecord/test/cases/associations/inner_join_association_test.rb b/activerecord/test/cases/associations/inner_join_association_test.rb index 07cf65a760..9938302885 100644 --- a/activerecord/test/cases/associations/inner_join_association_test.rb +++ b/activerecord/test/cases/associations/inner_join_association_test.rb @@ -54,7 +54,7 @@ class InnerJoinAssociationTest < ActiveRecord::TestCase def test_find_with_implicit_inner_joins_without_select_does_not_imply_readonly authors = Author.joins(:posts) assert_not authors.empty?, "expected authors to be non-empty" - assert authors.none? {|a| a.readonly? }, "expected no authors to be readonly" + assert authors.none?(&:readonly?), "expected no authors to be readonly" end def test_find_with_implicit_inner_joins_honors_readonly_with_select diff --git a/activerecord/test/cases/associations/join_model_test.rb b/activerecord/test/cases/associations/join_model_test.rb index cace7ba142..140ccdac72 100644 --- a/activerecord/test/cases/associations/join_model_test.rb +++ b/activerecord/test/cases/associations/join_model_test.rb @@ -393,18 +393,18 @@ class AssociationsJoinModelTest < ActiveRecord::TestCase end def test_has_many_through_polymorphic_has_one - assert_equal Tagging.find(1,2).sort_by { |t| t.id }, authors(:david).taggings_2 + assert_equal Tagging.find(1,2).sort_by(&:id), authors(:david).taggings_2 end def test_has_many_through_polymorphic_has_many - assert_equal taggings(:welcome_general, :thinking_general), authors(:david).taggings.distinct.sort_by { |t| t.id } + assert_equal taggings(:welcome_general, :thinking_general), authors(:david).taggings.distinct.sort_by(&:id) end def test_include_has_many_through_polymorphic_has_many author = Author.includes(:taggings).find authors(:david).id expected_taggings = taggings(:welcome_general, :thinking_general) assert_no_queries do - assert_equal expected_taggings, author.taggings.distinct.sort_by { |t| t.id } + assert_equal expected_taggings, author.taggings.distinct.sort_by(&:id) end end diff --git a/activerecord/test/cases/associations_test.rb b/activerecord/test/cases/associations_test.rb index 04ef50e58a..c6769edcbf 100644 --- a/activerecord/test/cases/associations_test.rb +++ b/activerecord/test/cases/associations_test.rb @@ -48,7 +48,7 @@ class AssociationsTest < ActiveRecord::TestCase assert_kind_of Firm, firm firm.clear_association_cache - assert_equal Firm.find(1).clients.collect{ |x| x.name }.sort, firm.clients.collect{ |x| x.name }.sort + assert_equal Firm.find(1).clients.collect(&:name).sort, firm.clients.collect(&:name).sort end def test_clear_association_cache_new_record diff --git a/activerecord/test/cases/autosave_association_test.rb b/activerecord/test/cases/autosave_association_test.rb index 71c34d816a..04d5a2869c 100644 --- a/activerecord/test/cases/autosave_association_test.rb +++ b/activerecord/test/cases/autosave_association_test.rb @@ -774,13 +774,13 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase def test_should_destroy_has_many_as_part_of_the_save_transaction_if_they_were_marked_for_destruction 2.times { |i| @pirate.birds.create!(:name => "birds_#{i}") } - assert !@pirate.birds.any? { |child| child.marked_for_destruction? } + assert !@pirate.birds.any?(&:marked_for_destruction?) - @pirate.birds.each { |child| child.mark_for_destruction } + @pirate.birds.each(&:mark_for_destruction) klass = @pirate.birds.first.class ids = @pirate.birds.map(&:id) - assert @pirate.birds.all? { |child| child.marked_for_destruction? } + assert @pirate.birds.all?(&:marked_for_destruction?) ids.each { |id| assert klass.find_by_id(id) } @pirate.save @@ -814,14 +814,14 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase @pirate.birds.each { |bird| bird.name = '' } assert !@pirate.valid? - @pirate.birds.each { |bird| bird.destroy } + @pirate.birds.each(&:destroy) assert @pirate.valid? end def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_has_many @pirate.birds.create!(:name => "birds_1") - @pirate.birds.each { |bird| bird.mark_for_destruction } + @pirate.birds.each(&:mark_for_destruction) assert @pirate.save @pirate.birds.each { |bird| bird.expects(:destroy).never } @@ -888,7 +888,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase association_name_with_callbacks = "birds_with_#{callback_type}_callbacks" @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed") - @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction } + @pirate.send(association_name_with_callbacks).each(&:mark_for_destruction) child_id = @pirate.send(association_name_with_callbacks).first.id @pirate.ship_log.clear @@ -906,8 +906,8 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase def test_should_destroy_habtm_as_part_of_the_save_transaction_if_they_were_marked_for_destruction 2.times { |i| @pirate.parrots.create!(:name => "parrots_#{i}") } - assert !@pirate.parrots.any? { |parrot| parrot.marked_for_destruction? } - @pirate.parrots.each { |parrot| parrot.mark_for_destruction } + assert !@pirate.parrots.any?(&:marked_for_destruction?) + @pirate.parrots.each(&:mark_for_destruction) assert_no_difference "Parrot.count" do @pirate.save @@ -940,14 +940,14 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase @pirate.parrots.each { |parrot| parrot.name = '' } assert !@pirate.valid? - @pirate.parrots.each { |parrot| parrot.destroy } + @pirate.parrots.each(&:destroy) assert @pirate.valid? end def test_a_child_marked_for_destruction_should_not_be_destroyed_twice_while_saving_habtm @pirate.parrots.create!(:name => "parrots_1") - @pirate.parrots.each { |parrot| parrot.mark_for_destruction } + @pirate.parrots.each(&:mark_for_destruction) assert @pirate.save Pirate.transaction do @@ -992,7 +992,7 @@ class TestDestroyAsPartOfAutosaveAssociation < ActiveRecord::TestCase association_name_with_callbacks = "parrots_with_#{callback_type}_callbacks" @pirate.send(association_name_with_callbacks).create!(:name => "Crowe the One-Eyed") - @pirate.send(association_name_with_callbacks).each { |c| c.mark_for_destruction } + @pirate.send(association_name_with_callbacks).each(&:mark_for_destruction) child_id = @pirate.send(association_name_with_callbacks).first.id @pirate.ship_log.clear diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 33a59d4678..a607c1319f 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -934,7 +934,7 @@ class FinderTest < ActiveRecord::TestCase joins('LEFT JOIN developers_projects ON developers.id = developers_projects.developer_id'). where('project_id=1').to_a assert_equal 3, developers_on_project_one.length - developer_names = developers_on_project_one.map { |d| d.name } + developer_names = developers_on_project_one.map(&:name) assert developer_names.include?('David') assert developer_names.include?('Jamis') end @@ -989,7 +989,7 @@ class FinderTest < ActiveRecord::TestCase end def test_select_values - assert_equal ["1","2","3","4","5","6","7","8","9", "10", "11"], Company.connection.select_values("SELECT id FROM companies ORDER BY id").map! { |i| i.to_s } + assert_equal ["1","2","3","4","5","6","7","8","9", "10", "11"], Company.connection.select_values("SELECT id FROM companies ORDER BY id").map!(&:to_s) assert_equal ["37signals","Summit","Microsoft", "Flamboyant Software", "Ex Nihilo", "RailsCore", "Leetsoft", "Jadedpixel", "Odegy", "Ex Nihilo Part Deux", "Apex"], Company.connection.select_values("SELECT name FROM companies ORDER BY id") end @@ -1015,7 +1015,7 @@ class FinderTest < ActiveRecord::TestCase where(client_of: [2, 1, nil], name: ['37signals', 'Summit', 'Microsoft']). order('client_of DESC'). - map { |x| x.client_of } + map(&:client_of) assert client_of.include?(nil) assert_equal [2, 1].sort, client_of.compact.sort @@ -1025,7 +1025,7 @@ class FinderTest < ActiveRecord::TestCase client_of = Company. where(client_of: [nil]). order('client_of DESC'). - map { |x| x.client_of } + map(&:client_of) assert_equal [], client_of.compact end diff --git a/activerecord/test/cases/migration/column_positioning_test.rb b/activerecord/test/cases/migration/column_positioning_test.rb index 77a752f050..62186e13a5 100644 --- a/activerecord/test/cases/migration/column_positioning_test.rb +++ b/activerecord/test/cases/migration/column_positioning_test.rb @@ -25,30 +25,30 @@ module ActiveRecord if current_adapter?(:MysqlAdapter, :Mysql2Adapter) def test_column_positioning - assert_equal %w(first second third), conn.columns(:testings).map {|c| c.name } + assert_equal %w(first second third), conn.columns(:testings).map(&:name) end def test_add_column_with_positioning conn.add_column :testings, :new_col, :integer - assert_equal %w(first second third new_col), conn.columns(:testings).map {|c| c.name } + assert_equal %w(first second third new_col), conn.columns(:testings).map(&:name) end def test_add_column_with_positioning_first conn.add_column :testings, :new_col, :integer, :first => true - assert_equal %w(new_col first second third), conn.columns(:testings).map {|c| c.name } + assert_equal %w(new_col first second third), conn.columns(:testings).map(&:name) end def test_add_column_with_positioning_after conn.add_column :testings, :new_col, :integer, :after => :first - assert_equal %w(first new_col second third), conn.columns(:testings).map {|c| c.name } + assert_equal %w(first new_col second third), conn.columns(:testings).map(&:name) end def test_change_column_with_positioning conn.change_column :testings, :second, :integer, :first => true - assert_equal %w(second first third), conn.columns(:testings).map {|c| c.name } + assert_equal %w(second first third), conn.columns(:testings).map(&:name) conn.change_column :testings, :second, :integer, :after => :third - assert_equal %w(first third second), conn.columns(:testings).map {|c| c.name } + assert_equal %w(first third second), conn.columns(:testings).map(&:name) end end end diff --git a/activerecord/test/cases/migrator_test.rb b/activerecord/test/cases/migrator_test.rb index f05ca900aa..c0daa83e9c 100644 --- a/activerecord/test/cases/migrator_test.rb +++ b/activerecord/test/cases/migrator_test.rb @@ -149,7 +149,7 @@ class MigratorTest < ActiveRecord::TestCase def test_up_calls_up migrations = [Sensor.new(nil, 0), Sensor.new(nil, 1), Sensor.new(nil, 2)] ActiveRecord::Migrator.new(:up, migrations).migrate - assert migrations.all? { |m| m.went_up } + assert migrations.all?(&:went_up) assert migrations.all? { |m| !m.went_down } assert_equal 2, ActiveRecord::Migrator.current_version end @@ -160,7 +160,7 @@ class MigratorTest < ActiveRecord::TestCase migrations = [Sensor.new(nil, 0), Sensor.new(nil, 1), Sensor.new(nil, 2)] ActiveRecord::Migrator.new(:down, migrations).migrate assert migrations.all? { |m| !m.went_up } - assert migrations.all? { |m| m.went_down } + assert migrations.all?(&:went_down) assert_equal 0, ActiveRecord::Migrator.current_version end diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb index cf96c3fccf..5c7e8a65d2 100644 --- a/activerecord/test/cases/nested_attributes_test.rb +++ b/activerecord/test/cases/nested_attributes_test.rb @@ -13,7 +13,7 @@ require 'active_support/hash_with_indifferent_access' class TestNestedAttributesInGeneral < ActiveRecord::TestCase teardown do - Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? } + Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc(&:empty?) end def test_base_should_have_an_empty_nested_attributes_options @@ -300,13 +300,13 @@ class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase end def test_should_not_destroy_an_existing_record_if_allow_destroy_is_false - Pirate.accepts_nested_attributes_for :ship, :allow_destroy => false, :reject_if => proc { |attributes| attributes.empty? } + Pirate.accepts_nested_attributes_for :ship, :allow_destroy => false, :reject_if => proc(&:empty?) @pirate.update(ship_attributes: { id: @pirate.ship.id, _destroy: '1' }) assert_equal @ship, @pirate.reload.ship - Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? } + Pirate.accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc(&:empty?) end def test_should_also_work_with_a_HashWithIndifferentAccess @@ -494,12 +494,12 @@ class TestNestedAttributesOnABelongsToAssociation < ActiveRecord::TestCase end def test_should_not_destroy_an_existing_record_if_allow_destroy_is_false - Ship.accepts_nested_attributes_for :pirate, :allow_destroy => false, :reject_if => proc { |attributes| attributes.empty? } + Ship.accepts_nested_attributes_for :pirate, :allow_destroy => false, :reject_if => proc(&:empty?) @ship.update(pirate_attributes: { id: @ship.pirate.id, _destroy: '1' }) assert_nothing_raised(ActiveRecord::RecordNotFound) { @ship.pirate.reload } ensure - Ship.accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? } + Ship.accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc(&:empty?) end def test_should_work_with_update_as_well @@ -855,7 +855,7 @@ end module NestedAttributesLimitTests def teardown - Pirate.accepts_nested_attributes_for :parrots, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? } + Pirate.accepts_nested_attributes_for :parrots, :allow_destroy => true, :reject_if => proc(&:empty?) end def test_limit_with_less_records diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb index 2bcd496415..6fc4731f01 100644 --- a/activerecord/test/cases/persistence_test.rb +++ b/activerecord/test/cases/persistence_test.rb @@ -127,7 +127,7 @@ class PersistenceTest < ActiveRecord::TestCase assert_difference('Topic.count', -topics_by_mary.size) do destroyed = Topic.destroy_all(conditions).sort_by(&:id) assert_equal topics_by_mary, destroyed - assert destroyed.all? { |topic| topic.frozen? }, "destroyed topics should be frozen" + assert destroyed.all?(&:frozen?), "destroyed topics should be frozen" end end @@ -137,7 +137,7 @@ class PersistenceTest < ActiveRecord::TestCase assert_difference('Client.count', -2) do destroyed = Client.destroy([2, 3]).sort_by(&:id) assert_equal clients, destroyed - assert destroyed.all? { |client| client.frozen? }, "destroyed clients should be frozen" + assert destroyed.all?(&:frozen?), "destroyed clients should be frozen" end end diff --git a/activerecord/test/cases/pooled_connections_test.rb b/activerecord/test/cases/pooled_connections_test.rb index 8eea10143f..98888150a8 100644 --- a/activerecord/test/cases/pooled_connections_test.rb +++ b/activerecord/test/cases/pooled_connections_test.rb @@ -13,7 +13,7 @@ class PooledConnectionsTest < ActiveRecord::TestCase teardown do ActiveRecord::Base.clear_all_connections! ActiveRecord::Base.establish_connection(@connection) - @per_test_teardown.each {|td| td.call } + @per_test_teardown.each(&:call) end # Will deadlock due to lack of Monitor timeouts in 1.9 diff --git a/activerecord/test/cases/reflection_test.rb b/activerecord/test/cases/reflection_test.rb index 094fcccc89..e86b892a0a 100644 --- a/activerecord/test/cases/reflection_test.rb +++ b/activerecord/test/cases/reflection_test.rb @@ -50,13 +50,13 @@ class ReflectionTest < ActiveRecord::TestCase end def test_columns_are_returned_in_the_order_they_were_declared - column_names = Topic.columns.map { |column| column.name } + column_names = Topic.columns.map(&:name) assert_equal %w(id title author_name author_email_address written_on bonus_time last_read content important approved replies_count unique_replies_count parent_id parent_title type group created_at updated_at), column_names end def test_content_columns content_columns = Topic.content_columns - content_column_names = content_columns.map {|column| column.name} + content_column_names = content_columns.map(&:name) assert_equal 13, content_columns.length assert_equal %w(title author_name author_email_address written_on bonus_time last_read content important group approved parent_title created_at updated_at).sort, content_column_names.sort end diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb index ca86d58b35..fc9637a167 100644 --- a/activerecord/test/cases/relations_test.rb +++ b/activerecord/test/cases/relations_test.rb @@ -249,7 +249,7 @@ class RelationTest < ActiveRecord::TestCase def test_finding_with_reorder topics = Topic.order('author_name').order('title').reorder('id').to_a - topics_titles = topics.map{ |t| t.title } + topics_titles = topics.map(&:title) assert_equal ['The First Topic', 'The Second Topic of the day', 'The Third Topic of the day', 'The Fourth Topic of the day', 'The Fifth Topic of the day'], topics_titles end @@ -441,7 +441,7 @@ class RelationTest < ActiveRecord::TestCase where('project_id=1').to_a assert_equal 3, developers_on_project_one.length - developer_names = developers_on_project_one.map { |d| d.name } + developer_names = developers_on_project_one.map(&:name) assert developer_names.include?('David') assert developer_names.include?('Jamis') end @@ -652,8 +652,8 @@ class RelationTest < ActiveRecord::TestCase expected_taggings = taggings(:welcome_general, :thinking_general) assert_no_queries do - assert_equal expected_taggings, author.taggings.distinct.sort_by { |t| t.id } - assert_equal expected_taggings, author.taggings.uniq.sort_by { |t| t.id } + assert_equal expected_taggings, author.taggings.distinct.sort_by(&:id) + assert_equal expected_taggings, author.taggings.uniq.sort_by(&:id) end authors = Author.all diff --git a/activerecord/test/cases/scoping/default_scoping_test.rb b/activerecord/test/cases/scoping/default_scoping_test.rb index 880d0e8293..5bdebe6ac7 100644 --- a/activerecord/test/cases/scoping/default_scoping_test.rb +++ b/activerecord/test/cases/scoping/default_scoping_test.rb @@ -8,8 +8,8 @@ class DefaultScopingTest < ActiveRecord::TestCase fixtures :developers, :posts, :comments def test_default_scope - expected = Developer.all.merge!(:order => 'salary DESC').to_a.collect { |dev| dev.salary } - received = DeveloperOrderedBySalary.all.collect { |dev| dev.salary } + expected = Developer.all.merge!(:order => 'salary DESC').to_a.collect(&:salary) + received = DeveloperOrderedBySalary.all.collect(&:salary) assert_equal expected, received end @@ -86,14 +86,14 @@ class DefaultScopingTest < ActiveRecord::TestCase end def test_scope_overwrites_default - expected = Developer.all.merge!(order: 'salary DESC, name DESC').to_a.collect { |dev| dev.name } - received = DeveloperOrderedBySalary.by_name.to_a.collect { |dev| dev.name } + expected = Developer.all.merge!(order: 'salary DESC, name DESC').to_a.collect(&:name) + received = DeveloperOrderedBySalary.by_name.to_a.collect(&:name) assert_equal expected, received end def test_reorder_overrides_default_scope_order - expected = Developer.order('name DESC').collect { |dev| dev.name } - received = DeveloperOrderedBySalary.reorder('name DESC').collect { |dev| dev.name } + expected = Developer.order('name DESC').collect(&:name) + received = DeveloperOrderedBySalary.reorder('name DESC').collect(&:name) assert_equal expected, received end @@ -146,34 +146,34 @@ class DefaultScopingTest < ActiveRecord::TestCase end def test_unscope_multiple_where_clauses - expected = Developer.order('salary DESC').collect { |dev| dev.name } - received = DeveloperOrderedBySalary.where(name: 'Jamis').where(id: 1).unscope(where: [:name, :id]).collect { |dev| dev.name } + expected = Developer.order('salary DESC').collect(&:name) + received = DeveloperOrderedBySalary.where(name: 'Jamis').where(id: 1).unscope(where: [:name, :id]).collect(&:name) assert_equal expected, received end def test_unscope_string_where_clauses_involved dev_relation = Developer.order('salary DESC').where("created_at > ?", 1.year.ago) - expected = dev_relation.collect { |dev| dev.name } + expected = dev_relation.collect(&:name) dev_ordered_relation = DeveloperOrderedBySalary.where(name: 'Jamis').where("created_at > ?", 1.year.ago) - received = dev_ordered_relation.unscope(where: [:name]).collect { |dev| dev.name } + received = dev_ordered_relation.unscope(where: [:name]).collect(&:name) assert_equal expected, received end def test_unscope_with_grouping_attributes - expected = Developer.order('salary DESC').collect { |dev| dev.name } - received = DeveloperOrderedBySalary.group(:name).unscope(:group).collect { |dev| dev.name } + expected = Developer.order('salary DESC').collect(&:name) + received = DeveloperOrderedBySalary.group(:name).unscope(:group).collect(&:name) assert_equal expected, received - expected_2 = Developer.order('salary DESC').collect { |dev| dev.name } - received_2 = DeveloperOrderedBySalary.group("name").unscope(:group).collect { |dev| dev.name } + expected_2 = Developer.order('salary DESC').collect(&:name) + received_2 = DeveloperOrderedBySalary.group("name").unscope(:group).collect(&:name) assert_equal expected_2, received_2 end def test_unscope_with_limit_in_query - expected = Developer.order('salary DESC').collect { |dev| dev.name } - received = DeveloperOrderedBySalary.limit(1).unscope(:limit).collect { |dev| dev.name } + expected = Developer.order('salary DESC').collect(&:name) + received = DeveloperOrderedBySalary.limit(1).unscope(:limit).collect(&:name) assert_equal expected, received end @@ -183,42 +183,42 @@ class DefaultScopingTest < ActiveRecord::TestCase end def test_unscope_reverse_order - expected = Developer.all.collect { |dev| dev.name } - received = Developer.order('salary DESC').reverse_order.unscope(:order).collect { |dev| dev.name } + expected = Developer.all.collect(&:name) + received = Developer.order('salary DESC').reverse_order.unscope(:order).collect(&:name) assert_equal expected, received end def test_unscope_select - expected = Developer.order('salary ASC').collect { |dev| dev.name } - received = Developer.order('salary DESC').reverse_order.select(:name).unscope(:select).collect { |dev| dev.name } + expected = Developer.order('salary ASC').collect(&:name) + received = Developer.order('salary DESC').reverse_order.select(:name).unscope(:select).collect(&:name) assert_equal expected, received - expected_2 = Developer.all.collect { |dev| dev.id } - received_2 = Developer.select(:name).unscope(:select).collect { |dev| dev.id } + expected_2 = Developer.all.collect(&:id) + received_2 = Developer.select(:name).unscope(:select).collect(&:id) assert_equal expected_2, received_2 end def test_unscope_offset - expected = Developer.all.collect { |dev| dev.name } - received = Developer.offset(5).unscope(:offset).collect { |dev| dev.name } + expected = Developer.all.collect(&:name) + received = Developer.offset(5).unscope(:offset).collect(&:name) assert_equal expected, received end def test_unscope_joins_and_select_on_developers_projects - expected = Developer.all.collect { |dev| dev.name } - received = Developer.joins('JOIN developers_projects ON id = developer_id').select(:id).unscope(:joins, :select).collect { |dev| dev.name } + expected = Developer.all.collect(&:name) + received = Developer.joins('JOIN developers_projects ON id = developer_id').select(:id).unscope(:joins, :select).collect(&:name) assert_equal expected, received end def test_unscope_includes - expected = Developer.all.collect { |dev| dev.name } - received = Developer.includes(:projects).select(:id).unscope(:includes, :select).collect { |dev| dev.name } + expected = Developer.all.collect(&:name) + received = Developer.includes(:projects).select(:id).unscope(:includes, :select).collect(&:name) assert_equal expected, received end def test_unscope_having - expected = DeveloperOrderedBySalary.all.collect { |dev| dev.name } - received = DeveloperOrderedBySalary.having("name IN ('Jamis', 'David')").unscope(:having).collect { |dev| dev.name } + expected = DeveloperOrderedBySalary.all.collect(&:name) + received = DeveloperOrderedBySalary.having("name IN ('Jamis', 'David')").unscope(:having).collect(&:name) assert_equal expected, received end @@ -281,8 +281,8 @@ class DefaultScopingTest < ActiveRecord::TestCase end def test_order_in_default_scope_should_not_prevail - expected = Developer.all.merge!(order: 'salary desc').to_a.collect { |dev| dev.salary } - received = DeveloperOrderedBySalary.all.merge!(order: 'salary').to_a.collect { |dev| dev.salary } + expected = Developer.all.merge!(order: 'salary desc').to_a.collect(&:salary) + received = DeveloperOrderedBySalary.all.merge!(order: 'salary').to_a.collect(&:salary) assert_equal expected, received end diff --git a/activerecord/test/cases/test_case.rb b/activerecord/test/cases/test_case.rb index eb44c4a83c..5ba17359f0 100644 --- a/activerecord/test/cases/test_case.rb +++ b/activerecord/test/cases/test_case.rb @@ -43,7 +43,7 @@ module ActiveRecord patterns_to_match.each do |pattern| failed_patterns << pattern unless SQLCounter.log_all.any?{ |sql| pattern === sql } end - assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map{ |p| p.inspect }.join(', ')} not found.#{SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{SQLCounter.log.join("\n")}"}" + assert failed_patterns.empty?, "Query pattern(s) #{failed_patterns.map(&:inspect).join(', ')} not found.#{SQLCounter.log.size == 0 ? '' : "\nQueries:\n#{SQLCounter.log.join("\n")}"}" end def assert_queries(num = 1, options = {}) diff --git a/activerecord/test/cases/transactions_test.rb b/activerecord/test/cases/transactions_test.rb index 7160e8324d..72c07d8aea 100644 --- a/activerecord/test/cases/transactions_test.rb +++ b/activerecord/test/cases/transactions_test.rb @@ -13,7 +13,7 @@ class TransactionTest < ActiveRecord::TestCase fixtures :topics, :developers, :authors, :posts def setup - @first, @second = Topic.find(1, 2).sort_by { |t| t.id } + @first, @second = Topic.find(1, 2).sort_by(&:id) end def test_persisted_in_a_model_with_custom_primary_key_after_failed_save @@ -699,7 +699,7 @@ if current_adapter?(:PostgreSQLAdapter) end end - threads.each { |t| t.join } + threads.each(&:join) end end @@ -747,7 +747,7 @@ if current_adapter?(:PostgreSQLAdapter) Developer.connection.close end - threads.each { |t| t.join } + threads.each(&:join) end assert_equal original_salary, Developer.find(1).salary diff --git a/activerecord/test/cases/validations_repair_helper.rb b/activerecord/test/cases/validations_repair_helper.rb index 2bbf0f23b3..b30666d876 100644 --- a/activerecord/test/cases/validations_repair_helper.rb +++ b/activerecord/test/cases/validations_repair_helper.rb @@ -5,9 +5,7 @@ module ActiveRecord module ClassMethods def repair_validations(*model_classes) teardown do - model_classes.each do |k| - k.clear_validators! - end + model_classes.each(&:clear_validators!) end end end @@ -15,9 +13,7 @@ module ActiveRecord def repair_validations(*model_classes) yield if block_given? ensure - model_classes.each do |k| - k.clear_validators! - end + model_classes.each(&:clear_validators!) end end end diff --git a/activerecord/test/models/customer.rb b/activerecord/test/models/customer.rb index 7e8e82542f..afe4b3d707 100644 --- a/activerecord/test/models/customer.rb +++ b/activerecord/test/models/customer.rb @@ -2,7 +2,7 @@ class Customer < ActiveRecord::Base cattr_accessor :gps_conversion_was_run composed_of :address, :mapping => [ %w(address_street street), %w(address_city city), %w(address_country country) ], :allow_nil => true - composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), :converter => Proc.new { |balance| balance.to_money } + composed_of :balance, :class_name => "Money", :mapping => %w(balance amount), :converter => Proc.new(&:to_money) composed_of :gps_location, :allow_nil => true composed_of :non_blank_gps_location, :class_name => "GpsLocation", :allow_nil => true, :mapping => %w(gps_location gps_location), :converter => lambda { |gps| self.gps_conversion_was_run = true; gps.blank? ? nil : GpsLocation.new(gps)} diff --git a/activerecord/test/models/pirate.rb b/activerecord/test/models/pirate.rb index 90a3c3ecee..641a33f9be 100644 --- a/activerecord/test/models/pirate.rb +++ b/activerecord/test/models/pirate.rb @@ -36,8 +36,8 @@ class Pirate < ActiveRecord::Base has_one :foo_bulb, -> { where :name => 'foo' }, :foreign_key => :car_id, :class_name => "Bulb" - accepts_nested_attributes_for :parrots, :birds, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? } - accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? } + accepts_nested_attributes_for :parrots, :birds, :allow_destroy => true, :reject_if => proc(&:empty?) + accepts_nested_attributes_for :ship, :allow_destroy => true, :reject_if => proc(&:empty?) accepts_nested_attributes_for :update_only_ship, :update_only => true accepts_nested_attributes_for :parrots_with_method_callbacks, :parrots_with_proc_callbacks, :birds_with_method_callbacks, :birds_with_proc_callbacks, :allow_destroy => true diff --git a/activerecord/test/models/ship.rb b/activerecord/test/models/ship.rb index 77a4728d0b..5f618a50d2 100644 --- a/activerecord/test/models/ship.rb +++ b/activerecord/test/models/ship.rb @@ -6,7 +6,7 @@ class Ship < ActiveRecord::Base has_many :parts, :class_name => 'ShipPart' accepts_nested_attributes_for :parts, :allow_destroy => true - accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc { |attributes| attributes.empty? } + accepts_nested_attributes_for :pirate, :allow_destroy => true, :reject_if => proc(&:empty?) accepts_nested_attributes_for :update_only_pirate, :update_only => true validates_presence_of :name diff --git a/activesupport/bin/generate_tables b/activesupport/bin/generate_tables index f39e89b7d0..71a6b78652 100755 --- a/activesupport/bin/generate_tables +++ b/activesupport/bin/generate_tables @@ -55,7 +55,7 @@ module ActiveSupport codepoint.combining_class = Integer($4) #codepoint.bidi_class = $5 codepoint.decomp_type = $7 - codepoint.decomp_mapping = ($8=='') ? nil : $8.split.collect { |element| element.hex } + codepoint.decomp_mapping = ($8=='') ? nil : $8.split.collect(&:hex) #codepoint.bidi_mirrored = ($13=='Y') ? true : false codepoint.uppercase_mapping = ($16=='') ? 0 : $16.hex codepoint.lowercase_mapping = ($17=='') ? 0 : $17.hex diff --git a/activesupport/lib/active_support/core_ext/array/conversions.rb b/activesupport/lib/active_support/core_ext/array/conversions.rb index 76ffd23ed1..080e3b5ef7 100644 --- a/activesupport/lib/active_support/core_ext/array/conversions.rb +++ b/activesupport/lib/active_support/core_ext/array/conversions.rb @@ -92,7 +92,7 @@ class Array if empty? 'null' else - collect { |element| element.id }.join(',') + collect(&:id).join(',') end else to_default_s diff --git a/activesupport/lib/active_support/core_ext/hash/keys.rb b/activesupport/lib/active_support/core_ext/hash/keys.rb index f4105f66b0..9297a59c46 100644 --- a/activesupport/lib/active_support/core_ext/hash/keys.rb +++ b/activesupport/lib/active_support/core_ext/hash/keys.rb @@ -31,13 +31,13 @@ class Hash # hash.stringify_keys # # => {"name"=>"Rob", "age"=>"28"} def stringify_keys - transform_keys{ |key| key.to_s } + transform_keys(&:to_s) end # Destructively convert all keys to strings. Same as # +stringify_keys+, but modifies +self+. def stringify_keys! - transform_keys!{ |key| key.to_s } + transform_keys!(&:to_s) end # Returns a new hash with all keys converted to symbols, as long as @@ -105,14 +105,14 @@ class Hash # hash.deep_stringify_keys # # => {"person"=>{"name"=>"Rob", "age"=>"28"}} def deep_stringify_keys - deep_transform_keys{ |key| key.to_s } + deep_transform_keys(&:to_s) end # Destructively convert all keys to strings. # This includes the keys from the root hash and from all # nested hashes and arrays. def deep_stringify_keys! - deep_transform_keys!{ |key| key.to_s } + deep_transform_keys!(&:to_s) end # Returns a new hash with all keys converted to symbols, as long as diff --git a/activesupport/lib/active_support/core_ext/object/deep_dup.rb b/activesupport/lib/active_support/core_ext/object/deep_dup.rb index 2e99f4a1b8..0191d2e973 100644 --- a/activesupport/lib/active_support/core_ext/object/deep_dup.rb +++ b/activesupport/lib/active_support/core_ext/object/deep_dup.rb @@ -25,7 +25,7 @@ class Array # array[1][2] # => nil # dup[1][2] # => 4 def deep_dup - map { |it| it.deep_dup } + map(&:deep_dup) end end diff --git a/activesupport/lib/active_support/core_ext/object/instance_variables.rb b/activesupport/lib/active_support/core_ext/object/instance_variables.rb index 755e1c6b16..593a7a4940 100644 --- a/activesupport/lib/active_support/core_ext/object/instance_variables.rb +++ b/activesupport/lib/active_support/core_ext/object/instance_variables.rb @@ -23,6 +23,6 @@ class Object # # C.new(0, 1).instance_variable_names # => ["@y", "@x"] def instance_variable_names - instance_variables.map { |var| var.to_s } + instance_variables.map(&:to_s) end end diff --git a/activesupport/lib/active_support/core_ext/object/to_query.rb b/activesupport/lib/active_support/core_ext/object/to_query.rb index ccd568bbf5..ec5ace4e16 100644 --- a/activesupport/lib/active_support/core_ext/object/to_query.rb +++ b/activesupport/lib/active_support/core_ext/object/to_query.rb @@ -38,7 +38,7 @@ class Array # Calls to_param on all its elements and joins the result with # slashes. This is used by url_for in Action Pack. def to_param - collect { |e| e.to_param }.join '/' + collect(&:to_param).join '/' end # Converts an array into a string suitable for use as a URL query string, diff --git a/activesupport/lib/active_support/dependencies.rb b/activesupport/lib/active_support/dependencies.rb index 65a370dd30..ff8c0fd310 100644 --- a/activesupport/lib/active_support/dependencies.rb +++ b/activesupport/lib/active_support/dependencies.rb @@ -742,7 +742,7 @@ module ActiveSupport #:nodoc: protected def log_call(*args) if log_activity? - arg_str = args.collect { |arg| arg.inspect } * ', ' + arg_str = args.collect(&:inspect) * ', ' /in `([a-z_\?\!]+)'/ =~ caller(1).first selector = $1 || '' log "called #{selector}(#{arg_str})" diff --git a/activesupport/lib/active_support/number_helper/number_to_human_converter.rb b/activesupport/lib/active_support/number_helper/number_to_human_converter.rb index 9a3dc526ae..6940beb318 100644 --- a/activesupport/lib/active_support/number_helper/number_to_human_converter.rb +++ b/activesupport/lib/active_support/number_helper/number_to_human_converter.rb @@ -59,7 +59,7 @@ module ActiveSupport translate_in_locale("human.decimal_units.units", raise: true) else raise ArgumentError, ":units must be a Hash or String translation scope." - end.keys.map { |e_name| INVERTED_DECIMAL_UNITS[e_name] }.sort_by { |e| -e } + end.keys.map { |e_name| INVERTED_DECIMAL_UNITS[e_name] }.sort_by(&:-@) end end end diff --git a/activesupport/lib/active_support/testing/assertions.rb b/activesupport/lib/active_support/testing/assertions.rb index 11cca82995..8b649c193f 100644 --- a/activesupport/lib/active_support/testing/assertions.rb +++ b/activesupport/lib/active_support/testing/assertions.rb @@ -66,7 +66,7 @@ module ActiveSupport exps = expressions.map { |e| e.respond_to?(:call) ? e : lambda { eval(e, block.binding) } } - before = exps.map { |e| e.call } + before = exps.map(&:call) yield diff --git a/activesupport/lib/active_support/values/time_zone.rb b/activesupport/lib/active_support/values/time_zone.rb index 55533a5d40..fd05a5459c 100644 --- a/activesupport/lib/active_support/values/time_zone.rb +++ b/activesupport/lib/active_support/values/time_zone.rb @@ -237,7 +237,7 @@ module ActiveSupport case arg when String begin - @lazy_zones_map[arg] ||= create(arg).tap { |tz| tz.utc_offset } + @lazy_zones_map[arg] ||= create(arg).tap(&:utc_offset) rescue TZInfo::InvalidTimezoneIdentifier nil end diff --git a/activesupport/test/core_ext/enumerable_test.rb b/activesupport/test/core_ext/enumerable_test.rb index 6fcf6e8743..346dc3d208 100644 --- a/activesupport/test/core_ext/enumerable_test.rb +++ b/activesupport/test/core_ext/enumerable_test.rb @@ -71,14 +71,14 @@ class EnumerableTests < ActiveSupport::TestCase def test_index_by payments = GenericEnumerable.new([ Payment.new(5), Payment.new(15), Payment.new(10) ]) assert_equal({ 5 => Payment.new(5), 15 => Payment.new(15), 10 => Payment.new(10) }, - payments.index_by { |p| p.price }) + payments.index_by(&:price)) assert_equal Enumerator, payments.index_by.class if Enumerator.method_defined? :size assert_equal nil, payments.index_by.size assert_equal 42, (1..42).index_by.size end assert_equal({ 5 => Payment.new(5), 15 => Payment.new(15), 10 => Payment.new(10) }, - payments.index_by.each { |p| p.price }) + payments.index_by.each(&:price)) end def test_many diff --git a/activesupport/test/core_ext/hash_ext_test.rb b/activesupport/test/core_ext/hash_ext_test.rb index 5e9fdfd872..3d2f50ce49 100644 --- a/activesupport/test/core_ext/hash_ext_test.rb +++ b/activesupport/test/core_ext/hash_ext_test.rb @@ -365,7 +365,7 @@ class HashExtTest < ActiveSupport::TestCase :member? => true } hashes.each do |name, hash| - method_map.sort_by { |m| m.to_s }.each do |meth, expected| + method_map.sort_by(&:to_s).each do |meth, expected| assert_equal(expected, hash.__send__(meth, 'a'), "Calling #{name}.#{meth} 'a'") assert_equal(expected, hash.__send__(meth, :a), diff --git a/activesupport/test/core_ext/object/try_test.rb b/activesupport/test/core_ext/object/try_test.rb index efc6beaf02..89438675c1 100644 --- a/activesupport/test/core_ext/object/try_test.rb +++ b/activesupport/test/core_ext/object/try_test.rb @@ -52,11 +52,11 @@ class ObjectTryTest < ActiveSupport::TestCase end def test_try_only_block - assert_equal @string.reverse, @string.try { |s| s.reverse } + assert_equal @string.reverse, @string.try(&:reverse) end def test_try_only_block_bang - assert_equal @string.reverse, @string.try! { |s| s.reverse } + assert_equal @string.reverse, @string.try!(&:reverse) end def test_try_only_block_nil diff --git a/activesupport/test/core_ext/string_ext_test.rb b/activesupport/test/core_ext/string_ext_test.rb index e32c178951..0af207fae9 100644 --- a/activesupport/test/core_ext/string_ext_test.rb +++ b/activesupport/test/core_ext/string_ext_test.rb @@ -281,15 +281,11 @@ class StringInflectionsTest < ActiveSupport::TestCase end def test_constantize - run_constantize_tests_on do |string| - string.constantize - end + run_constantize_tests_on(&:constantize) end def test_safe_constantize - run_safe_constantize_tests_on do |string| - string.safe_constantize - end + run_safe_constantize_tests_on(&:safe_constantize) end end diff --git a/activesupport/test/multibyte_chars_test.rb b/activesupport/test/multibyte_chars_test.rb index feca013675..94748dd991 100644 --- a/activesupport/test/multibyte_chars_test.rb +++ b/activesupport/test/multibyte_chars_test.rb @@ -182,7 +182,7 @@ class MultibyteCharsUTF8BehaviourTest < ActiveSupport::TestCase end def test_sortability - words = %w(builder armor zebra).sort_by { |s| s.mb_chars } + words = %w(builder armor zebra).sort_by(&:mb_chars) assert_equal %w(armor builder zebra), words end diff --git a/activesupport/test/multibyte_conformance_test.rb b/activesupport/test/multibyte_conformance_test.rb index aba81b8248..f7bd21c8ab 100644 --- a/activesupport/test/multibyte_conformance_test.rb +++ b/activesupport/test/multibyte_conformance_test.rb @@ -115,7 +115,7 @@ class MultibyteConformanceTest < ActiveSupport::TestCase next if (line.empty? || line =~ /^\#/) cols, comment = line.split("#") - cols = cols.split(";").map{|e| e.strip}.reject{|e| e.empty? } + cols = cols.split(";").map(&:strip).reject(&:empty?) next unless cols.length == 5 # codepoints are in hex in the test suite, pack wants them as integers diff --git a/activesupport/test/rescuable_test.rb b/activesupport/test/rescuable_test.rb index ec9d231125..b8af888f7c 100644 --- a/activesupport/test/rescuable_test.rb +++ b/activesupport/test/rescuable_test.rb @@ -93,13 +93,13 @@ class RescuableTest < ActiveSupport::TestCase def test_rescues_defined_later_are_added_at_end_of_the_rescue_handlers_array expected = ["WraithAttack", "WraithAttack", "NuclearExplosion", "MadRonon"] - result = @stargate.send(:rescue_handlers).collect {|e| e.first} + result = @stargate.send(:rescue_handlers).collect(&:first) assert_equal expected, result end def test_children_should_inherit_rescue_definitions_from_parents_and_child_rescue_should_be_appended expected = ["WraithAttack", "WraithAttack", "NuclearExplosion", "MadRonon", "CoolError"] - result = @cool_stargate.send(:rescue_handlers).collect {|e| e.first} + result = @cool_stargate.send(:rescue_handlers).collect(&:first) assert_equal expected, result end end diff --git a/ci/travis.rb b/ci/travis.rb index a1920a7a1f..b62f90a59e 100755 --- a/ci/travis.rb +++ b/ci/travis.rb @@ -140,6 +140,6 @@ if failures.empty? else puts puts "Rails build FAILED" - puts "Failed components: #{failures.map { |component| component.first }.join(', ')}" + puts "Failed components: #{failures.map(&:first).join(', ')}" exit(false) end diff --git a/guides/rails_guides/kindle.rb b/guides/rails_guides/kindle.rb index 09eecd5634..32926622e3 100644 --- a/guides/rails_guides/kindle.rb +++ b/guides/rails_guides/kindle.rb @@ -70,7 +70,7 @@ module Kindle File.open("sections/%03d/_section.txt" % section_idx, 'w') {|f| f.puts title} doc.xpath("//h3[@id]").each_with_index do |h3,item_idx| subsection = h3.inner_text - content = h3.xpath("./following-sibling::*").take_while {|x| x.name != "h3"}.map {|x| x.to_html} + content = h3.xpath("./following-sibling::*").take_while {|x| x.name != "h3"}.map(&:to_html) item = Nokogiri::HTML(h3.to_html + content.join("\n")) item_path = "sections/%03d/%03d.html" % [section_idx, item_idx] add_head_section(item, subsection) diff --git a/railties/lib/rails/application/routes_reloader.rb b/railties/lib/rails/application/routes_reloader.rb index 737977adf9..cf0a4e128f 100644 --- a/railties/lib/rails/application/routes_reloader.rb +++ b/railties/lib/rails/application/routes_reloader.rb @@ -41,9 +41,7 @@ module Rails end def finalize! - route_sets.each do |routes| - routes.finalize! - end + route_sets.each(&:finalize!) end def revert diff --git a/railties/lib/rails/commands/plugin.rb b/railties/lib/rails/commands/plugin.rb index 95bbdd4cdf..52d8966ead 100644 --- a/railties/lib/rails/commands/plugin.rb +++ b/railties/lib/rails/commands/plugin.rb @@ -11,7 +11,7 @@ else end if File.exist?(railsrc) extra_args_string = File.read(railsrc) - extra_args = extra_args_string.split(/\n+/).flat_map {|l| l.split} + extra_args = extra_args_string.split(/\n+/).flat_map(&:split) puts "Using #{extra_args.join(" ")} from #{railsrc}" ARGV.insert(1, *extra_args) end diff --git a/railties/lib/rails/generators.rb b/railties/lib/rails/generators.rb index bf2390cb7e..e25c364178 100644 --- a/railties/lib/rails/generators.rb +++ b/railties/lib/rails/generators.rb @@ -153,7 +153,7 @@ module Rails def self.invoke(namespace, args=ARGV, config={}) names = namespace.to_s.split(':') if klass = find_by_namespace(names.pop, names.any? && names.join(':')) - args << "--help" if args.empty? && klass.arguments.any? { |a| a.required? } + args << "--help" if args.empty? && klass.arguments.any?(&:required?) klass.start(args, config) else options = sorted_groups.map(&:last).flatten @@ -226,7 +226,7 @@ module Rails def self.public_namespaces lookup! - subclasses.map { |k| k.namespace } + subclasses.map(&:namespace) end def self.print_generators diff --git a/railties/lib/rails/generators/actions.rb b/railties/lib/rails/generators/actions.rb index ffdb314612..5373121835 100644 --- a/railties/lib/rails/generators/actions.rb +++ b/railties/lib/rails/generators/actions.rb @@ -189,7 +189,7 @@ module Rails # generate(:authenticated, "user session") def generate(what, *args) log :generate, what - argument = args.flat_map {|arg| arg.to_s }.join(" ") + argument = args.flat_map(&:to_s).join(" ") in_root { run_ruby_script("bin/rails generate #{what} #{argument}", verbose: false) } end diff --git a/railties/lib/rails/generators/base.rb b/railties/lib/rails/generators/base.rb index 9af6435f23..813b8b629e 100644 --- a/railties/lib/rails/generators/base.rb +++ b/railties/lib/rails/generators/base.rb @@ -273,7 +273,7 @@ module Rails # Use Rails default banner. def self.banner - "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map{ |a| a.usage }.join(' ')} [options]".gsub(/\s+/, ' ') + "rails generate #{namespace.sub(/^rails:/,'')} #{self.arguments.map(&:usage).join(' ')} [options]".gsub(/\s+/, ' ') end # Sets the base_name taking into account the current class namespace. diff --git a/railties/lib/rails/generators/named_base.rb b/railties/lib/rails/generators/named_base.rb index b7da44ca2d..397e1e73f1 100644 --- a/railties/lib/rails/generators/named_base.rb +++ b/railties/lib/rails/generators/named_base.rb @@ -99,7 +99,7 @@ module Rails end def class_name - (class_path + [file_name]).map!{ |m| m.camelize }.join('::') + (class_path + [file_name]).map!(&:camelize).join('::') end def human_name @@ -156,7 +156,7 @@ module Rails def assign_names!(name) #:nodoc: @class_path = name.include?('/') ? name.split('/') : name.split('::') - @class_path.map! { |m| m.underscore } + @class_path.map!(&:underscore) @file_name = @class_path.pop end diff --git a/railties/lib/rails/generators/rails/app/app_generator.rb b/railties/lib/rails/generators/rails/app/app_generator.rb index 9110c129d1..f8a8ae90d9 100644 --- a/railties/lib/rails/generators/rails/app/app_generator.rb +++ b/railties/lib/rails/generators/rails/app/app_generator.rb @@ -260,9 +260,7 @@ module Rails public_task :generate_spring_binstubs def run_after_bundle_callbacks - @after_bundle_callbacks.each do |callback| - callback.call - end + @after_bundle_callbacks.each(&:call) end protected diff --git a/railties/lib/rails/generators/resource_helpers.rb b/railties/lib/rails/generators/resource_helpers.rb index 4669935156..3f84d76ae0 100644 --- a/railties/lib/rails/generators/resource_helpers.rb +++ b/railties/lib/rails/generators/resource_helpers.rb @@ -39,7 +39,7 @@ module Rails def assign_controller_names!(name) @controller_name = name @controller_class_path = name.include?('/') ? name.split('/') : name.split('::') - @controller_class_path.map! { |m| m.underscore } + @controller_class_path.map!(&:underscore) @controller_file_name = @controller_class_path.pop end @@ -48,7 +48,7 @@ module Rails end def controller_class_name - (controller_class_path + [controller_file_name]).map!{ |m| m.camelize }.join('::') + (controller_class_path + [controller_file_name]).map!(&:camelize).join('::') end def controller_i18n_scope diff --git a/railties/lib/rails/info.rb b/railties/lib/rails/info.rb index 94ede76932..5909446b66 100644 --- a/railties/lib/rails/info.rb +++ b/railties/lib/rails/info.rb @@ -8,7 +8,7 @@ module Rails mattr_accessor :properties class << (@@properties = []) def names - map {|val| val.first } + map(&:first) end def value_for(property_name) @@ -26,7 +26,7 @@ module Rails end def to_s - column_width = properties.names.map {|name| name.length}.max + column_width = properties.names.map(&:length).max info = properties.map do |name, value| value = value.join(", ") if value.is_a?(Array) "%-#{column_width}s %s" % [name, value] diff --git a/railties/lib/rails/paths.rb b/railties/lib/rails/paths.rb index d11804af17..5458036219 100644 --- a/railties/lib/rails/paths.rb +++ b/railties/lib/rails/paths.rb @@ -77,23 +77,23 @@ module Rails end def all_paths - values.tap { |v| v.uniq! } + values.tap(&:uniq!) end def autoload_once - filter_by { |p| p.autoload_once? } + filter_by(&:autoload_once?) end def eager_load - filter_by { |p| p.eager_load? } + filter_by(&:eager_load?) end def autoload_paths - filter_by { |p| p.autoload? } + filter_by(&:autoload?) end def load_paths - filter_by { |p| p.load_path? } + filter_by(&:load_path?) end private diff --git a/railties/test/railties/engine_test.rb b/railties/test/railties/engine_test.rb index 6239af2066..260ee0eda9 100644 --- a/railties/test/railties/engine_test.rb +++ b/railties/test/railties/engine_test.rb @@ -518,7 +518,7 @@ YAML def call(env) response = @app.call(env) - response[2].each { |b| b.upcase! } + response[2].each(&:upcase!) response end end -- cgit v1.2.3 From f413cbee8dd702e2cae550c04b16e6c98411aeab Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Fri, 28 Nov 2014 14:58:10 -0500 Subject: Pure rack apps can be mounted with a name See https://github.com/rails/rails/commit/9b15828b5c347395b42066a588c88e5eb4e72279#commitcomment-8764492 --- actionpack/lib/action_dispatch/routing/mapper.rb | 8 +------- actionpack/test/dispatch/routing/inspector_test.rb | 2 +- railties/test/application/routing_test.rb | 20 ++++++++++++++++++++ 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index a8be77f46d..5040aa82b2 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -580,13 +580,7 @@ module ActionDispatch raise "A rack application must be specified" unless path rails_app = rails_app? app - - if rails_app - options[:as] ||= app.railtie_name - else - # non rails apps can't have an :as - options[:as] = nil - end + options[:as] ||= app.railtie_name if rails_app target_as = name_for_action(options[:as], path) options[:via] ||= :all diff --git a/actionpack/test/dispatch/routing/inspector_test.rb b/actionpack/test/dispatch/routing/inspector_test.rb index ff33dd5652..5910f364cc 100644 --- a/actionpack/test/dispatch/routing/inspector_test.rb +++ b/actionpack/test/dispatch/routing/inspector_test.rb @@ -235,7 +235,7 @@ module ActionDispatch assert_equal [ "Prefix Verb URI Pattern Controller#Action", - " /foo #{RackApp.name} {:constraint=>( my custom constraint )}" + " foo /foo #{RackApp.name} {:constraint=>( my custom constraint )}" ], output end diff --git a/railties/test/application/routing_test.rb b/railties/test/application/routing_test.rb index 8576a2b738..cbada6be97 100644 --- a/railties/test/application/routing_test.rb +++ b/railties/test/application/routing_test.rb @@ -123,6 +123,26 @@ module ApplicationTests assert_equal '/archives', last_response.body end + test "mount named rack app" do + controller :foo, <<-RUBY + class FooController < ApplicationController + def index + render text: my_blog_path + end + end + RUBY + + app_file 'config/routes.rb', <<-RUBY + Rails.application.routes.draw do + mount lambda { |env| [200, {}, [env["PATH_INFO"]]] }, at: "/blog", as: "my_blog" + get '/foo' => 'foo#index' + end + RUBY + + get '/foo' + assert_equal '/blog', last_response.body + end + test "multiple controllers" do controller :foo, <<-RUBY class FooController < ApplicationController -- cgit v1.2.3 From 35a14cfd5d60edb74309c3bfaf8e37d60f93b786 Mon Sep 17 00:00:00 2001 From: Igor Zubkov Date: Sat, 29 Nov 2014 18:45:47 +0200 Subject: Bump ruby version to 2.1.0 in rails.gemspec too. --- rails.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rails.gemspec b/rails.gemspec index 9969748a09..be83304e2b 100644 --- a/rails.gemspec +++ b/rails.gemspec @@ -7,7 +7,7 @@ Gem::Specification.new do |s| s.summary = 'Full-stack web application framework.' s.description = 'Ruby on Rails is a full-stack web framework optimized for programmer happiness and sustainable productivity. It encourages beautiful code by favoring convention over configuration.' - s.required_ruby_version = '>= 1.9.3' + s.required_ruby_version = '>= 2.1.0' s.required_rubygems_version = '>= 1.8.11' s.license = 'MIT' -- cgit v1.2.3 From b59b794ca80df49c0a60fa305e6db92a88458a2c Mon Sep 17 00:00:00 2001 From: Igor Zubkov Date: Sat, 29 Nov 2014 23:52:21 +0200 Subject: Fix link in documentation. [ci skip] --- actionview/lib/action_view/base.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/actionview/lib/action_view/base.rb b/actionview/lib/action_view/base.rb index 3071a13655..1feafc1094 100644 --- a/actionview/lib/action_view/base.rb +++ b/actionview/lib/action_view/base.rb @@ -126,8 +126,8 @@ module ActionView #:nodoc: # end # end # - # For more information on Builder please consult the [source - # code](https://github.com/jimweirich/builder). + # For more information on Builder please consult the {source + # code}[https://github.com/jimweirich/builder]. class Base include Helpers, ::ERB::Util, Context -- cgit v1.2.3 From de239066e32d654f6815a94cdf8ce4b67b058726 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Wed, 26 Nov 2014 13:22:11 -0700 Subject: Stop using `Arel::Table.engine` We never actually make use of it on the table, since we're constructing the select manager manually. It looks like if we ever actually were grabbing it from the table, we're grossly misusing it since it's meant to vary by AR class. Its existence on `Arel::Table` appears to be purely for convenience methods that are never used outside of tests. However, in production code it just complicates construction of the tables on the rails side, and the plan is to remove it from `Arel::Table` entirely. I'm not convinced it needs to live on `SelectManager`, etc either. --- activerecord/lib/active_record/core.rb | 2 +- activerecord/lib/active_record/relation/predicate_builder.rb | 4 ++-- activerecord/lib/active_record/relation/query_methods.rb | 2 +- activerecord/lib/active_record/sanitization.rb | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index 89d8932e9e..c812e7842a 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -235,7 +235,7 @@ module ActiveRecord # scope :published_and_commented, -> { published.and(self.arel_table[:comments_count].gt(0)) } # end def arel_table # :nodoc: - @arel_table ||= Arel::Table.new(table_name, arel_engine) + @arel_table ||= Arel::Table.new(table_name) end # Returns the Arel engine. diff --git a/activerecord/lib/active_record/relation/predicate_builder.rb b/activerecord/lib/active_record/relation/predicate_builder.rb index e4b6b49087..938bf55c6d 100644 --- a/activerecord/lib/active_record/relation/predicate_builder.rb +++ b/activerecord/lib/active_record/relation/predicate_builder.rb @@ -25,7 +25,7 @@ module ActiveRecord if value.empty? queries << '1=0' else - table = Arel::Table.new(column, default_table.engine) + table = Arel::Table.new(column) association = klass._reflect_on_association(column) value.each do |k, v| @@ -37,7 +37,7 @@ module ActiveRecord if column.include?('.') table_name, column = column.split('.', 2) - table = Arel::Table.new(table_name, default_table.engine) + table = Arel::Table.new(table_name) end queries.concat expand(klass, table, column, value) diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 6e384facce..0edd2b1e48 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -858,7 +858,7 @@ module ActiveRecord private def build_arel - arel = Arel::SelectManager.new(table.engine, table) + arel = Arel::SelectManager.new(klass.arel_engine, table) build_joins(arel, joins_values.flatten) unless joins_values.empty? diff --git a/activerecord/lib/active_record/sanitization.rb b/activerecord/lib/active_record/sanitization.rb index 6a130c145b..88dfddebcc 100644 --- a/activerecord/lib/active_record/sanitization.rb +++ b/activerecord/lib/active_record/sanitization.rb @@ -93,7 +93,7 @@ sanitize_sql_hash_for_conditions is deprecated, and will be removed in Rails 5.0 attrs = PredicateBuilder.resolve_column_aliases self, attrs attrs = expand_hash_conditions_for_aggregates(attrs) - table = Arel::Table.new(table_name, arel_engine).alias(default_table_name) + table = Arel::Table.new(table_name).alias(default_table_name) PredicateBuilder.build_from_hash(self, attrs, table).map { |b| connection.visitor.compile b }.join(' AND ') -- cgit v1.2.3 From b5242b6f95bc6a9481f438dce3fbed89e0f1edb0 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Sat, 29 Nov 2014 16:11:57 -0700 Subject: Use arel master --- Gemfile | 1 + 1 file changed, 1 insertion(+) diff --git a/Gemfile b/Gemfile index e2cbce24c8..a021f77417 100644 --- a/Gemfile +++ b/Gemfile @@ -14,6 +14,7 @@ gem 'rack-cache', '~> 1.2' gem 'jquery-rails', github: 'rails/jquery-rails' gem 'coffee-rails', '~> 4.1.0' gem 'turbolinks' +gem 'arel', github: 'rails/arel' # require: false so bcrypt is loaded only when has_secure_password is used. # This is to avoid ActiveModel (and by extension the entire framework) -- cgit v1.2.3 From a975407a0a4f8bb06f8d4696de6a8b5e5a086622 Mon Sep 17 00:00:00 2001 From: Sean Griffin Date: Sat, 29 Nov 2014 17:23:10 -0700 Subject: Update Arel usage for rails/arel#98fc259 `where_sql` now requires that we pass it an engine. None of the manager classes take an engine in their constructor. --- .../active_record/associations/has_many_through_association.rb | 2 +- activerecord/lib/active_record/relation.rb | 4 ++-- activerecord/lib/active_record/relation/finder_methods.rb | 8 ++++---- activerecord/lib/active_record/relation/query_methods.rb | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) 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 5cfedcc009..3f4d3bfc08 100644 --- a/activerecord/lib/active_record/associations/has_many_through_association.rb +++ b/activerecord/lib/active_record/associations/has_many_through_association.rb @@ -165,7 +165,7 @@ module ActiveRecord arel = scope.arel - stmt = Arel::DeleteManager.new arel.engine + stmt = Arel::DeleteManager.new stmt.from scope.klass.arel_table stmt.wheres = arel.constraints diff --git a/activerecord/lib/active_record/relation.rb b/activerecord/lib/active_record/relation.rb index 7e1994086f..7df50f7c97 100644 --- a/activerecord/lib/active_record/relation.rb +++ b/activerecord/lib/active_record/relation.rb @@ -327,7 +327,7 @@ module ActiveRecord def update_all(updates) raise ArgumentError, "Empty list of attributes to change" if updates.blank? - stmt = Arel::UpdateManager.new(arel.engine) + stmt = Arel::UpdateManager.new stmt.set Arel.sql(@klass.send(:sanitize_sql_for_assignment, updates)) stmt.table(table) @@ -465,7 +465,7 @@ module ActiveRecord if conditions where(conditions).delete_all else - stmt = Arel::DeleteManager.new(arel.engine) + stmt = Arel::DeleteManager.new stmt.from(table) if joins_values.any? diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 5061940d82..357861caaa 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -108,7 +108,7 @@ module ActiveRecord # Same as +take+ but raises ActiveRecord::RecordNotFound if no record # is found. Note that take! accepts no arguments. def take! - take or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]") + take or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]") end # Find the first record (or first N records if a parameter is supplied). @@ -176,7 +176,7 @@ module ActiveRecord # Same as +last+ but raises ActiveRecord::RecordNotFound if no record # is found. Note that last! accepts no arguments. def last! - last or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]") + last or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]") end # Find the second record. @@ -323,7 +323,7 @@ module ActiveRecord # the expected number of results should be provided in the +expected_size+ # argument. def raise_record_not_found_exception!(ids, result_size, expected_size) #:nodoc: - conditions = arel.where_sql + conditions = arel.where_sql(@klass.arel_engine) conditions = " [#{conditions}]" if conditions if Array(ids).size == 1 @@ -498,7 +498,7 @@ module ActiveRecord end def find_nth!(index) - find_nth(index, offset_index) or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql}]") + find_nth(index, offset_index) or raise RecordNotFound.new("Couldn't find #{@klass.name} with [#{arel.where_sql(@klass.arel_engine)}]") end def find_nth_with_limit(offset, limit) diff --git a/activerecord/lib/active_record/relation/query_methods.rb b/activerecord/lib/active_record/relation/query_methods.rb index 0edd2b1e48..d58af01339 100644 --- a/activerecord/lib/active_record/relation/query_methods.rb +++ b/activerecord/lib/active_record/relation/query_methods.rb @@ -858,7 +858,7 @@ module ActiveRecord private def build_arel - arel = Arel::SelectManager.new(klass.arel_engine, table) + arel = Arel::SelectManager.new(table) build_joins(arel, joins_values.flatten) unless joins_values.empty? -- cgit v1.2.3 From c15d3fb0da9e90850a79dc64ebd6614618e35fec Mon Sep 17 00:00:00 2001 From: "yuuji.yaginuma" Date: Sun, 30 Nov 2014 10:18:07 +0900 Subject: [ci skip] fix description of url_for --- actionmailer/lib/action_mailer/base.rb | 5 ----- guides/source/action_mailer_basics.md | 14 +------------- 2 files changed, 1 insertion(+), 18 deletions(-) diff --git a/actionmailer/lib/action_mailer/base.rb b/actionmailer/lib/action_mailer/base.rb index a88e884ee8..67e316c4fe 100644 --- a/actionmailer/lib/action_mailer/base.rb +++ b/actionmailer/lib/action_mailer/base.rb @@ -132,11 +132,6 @@ module ActionMailer # # config.action_mailer.default_url_options = { host: "example.com" } # - # When you decide to set a default :host for your mailers, then you need to make sure to use the - # only_path: false option when using url_for. Since the url_for view helper - # will generate relative URLs by default when a :host option isn't explicitly provided, passing - # only_path: false will ensure that absolute URLs are generated. - # # = Sending mail # # Once a mailer action and template are defined, you can deliver your message or create it and save it diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md index 2e8ab83241..ba7c16aa1d 100644 --- a/guides/source/action_mailer_basics.md +++ b/guides/source/action_mailer_basics.md @@ -470,16 +470,7 @@ By using the full URL, your links will now work in your emails. #### generating URLs with `url_for` -You need to pass the `only_path: false` option when using `url_for`. This will -ensure that absolute URLs are generated because the `url_for` view helper will, -by default, generate relative URLs when a `:host` option isn't explicitly -provided. - -```erb -<%= url_for(controller: 'welcome', - action: 'greeting', - only_path: false) %> -``` +`url_for` generate full URL by default in templates. If you did not configure the `:host` option globally make sure to pass it to `url_for`. @@ -491,9 +482,6 @@ If you did not configure the `:host` option globally make sure to pass it to action: 'greeting') %> ``` -NOTE: When you explicitly pass the `:host` Rails will always generate absolute -URLs, so there is no need to pass `only_path: false`. - #### generating URLs with named routes Email clients have no web context and so paths have no base URL to form complete -- cgit v1.2.3 From 9710d73260d29c8633e314360c4dca7485d142d0 Mon Sep 17 00:00:00 2001 From: Prathamesh Sonpatki Date: Mon, 10 Nov 2014 12:44:12 +0530 Subject: [Testing guide] Use "Fixtures API" instead of "fixture api". --- guides/source/testing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index b4c70dfa1d..ceb849f690 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -51,7 +51,7 @@ The `test_helper.rb` file holds the default configuration for your tests. For good tests, you'll need to give some thought to setting up test data. In Rails, you can handle this by defining and customizing fixtures. -You can find comprehensive documentation in the [fixture api documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html). +You can find comprehensive documentation in the [Fixtures API documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html). #### What Are Fixtures? -- cgit v1.2.3 From 98e41032fd0f31cb732d8b4c206ca7a32fae7cc0 Mon Sep 17 00:00:00 2001 From: Prathamesh Sonpatki Date: Mon, 10 Nov 2014 13:45:45 +0530 Subject: [Testing guide] Using "Fixtures API" consistently - In guides, "API" is used consistently instead of "api". - Reason behind replacing "fixtures API" to "Fixtures API" is because here we are referring to the concept of "fixtures". In other places in the guide "fixture" OR "fixtures" is referred to the single or multiple instances of test data. - This is also followup of https://github.com/rails/docrails/commit/aa9d1332b20305dd860b21a7ada06c5252bebad5#commitcomment-8497376. --- guides/source/testing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/guides/source/testing.md b/guides/source/testing.md index ceb849f690..d54f431d54 100644 --- a/guides/source/testing.md +++ b/guides/source/testing.md @@ -100,7 +100,7 @@ Note: For associations to reference one another by name, you cannot specify the attribute on the fixtures. Rails will auto assign a primary key to be consistent between runs. If you manually specify an `id:` attribute, this behavior will not work. For more information on this association behavior please read the - [fixture api documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html). + [Fixtures API documentation](http://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html). #### ERB'in It Up -- cgit v1.2.3 From 6874133f9e5ca79f30f43632da4338d7b82ddeff Mon Sep 17 00:00:00 2001 From: Hendy Tanata Date: Wed, 26 Nov 2014 09:16:44 -0800 Subject: Fix grammar on ActiveRecord::AttributeMethods doc. [ci skip] --- activerecord/lib/active_record/attribute_methods.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index d766996d37..83fcefa64d 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -218,7 +218,7 @@ module ActiveRecord # A Person object with a name attribute can ask person.respond_to?(:name), # person.respond_to?(:name=), and person.respond_to?(:name?) - # which will all return +true+. It also define the attribute methods if they have + # which will all return +true+. It also defines the attribute methods if they have # not been generated. # # class Person < ActiveRecord::Base -- cgit v1.2.3
-                <% extract_source[:code].each_key do |line_number| %>
+                <% source_extract[:code].each_key do |line_number| %>
 <%= line_number -%>
                 <% end %>
               
-<% extract_source[:code].each do |line, source| -%>
"><%= source -%>
<% end -%> +<% source_extract[:code].each do |line, source| -%>
"><%= source -%>
<% end -%>