diff options
41 files changed, 399 insertions, 136 deletions
diff --git a/actionmailer/test/abstract_unit.rb b/actionmailer/test/abstract_unit.rb index 93d16f491d..4e5a9c3715 100644 --- a/actionmailer/test/abstract_unit.rb +++ b/actionmailer/test/abstract_unit.rb @@ -23,10 +23,6 @@ ActiveSupport::Deprecation.debug = true # Disable available locale checks to avoid warnings running the test suite. I18n.enforce_available_locales = false -# Bogus template processors -ActionView::Template.register_template_handler :haml, lambda { |template| "Look its HAML!".inspect } -ActionView::Template.register_template_handler :bak, lambda { |template| "Lame backup".inspect } - FIXTURE_LOAD_PATH = File.expand_path('fixtures', File.dirname(__FILE__)) ActionMailer::Base.view_paths = FIXTURE_LOAD_PATH diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index dfd5ddeedf..5474f5dd58 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -1,3 +1,10 @@ +* 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. diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb index 3111992f82..5b52c19802 100644 --- a/actionpack/lib/action_controller/metal/http_authentication.rb +++ b/actionpack/lib/action_controller/metal/http_authentication.rb @@ -121,8 +121,8 @@ module ActionController def authentication_request(controller, realm) controller.headers["WWW-Authenticate"] = %(Basic realm="#{realm.gsub(/"/, "")}") - controller.response_body = "HTTP Basic: Access denied.\n" controller.status = 401 + controller.response_body = "HTTP Basic: Access denied.\n" end end @@ -256,8 +256,8 @@ module ActionController def authentication_request(controller, realm, message = nil) message ||= "HTTP Digest: Access denied.\n" authentication_header(controller, realm) - controller.response_body = message controller.status = 401 + controller.response_body = message end def secret_token(request) @@ -449,7 +449,7 @@ module ActionController authorization_request = request.authorization.to_s if authorization_request[TOKEN_REGEX] params = token_params_from authorization_request - [params.shift.last, Hash[params].with_indifferent_access] + [params.shift[1], Hash[params].with_indifferent_access] end end @@ -464,7 +464,7 @@ module ActionController # This removes the `"` characters wrapping the value. def rewrite_param_values(array_params) - array_params.each { |param| param.last.gsub! %r/^"|"$/, '' } + array_params.each { |param| (param[1] || "").gsub! %r/^"|"$/, '' } end # This method takes an authorization body and splits up the key-value diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index e6695ffc90..849286a4a9 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -629,8 +629,11 @@ module ActionController @response.prepare! @assigns = @controller.respond_to?(:view_assigns) ? @controller.view_assigns : {} - @request.session['flash'] = @request.flash.to_session_value - @request.session.delete('flash') if @request.session['flash'].blank? + + if flash_value = @request.flash.to_session_value + @request.session['flash'] = flash_value + end + @response end diff --git a/actionpack/lib/action_dispatch/http/url.rb b/actionpack/lib/action_dispatch/http/url.rb index 4cba4f5f37..a5858758c6 100644 --- a/actionpack/lib/action_dispatch/http/url.rb +++ b/actionpack/lib/action_dispatch/http/url.rb @@ -5,27 +5,26 @@ module ActionDispatch module Http module URL IP_HOST_REGEXP = /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/ - HOST_REGEXP = /(^.*:\/\/)?([^:]+)(?::(\d+$))?/ + HOST_REGEXP = /(^[^:]+:\/\/)?([^:]+)(?::(\d+$))?/ PROTOCOL_REGEXP = /^([^:]+)(:)?(\/\/)?$/ mattr_accessor :tld_length self.tld_length = 1 class << self - def extract_domain(host, tld_length = @@tld_length) - host.split('.').last(1 + tld_length).join('.') if named_host?(host) + def extract_domain(host, tld_length) + extract_domain_from(host, tld_length) if named_host?(host) end - def extract_subdomains(host, tld_length = @@tld_length) + def extract_subdomains(host, tld_length) if named_host?(host) - parts = host.split('.') - parts[0..-(tld_length + 2)] + extract_subdomains_from(host, tld_length) else [] end end - def extract_subdomain(host, tld_length = @@tld_length) + def extract_subdomain(host, tld_length) extract_subdomains(host, tld_length).join('.') end @@ -60,6 +59,15 @@ module ActionDispatch private + def extract_domain_from(host, tld_length) + host.split('.').last(1 + tld_length).join('.') + end + + def extract_subdomains_from(host, tld_length) + parts = host.split('.') + parts[0..-(tld_length + 2)] + end + def add_trailing_slash(path) # includes querysting if path.include?('?') @@ -73,38 +81,38 @@ module ActionDispatch end def build_host_url(options) - if match = options[:host].match(HOST_REGEXP) - options[:protocol] ||= match[1] unless options[:protocol] == false - options[:host] = match[2] - options[:port] = match[3] unless options.key?(:port) + protocol = options[:protocol] + host = options[:host] + port = options[:port] + if match = host.match(HOST_REGEXP) + protocol ||= match[1] unless protocol == false + host = match[2] + port = match[3] unless options.key? :port end - options[:protocol] = normalize_protocol(options) - options[:host] = normalize_host(options) - options[:port] = normalize_port(options) + protocol = normalize_protocol protocol + host = normalize_host(host, options) - result = options[:protocol] + result = protocol.dup if options[:user] && options[:password] result << "#{Rack::Utils.escape(options[:user])}:#{Rack::Utils.escape(options[:password])}@" end - result << options[:host] - result << ":#{options[:port]}" if options[:port] + result << host + normalize_port(port, protocol) { |normalized_port| + result << ":#{normalized_port}" + } result end def named_host?(host) - host && IP_HOST_REGEXP !~ host + IP_HOST_REGEXP !~ host end - def same_host?(options) - (options[:subdomain] == true || !options.key?(:subdomain)) && options[:domain].nil? - end - - def normalize_protocol(options) - case options[:protocol] + def normalize_protocol(protocol) + case protocol when nil "http://" when false, "//" @@ -112,36 +120,39 @@ module ActionDispatch when PROTOCOL_REGEXP "#{$1}://" else - raise ArgumentError, "Invalid :protocol option: #{options[:protocol].inspect}" + raise ArgumentError, "Invalid :protocol option: #{protocol.inspect}" end end - def normalize_host(options) - return options[:host] if !named_host?(options[:host]) || same_host?(options) + def normalize_host(_host, options) + return _host unless named_host?(_host) tld_length = options[:tld_length] || @@tld_length + subdomain = options.fetch :subdomain, true + domain = options[:domain] host = "" - if options[:subdomain] == true || !options.key?(:subdomain) - host << extract_subdomain(options[:host], tld_length).to_param - elsif options[:subdomain].present? - host << options[:subdomain].to_param + if subdomain == true + return _host if domain.nil? + + host << extract_subdomains_from(_host, tld_length).join('.') + elsif subdomain + host << subdomain.to_param end host << "." unless host.empty? - host << (options[:domain] || extract_domain(options[:host], tld_length)) + host << (domain || extract_domain_from(_host, tld_length)) host end - def normalize_port(options) - return nil if options[:port].nil? || options[:port] == false + def normalize_port(port, protocol) + return unless port - case options[:protocol] - when "//" - options[:port] + case protocol + when "//" then yield port when "https://" - options[:port].to_i == 443 ? nil : options[:port] + yield port unless port.to_i == 443 else - options[:port].to_i == 80 ? nil : options[:port] + yield port unless port.to_i == 80 end end end diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb index 86b94652ce..ef90fff178 100644 --- a/actionpack/test/controller/http_token_authentication_test.rb +++ b/actionpack/test/controller/http_token_authentication_test.rb @@ -132,13 +132,30 @@ class HttpTokenAuthenticationTest < ActionController::TestCase assert_equal(expected, actual) end - private - - def sample_request(token) - @sample_request ||= OpenStruct.new authorization: %{Token token="#{token}"} + test "token_and_options returns empty string with empty token" do + token = '' + actual = ActionController::HttpAuthentication::Token.token_and_options(sample_request(token)).first + expected = token + assert_equal(expected, actual) end - def encode_credentials(token, options = {}) - ActionController::HttpAuthentication::Token.encode_credentials(token, options) + test "token_and_options returns nil with no value after the equal sign" do + actual = ActionController::HttpAuthentication::Token.token_and_options(malformed_request).first + expected = nil + assert_equal(expected, actual) end + + private + + def sample_request(token) + @sample_request ||= OpenStruct.new authorization: %{Token token="#{token}", nonce="def"} + end + + def malformed_request + @malformed_request ||= OpenStruct.new authorization: %{Token token=} + end + + def encode_credentials(token, options = {}) + ActionController::HttpAuthentication::Token.encode_credentials(token, options) + end end diff --git a/actionpack/test/controller/routing_test.rb b/actionpack/test/controller/routing_test.rb index 660589a86e..721dad4dd9 100644 --- a/actionpack/test/controller/routing_test.rb +++ b/actionpack/test/controller/routing_test.rb @@ -256,7 +256,6 @@ class LegacyRouteSetTests < ActiveSupport::TestCase end def test_scoped_lambda_with_get_lambda - scope_called = false inner_called = false rs.draw do diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index f52f8be101..7210c68e73 100644 --- a/actionpack/test/controller/url_for_test.rb +++ b/actionpack/test/controller/url_for_test.rb @@ -95,7 +95,7 @@ module AbstractController end def test_subdomain_may_be_object - model = mock(:to_param => 'api') + model = Class.new { def self.to_param; 'api'; end } add_host! assert_equal('http://api.basecamphq.com/c/a/i', W.new.url_for(:subdomain => model, :controller => 'c', :action => 'a', :id => 'i') diff --git a/actionpack/test/journey/router_test.rb b/actionpack/test/journey/router_test.rb index e092432b01..2e7e8e1bea 100644 --- a/actionpack/test/journey/router_test.rb +++ b/actionpack/test/journey/router_test.rb @@ -213,8 +213,6 @@ module ActionDispatch route_set = Routing::RouteSet.new mapper = Routing::Mapper.new route_set - strexp = Router::Strexp.build("/", {}, ['/', '.', '?'], false) - path = Path::Pattern.new strexp app = lambda { |env| [200, {}, ['success!']] } mapper.get '/weblog', :to => app diff --git a/actionview/CHANGELOG.md b/actionview/CHANGELOG.md index aaa9322c4e..d825d3b627 100644 --- a/actionview/CHANGELOG.md +++ b/actionview/CHANGELOG.md @@ -1,3 +1,19 @@ +* 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* diff --git a/actionview/lib/action_view/base.rb b/actionview/lib/action_view/base.rb index 8235b30599..900f96255e 100644 --- a/actionview/lib/action_view/base.rb +++ b/actionview/lib/action_view/base.rb @@ -130,6 +130,9 @@ module ActionView #:nodoc: # end # end # end + # + # For more information on Builder please consult the [source + # code](https://github.com/jimweirich/builder). class Base include Helpers, ::ERB::Util, Context diff --git a/actionview/lib/action_view/helpers/output_safety_helper.rb b/actionview/lib/action_view/helpers/output_safety_helper.rb index e1f40011c0..b0d9c7c7f9 100644 --- a/actionview/lib/action_view/helpers/output_safety_helper.rb +++ b/actionview/lib/action_view/helpers/output_safety_helper.rb @@ -18,9 +18,9 @@ module ActionView #:nodoc: end # This method returns a html safe string similar to what <tt>Array#join</tt> - # would return. All items in the array, including the supplied separator, are - # html escaped unless they are html safe, and the returned string is marked - # as html safe. + # would return. The array is flattened, and all items, including + # the supplied separator, are html escaped unless they are html + # safe, and the returned string is marked as html safe. # # safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />") # # => "<p>foo</p><br /><p>bar</p>" @@ -31,7 +31,7 @@ module ActionView #:nodoc: def safe_join(array, sep=$,) sep = ERB::Util.unwrapped_html_escape(sep) - array.map { |i| ERB::Util.unwrapped_html_escape(i) }.join(sep).html_safe + array.flatten.map! { |i| ERB::Util.unwrapped_html_escape(i) }.join(sep).html_safe end end end diff --git a/actionview/lib/action_view/helpers/tag_helper.rb b/actionview/lib/action_view/helpers/tag_helper.rb index 9b9ca7d60d..35444bcfb4 100644 --- a/actionview/lib/action_view/helpers/tag_helper.rb +++ b/actionview/lib/action_view/helpers/tag_helper.rb @@ -173,8 +173,11 @@ module ActionView end def tag_option(key, value, escape) - value = value.join(" ") if value.is_a?(Array) - value = ERB::Util.unwrapped_html_escape(value) if escape + if value.is_a?(Array) + value = escape ? safe_join(value, " ") : value.join(" ") + else + value = escape ? ERB::Util.unwrapped_html_escape(value) : value + end %(#{key}="#{value}") end end diff --git a/actionview/lib/action_view/template/handlers.rb b/actionview/lib/action_view/template/handlers.rb index d9cddc0040..33bfcb458c 100644 --- a/actionview/lib/action_view/template/handlers.rb +++ b/actionview/lib/action_view/template/handlers.rb @@ -32,6 +32,15 @@ module ActionView #:nodoc: @@template_extensions = nil end + # Opposite to register_template_handler. + def unregister_template_handler(*extensions) + extensions.each do |extension| + handler = @@template_handlers.delete extension.to_sym + @@default_template_handlers = nil if @@default_template_handlers == handler + end + @@template_extensions = nil + end + def template_handler_extensions @@template_handlers.keys.map {|key| key.to_s }.sort end diff --git a/actionview/test/actionpack/controller/layout_test.rb b/actionview/test/actionpack/controller/layout_test.rb index b44f57a23e..bd345fe873 100644 --- a/actionview/test/actionpack/controller/layout_test.rb +++ b/actionview/test/actionpack/controller/layout_test.rb @@ -6,9 +6,6 @@ require 'active_support/core_ext/array/extract_options' # method has access to the view_paths array when looking for a layout to automatically assign. old_load_paths = ActionController::Base.view_paths -ActionView::Template::register_template_handler :mab, - lambda { |template| template.source.inspect } - ActionController::Base.view_paths = [ File.dirname(__FILE__) + '/../../fixtures/actionpack/layout_tests/' ] class LayoutTest < ActionController::Base @@ -17,6 +14,15 @@ class LayoutTest < ActionController::Base self.view_paths = ActionController::Base.view_paths.dup end +module TemplateHandlerHelper + def with_template_handler(*extensions, handler) + ActionView::Template.register_template_handler(*extensions, handler) + yield + ensure + ActionView::Template.unregister_template_handler(*extensions) + end +end + # Restore view_paths to previous value ActionController::Base.view_paths = old_load_paths @@ -39,6 +45,8 @@ class MultipleExtensions < LayoutTest end class LayoutAutoDiscoveryTest < ActionController::TestCase + include TemplateHandlerHelper + def setup super @request.host = "www.nextangle.com" @@ -57,10 +65,12 @@ class LayoutAutoDiscoveryTest < ActionController::TestCase end def test_third_party_template_library_auto_discovers_layout - @controller = ThirdPartyTemplateLibraryController.new - get :hello - assert_response :success - assert_equal 'layouts/third_party_template_library.mab', @response.body + with_template_handler :mab, lambda { |template| template.source.inspect } do + @controller = ThirdPartyTemplateLibraryController.new + get :hello + assert_response :success + assert_equal 'layouts/third_party_template_library.mab', @response.body + end end def test_namespaced_controllers_auto_detect_layouts1 @@ -135,6 +145,7 @@ end class LayoutSetInResponseTest < ActionController::TestCase include ActionView::Template::Handlers + include TemplateHandlerHelper def test_layout_set_when_using_default_layout @controller = DefaultLayoutController.new @@ -191,9 +202,11 @@ class LayoutSetInResponseTest < ActionController::TestCase end def test_layout_set_when_using_render - @controller = SetsLayoutInRenderController.new - get :hello - assert_template :layout => "layouts/third_party_template_library" + with_template_handler :mab, lambda { |template| template.source.inspect } do + @controller = SetsLayoutInRenderController.new + get :hello + assert_template :layout => "layouts/third_party_template_library" + end end def test_layout_is_not_set_when_none_rendered diff --git a/actionview/test/template/dependency_tracker_test.rb b/actionview/test/template/dependency_tracker_test.rb index df3a0602d1..6c780f2297 100644 --- a/actionview/test/template/dependency_tracker_test.rb +++ b/actionview/test/template/dependency_tracker_test.rb @@ -31,6 +31,7 @@ class DependencyTrackerTest < ActionView::TestCase end def teardown + ActionView::Template.unregister_template_handler :neckbeard tracker.remove_tracker(:neckbeard) end diff --git a/actionview/test/template/output_safety_helper_test.rb b/actionview/test/template/output_safety_helper_test.rb index 76c71c9e6d..a1bf0e1a5f 100644 --- a/actionview/test/template/output_safety_helper_test.rb +++ b/actionview/test/template/output_safety_helper_test.rb @@ -25,4 +25,11 @@ class OutputSafetyHelperTest < ActionView::TestCase assert_equal "<p>foo</p><br /><p>bar</p>", joined end -end
\ No newline at end of file + test "safe_join should work recursively similarly to Array.join" do + joined = safe_join(['a',['b','c']], ':') + assert_equal 'a:b:c', joined + + joined = safe_join(['"a"',['<b>','<c>']], ' <br/> ') + assert_equal '"a" <br/> <b> <br/> <c>', joined + end +end diff --git a/actionview/test/template/render_test.rb b/actionview/test/template/render_test.rb index ca508abfb8..240a8e3c32 100644 --- a/actionview/test/template/render_test.rb +++ b/actionview/test/template/render_test.rb @@ -369,23 +369,40 @@ module RenderTestCases def test_render_inline_with_render_from_to_proc ActionView::Template.register_template_handler :ruby_handler, :source.to_proc - assert_equal '3', @view.render(:inline => "(1 + 2).to_s", :type => :ruby_handler) + assert_equal '3', @view.render(inline: "(1 + 2).to_s", type: :ruby_handler) + ensure + ActionView::Template.unregister_template_handler :ruby_handler end def test_render_inline_with_compilable_custom_type ActionView::Template.register_template_handler :foo, CustomHandler - assert_equal 'source: "Hello, World!"', @view.render(:inline => "Hello, World!", :type => :foo) + assert_equal 'source: "Hello, World!"', @view.render(inline: "Hello, World!", type: :foo) + ensure + ActionView::Template.unregister_template_handler :foo end def test_render_inline_with_locals_and_compilable_custom_type ActionView::Template.register_template_handler :foo, CustomHandler - assert_equal 'source: "Hello, <%= name %>!"', @view.render(:inline => "Hello, <%= name %>!", :locals => { :name => "Josh" }, :type => :foo) + assert_equal 'source: "Hello, <%= name %>!"', @view.render(inline: "Hello, <%= name %>!", locals: { name: "Josh" }, type: :foo) + ensure + ActionView::Template.unregister_template_handler :foo end def test_render_knows_about_types_registered_when_extensions_are_checked_earlier_in_initialization ActionView::Template::Handlers.extensions ActionView::Template.register_template_handler :foo, CustomHandler assert ActionView::Template::Handlers.extensions.include?(:foo) + ensure + ActionView::Template.unregister_template_handler :foo + end + + def test_render_does_not_use_unregistered_extension_and_template_handler + ActionView::Template.register_template_handler :foo, CustomHandler + ActionView::Template.unregister_template_handler :foo + assert_not ActionView::Template::Handlers.extensions.include?(:foo) + assert_equal "Hello, World!", @view.render(inline: "Hello, World!", type: :foo) + ensure + ActionView::Template::Handlers.class_variable_get(:@@template_handlers).delete(:foo) end def test_render_ignores_templates_with_malformed_template_handlers @@ -474,7 +491,9 @@ module RenderTestCases def test_render_with_passing_couple_extensions_to_one_register_template_handler_function_call ActionView::Template.register_template_handler :foo1, :foo2, CustomHandler - assert_equal @view.render(:inline => "Hello, World!", :type => :foo1), @view.render(:inline => "Hello, World!", :type => :foo2) + assert_equal @view.render(inline: "Hello, World!", type: :foo1), @view.render(inline: "Hello, World!", type: :foo2) + ensure + ActionView::Template.unregister_template_handler :foo1, :foo2 end def test_render_throws_exception_when_no_extensions_passed_to_register_template_handler_function_call diff --git a/actionview/test/template/tag_helper_test.rb b/actionview/test/template/tag_helper_test.rb index fb016a52de..c78b6450f2 100644 --- a/actionview/test/template/tag_helper_test.rb +++ b/actionview/test/template/tag_helper_test.rb @@ -80,11 +80,27 @@ class TagHelperTest < ActionView::TestCase str = content_tag('p', "limelight", :class => ["song", "play"]) assert_equal "<p class=\"song play\">limelight</p>", str + + str = content_tag('p', "limelight", :class => ["song", ["play"]]) + assert_equal "<p class=\"song play\">limelight</p>", str end def test_content_tag_with_unescaped_array_class str = content_tag('p', "limelight", {:class => ["song", "play>"]}, false) assert_equal "<p class=\"song play>\">limelight</p>", str + + str = content_tag('p', "limelight", {:class => ["song", ["play>"]]}, false) + assert_equal "<p class=\"song play>\">limelight</p>", str + end + + def test_content_tag_with_empty_array_class + str = content_tag('p', 'limelight', {:class => []}) + assert_equal '<p class="">limelight</p>', str + end + + def test_content_tag_with_unescaped_empty_array_class + str = content_tag('p', 'limelight', {:class => []}, false) + assert_equal '<p class="">limelight</p>', str end def test_content_tag_with_data_attributes @@ -115,6 +131,14 @@ class TagHelperTest < ActionView::TestCase end end + def test_tag_honors_html_safe_with_escaped_array_class + str = tag('p', :class => ['song>', 'play>'.html_safe]) + assert_equal '<p class="song> play>" />', str + + str = tag('p', :class => ['song>'.html_safe, 'play>']) + assert_equal '<p class="song> play>" />', str + end + def test_skip_invalid_escaped_attributes ['&1;', 'dfa3;', '& #123;'].each do |escaped| assert_equal %(<a href="#{escaped.gsub(/&/, '&')}" />), tag('a', :href => escaped) diff --git a/activemodel/lib/active_model/conversion.rb b/activemodel/lib/active_model/conversion.rb index 374265f0d8..9c9b6f4a77 100644 --- a/activemodel/lib/active_model/conversion.rb +++ b/activemodel/lib/active_model/conversion.rb @@ -40,13 +40,15 @@ module ActiveModel self end - # Returns an Enumerable of all key attributes if any is set, regardless if + # Returns an Array of all key attributes if any is set, regardless if # the object is persisted or not. Returns +nil+ if there are no key attributes. # - # class Person < ActiveRecord::Base + # class Person + # include ActiveModel::Conversion + # attr_accessor :id # end # - # person = Person.create + # person = Person.create(id: 1) # person.to_key # => [1] def to_key key = respond_to?(:id) && id @@ -56,10 +58,15 @@ module ActiveModel # Returns a +string+ representing the object's key suitable for use in URLs, # or +nil+ if <tt>persisted?</tt> is +false+. # - # class Person < ActiveRecord::Base + # class Person + # include ActiveModel::Conversion + # attr_accessor :id + # def persisted? + # true + # end # end # - # person = Person.create + # person = Person.create(id: 1) # person.to_param # => "1" def to_param (persisted? && key = to_key) ? key.join('-') : nil diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 8e958a851e..efa4abfa4d 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,17 @@ +* Fixed automatic maintaining test schema to properly handle sql structure + schema format. + + Fixes #15394. + + *Wojciech Wnętrzak* + +* 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* diff --git a/activerecord/lib/active_record/attribute_methods/primary_key.rb b/activerecord/lib/active_record/attribute_methods/primary_key.rb index 931209b07b..1c81a5b71b 100644 --- a/activerecord/lib/active_record/attribute_methods/primary_key.rb +++ b/activerecord/lib/active_record/attribute_methods/primary_key.rb @@ -15,8 +15,10 @@ module ActiveRecord # Returns the primary key value. def id - sync_with_transaction_state - read_attribute(self.class.primary_key) + if pk = self.class.primary_key + sync_with_transaction_state + read_attribute(pk) + end end # Sets the primary key value. diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb index d3e172927d..5a0efe49c7 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_dumper.rb @@ -1,5 +1,3 @@ -require 'ipaddr' - module ActiveRecord module ConnectionAdapters # :nodoc: # The goal of this module is to move Adapter specific column diff --git a/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb b/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb index 87817fe8d1..4e7d472d97 100644 --- a/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb +++ b/activerecord/lib/active_record/connection_adapters/postgresql/oid/array.rb @@ -12,12 +12,16 @@ module ActiveRecord def type_cast_from_database(value) if value.is_a?(::String) - type_cast_array(parse_pg_array(value)) + type_cast_array(parse_pg_array(value), :type_cast_from_database) else super end end + def type_cast_from_user(value) + type_cast_array(value, :type_cast_from_user) + end + # Loads pg_array_parser if available. String parsing can be # performed quicker by a native extension, which will not create # a large amount of Ruby objects that will need to be garbage @@ -32,11 +36,11 @@ module ActiveRecord private - def type_cast_array(value) + def type_cast_array(value, method) if value.is_a?(::Array) - value.map { |item| type_cast_array(item) } + value.map { |item| type_cast_array(item, method) } else - @subtype.type_cast_from_database(value) + @subtype.public_send(method, value) end end end diff --git a/activerecord/lib/active_record/core.rb b/activerecord/lib/active_record/core.rb index 7edaf256c7..86b4cc90ea 100644 --- a/activerecord/lib/active_record/core.rb +++ b/activerecord/lib/active_record/core.rb @@ -380,7 +380,11 @@ module ActiveRecord # Delegates to id in order to allow two records of the same type and id to work with something like: # [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ] def hash - id.hash + if id + id.hash + else + super + end end # Clone and freeze the attributes hash such that associations are still diff --git a/activerecord/lib/active_record/relation/calculations.rb b/activerecord/lib/active_record/relation/calculations.rb index 38970a66ae..028e4d80ab 100644 --- a/activerecord/lib/active_record/relation/calculations.rb +++ b/activerecord/lib/active_record/relation/calculations.rb @@ -176,9 +176,7 @@ module ActiveRecord } end - result = result.map do |attributes| - values = attributes.values - + result = result.rows.map do |values| columns.zip(values).map { |column, value| column.type_cast_from_database value } end columns.one? ? result.map!(&:first) : result diff --git a/activerecord/lib/active_record/tasks/database_tasks.rb b/activerecord/lib/active_record/tasks/database_tasks.rb index 168b338b97..649f316ed8 100644 --- a/activerecord/lib/active_record/tasks/database_tasks.rb +++ b/activerecord/lib/active_record/tasks/database_tasks.rb @@ -6,7 +6,7 @@ module ActiveRecord # <tt>ActiveRecord::Tasks::DatabaseTasks</tt> is a utility class, which encapsulates # logic behind common tasks used to manage database and migrations. # - # The tasks defined here are used in rake tasks provided by Active Record. + # The tasks defined here are used with Rake tasks provided by Active Record. # # In order to use DatabaseTasks, a few config values need to be set. All the needed # config values are set by Rails already, so it's necessary to do it only if you @@ -14,7 +14,6 @@ module ActiveRecord # (in such case after configuring the database tasks, you can also use the rake tasks # defined in Active Record). # - # # The possible config values are: # # * +env+: current environment (like Rails.env). @@ -161,10 +160,12 @@ module ActiveRecord when :ruby file ||= File.join(db_dir, "schema.rb") check_schema_file(file) + purge(current_config) load(file) when :sql file ||= File.join(db_dir, "structure.sql") check_schema_file(file) + purge(current_config) structure_load(current_config, file) else raise ArgumentError, "unknown format #{format.inspect}" diff --git a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb index 5688931db2..9ab64d0325 100644 --- a/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb +++ b/activerecord/lib/active_record/tasks/sqlite_database_tasks.rb @@ -21,7 +21,11 @@ module ActiveRecord FileUtils.rm(file) if File.exist?(file) end - alias :purge :drop + + def purge + drop + create + end def charset connection.encoding diff --git a/activerecord/test/cases/adapters/postgresql/array_test.rb b/activerecord/test/cases/adapters/postgresql/array_test.rb index 66750deb68..0b1e3295cc 100644 --- a/activerecord/test/cases/adapters/postgresql/array_test.rb +++ b/activerecord/test/cases/adapters/postgresql/array_test.rb @@ -97,8 +97,13 @@ class PostgresqlArrayTest < ActiveRecord::TestCase def test_type_cast_integers x = PgArray.new(ratings: ['1', '2']) - assert x.save! - assert_equal(['1', '2'], x.ratings) + + assert_equal([1, 2], x.ratings) + + x.save! + x.reload + + assert_equal([1, 2], x.ratings) end def test_select_with_strings diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb index dc8f25b0e7..541f74f21e 100644 --- a/activerecord/test/cases/base_test.rb +++ b/activerecord/test/cases/base_test.rb @@ -1597,4 +1597,11 @@ class BasicsTest < ActiveRecord::TestCase assert_equal after_handler, new_handler assert_equal orig_handler, klass.connection_handler end + + # Note: This is a performance optimization for Array#uniq and Hash#[] with + # AR::Base objects. If the future has made this irrelevant, feel free to + # delete this. + test "records without an id have unique hashes" do + assert_not_equal Post.new.hash, Post.new.hash + end end diff --git a/activerecord/test/cases/calculations_test.rb b/activerecord/test/cases/calculations_test.rb index dfc6a7ec67..222b1505a8 100644 --- a/activerecord/test/cases/calculations_test.rb +++ b/activerecord/test/cases/calculations_test.rb @@ -610,4 +610,11 @@ class CalculationsTest < ActiveRecord::TestCase assert_equal [1,2,3,4,5], taks_relation.pluck(:id) assert_equal [false, true, true, true, true], taks_relation.pluck(:approved) end + + def test_pluck_columns_with_same_name + expected = [["The First Topic", "The Second Topic of the day"], ["The Third Topic of the day", "The Fourth Topic of the day"]] + actual = Topic.joins(:replies) + .pluck('topics.title', 'replies_topics.title') + assert_equal expected, actual + end end diff --git a/activerecord/test/cases/persistence_test.rb b/activerecord/test/cases/persistence_test.rb index 7f5d0d66d3..bc21eef919 100644 --- a/activerecord/test/cases/persistence_test.rb +++ b/activerecord/test/cases/persistence_test.rb @@ -514,14 +514,14 @@ class PersistenceTest < ActiveRecord::TestCase def test_update_column_should_not_leave_the_object_dirty topic = Topic.find(1) - topic.update_column("content", "Have a nice day") + topic.update_column("content", "--- Have a nice day\n...\n") topic.reload - topic.update_column(:content, "You too") + topic.update_column(:content, "--- You too\n...\n") assert_equal [], topic.changed topic.reload - topic.update_column("content", "Have a nice day") + topic.update_column("content", "--- Have a nice day\n...\n") assert_equal [], topic.changed end @@ -605,14 +605,14 @@ class PersistenceTest < ActiveRecord::TestCase def test_update_columns_should_not_leave_the_object_dirty topic = Topic.find(1) - topic.update({ "content" => "Have a nice day", :author_name => "Jose" }) + topic.update({ "content" => "--- Have a nice day\n...\n", :author_name => "Jose" }) topic.reload - topic.update_columns({ content: "You too", "author_name" => "Sebastian" }) + topic.update_columns({ content: "--- You too\n...\n", "author_name" => "Sebastian" }) assert_equal [], topic.changed topic.reload - topic.update_columns({ content: "Have a nice day", author_name: "Jose" }) + topic.update_columns({ content: "--- Have a nice day\n...\n", author_name: "Jose" }) assert_equal [], topic.changed end diff --git a/activerecord/test/fixtures/topics.yml b/activerecord/test/fixtures/topics.yml index bf049abbf1..4c98b10380 100644 --- a/activerecord/test/fixtures/topics.yml +++ b/activerecord/test/fixtures/topics.yml @@ -6,7 +6,7 @@ first: written_on: 2003-07-16t15:28:11.2233+01:00 last_read: 2004-04-15 bonus_time: 2005-01-30t15:28:00.00+01:00 - content: Have a nice day + content: "--- Have a nice day\n...\n" approved: false replies_count: 1 @@ -15,7 +15,7 @@ second: title: The Second Topic of the day author_name: Mary written_on: 2004-07-15t15:28:00.0099+01:00 - content: Have a nice day + content: "--- Have a nice day\n...\n" approved: true replies_count: 0 parent_id: 1 @@ -26,7 +26,7 @@ third: title: The Third Topic of the day author_name: Carl written_on: 2012-08-12t20:24:22.129346+00:00 - content: I'm a troll + content: "--- I'm a troll\n...\n" approved: true replies_count: 1 @@ -35,7 +35,7 @@ fourth: title: The Fourth Topic of the day author_name: Carl written_on: 2006-07-15t15:28:00.0099+01:00 - content: Why not? + content: "--- Why not?\n...\n" approved: true type: Reply parent_id: 3 @@ -45,5 +45,5 @@ fifth: title: The Fifth Topic of the day author_name: Jason written_on: 2013-07-13t12:11:00.0099+01:00 - content: Omakase + content: "--- Omakase\n...\n" approved: true diff --git a/activesupport/lib/active_support/core_ext/object/duplicable.rb b/activesupport/lib/active_support/core_ext/object/duplicable.rb index 3d2c809c9f..c5d59128e5 100644 --- a/activesupport/lib/active_support/core_ext/object/duplicable.rb +++ b/activesupport/lib/active_support/core_ext/object/duplicable.rb @@ -19,7 +19,7 @@ class Object # Can you safely dup this object? # - # False for +nil+, +false+, +true+, symbol, and number objects; + # False for +nil+, +false+, +true+, symbol, number and BigDecimal(in 1.9.x) objects; # true otherwise. def duplicable? true diff --git a/activesupport/lib/active_support/testing/assertions.rb b/activesupport/lib/active_support/testing/assertions.rb index 76a591bc3b..11cca82995 100644 --- a/activesupport/lib/active_support/testing/assertions.rb +++ b/activesupport/lib/active_support/testing/assertions.rb @@ -9,7 +9,7 @@ module ActiveSupport # # assert_not nil # => true # assert_not false # => true - # assert_not 'foo' # => 'foo' is not nil or false + # assert_not 'foo' # => Expected "foo" to be nil or false # # An error message can be specified. # diff --git a/guides/source/action_mailer_basics.md b/guides/source/action_mailer_basics.md index c7117027c0..cb1c1c653d 100644 --- a/guides/source/action_mailer_basics.md +++ b/guides/source/action_mailer_basics.md @@ -309,7 +309,7 @@ email address in the format `"Full Name <email>"`. ```ruby def welcome_email(user) @user = user - email_with_name = "#{@user.name} <#{@user.email}>" + email_with_name = %("#{@user.name}" <#{@user.email}>) mail(to: email_with_name, subject: 'Welcome to My Awesome Site') end ``` diff --git a/guides/source/active_record_postgresql.md b/guides/source/active_record_postgresql.md index fa135b537c..248d4769a1 100644 --- a/guides/source/active_record_postgresql.md +++ b/guides/source/active_record_postgresql.md @@ -8,6 +8,7 @@ After reading this guide, you will know: * How to use PostgreSQL's datatypes. * How to use UUID primary keys. * How to implement full text search with PostgreSQL. +* How to back your Active Record models with views. -------------------------------------------------------------------------------- @@ -324,7 +325,8 @@ macbook.address * [type definition](http://www.postgresql.org/docs/9.3/static/datatype-geometric.html) -All geometric types are mapped to normal text. +All geometric types, with the exception of `points` are mapped to normal text. +A point is casted to an array containing `x` and `y` coordinates. UUID Primary Keys @@ -428,7 +430,7 @@ second = Article.create! title: "Brace yourself", Article.count # => 1 first.archive! -p Article.count # => 2 +Article.count # => 2 ``` NOTE: This application only cares about non-archived `Articles`. A view also diff --git a/guides/source/api_documentation_guidelines.md b/guides/source/api_documentation_guidelines.md index dda9baa8d7..2b6a9f61eb 100644 --- a/guides/source/api_documentation_guidelines.md +++ b/guides/source/api_documentation_guidelines.md @@ -13,7 +13,8 @@ After reading this guide, you will know: RDoc ---- -The [Rails API documentation](http://api.rubyonrails.org) is generated with RDoc. +The [Rails API documentation](http://api.rubyonrails.org) is generated with +[RDoc](http://docs.seattlerb.org/rdoc/). ```bash bundle exec rake rdoc @@ -21,6 +22,11 @@ The [Rails API documentation](http://api.rubyonrails.org) is generated with RDoc Resulting HTML files can be found in the ./doc/rdoc directory. +Please consult the RDoc documentation for help with the +[markup](http://docs.seattlerb.org/rdoc/RDoc/Markup.html), +and also take into account these [additional +directives](http://docs.seattlerb.org/rdoc/RDoc/Parser/Ruby.html). + Wording ------- diff --git a/guides/source/asset_pipeline.md b/guides/source/asset_pipeline.md index 526126e93d..2d1548f252 100644 --- a/guides/source/asset_pipeline.md +++ b/guides/source/asset_pipeline.md @@ -709,7 +709,7 @@ The default matcher for compiling files includes `application.js`, automatically) from `app/assets` folders including your gems: ```ruby -[ Proc.new { |path, fn| fn =~ /app\/assets/ && !%w(.js .css).include?(File.extname(path)) }, +[ Proc.new { |filename, path| path =~ /app\/assets/ && !%w(.js .css).include?(File.extname(filename)) }, /application.(css|js)$/ ] ``` @@ -856,10 +856,12 @@ duplication of work. Local compilation allows you to commit the compiled files into source control, and deploy as normal. -There are two caveats: +There are three caveats: * You must not run the Capistrano deployment task that precompiles assets. -* You must change the following two application configuration settings. +* You must ensure any necessary compressors or minifiers are +available on your development system. +* You must change the following application configuration setting: In `config/environments/development.rb`, place the following line: @@ -873,9 +875,6 @@ development mode, and pass all requests to Sprockets. The prefix is still set to would serve the precompiled assets from `/assets` in development, and you would not see any local changes until you compile assets again. -You will also need to ensure any necessary compressors or minifiers are -available on your development system. - In practice, this will allow you to precompile locally, have those files in your working tree, and commit those files to source control when needed. Development mode will work as expected. diff --git a/railties/test/application/test_test.rb b/railties/test/application/test_test.rb index a223180169..c724c867ec 100644 --- a/railties/test/application/test_test.rb +++ b/railties/test/application/test_test.rb @@ -67,7 +67,7 @@ module ApplicationTests assert_match %r{/app/test/unit/failing_test\.rb}, output end - test "migrations" do + test "ruby schema migrations" do output = script('generate model user name:string') version = output.match(/(\d+)_create_users\.rb/)[1] @@ -104,6 +104,95 @@ module ApplicationTests assert !result.include?("create_table(:users)") end + test "sql structure migrations" 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 + User.create! name: "Jon" + end + end + RUBY + + app_file 'db/structure.sql', '' + app_file 'config/initializers/enable_sql_schema_format.rb', <<-RUBY + Rails.application.config.active_record.schema_format = :sql + RUBY + + assert_unsuccessful_run "models/user_test.rb", "Migrations are pending" + + app_file 'db/structure.sql', <<-SQL + CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL); + CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version"); + CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255)); + INSERT INTO schema_migrations (version) VALUES ('#{version}'); + SQL + + app_file 'config/initializers/disable_maintain_test_schema.rb', <<-RUBY + Rails.application.config.active_record.maintain_test_schema = false + RUBY + + assert_unsuccessful_run "models/user_test.rb", "Could not find table 'users'" + + File.delete "#{app_path}/config/initializers/disable_maintain_test_schema.rb" + + assert_successful_test_run('models/user_test.rb') + end + + test "sql structure migrations when adding column to existing table" do + output_1 = script('generate model user name:string') + version_1 = output_1.match(/(\d+)_create_users\.rb/)[1] + + 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 + + app_file 'config/initializers/enable_sql_schema_format.rb', <<-RUBY + Rails.application.config.active_record.schema_format = :sql + RUBY + + app_file 'db/structure.sql', <<-SQL + CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL); + CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version"); + CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255)); + INSERT INTO schema_migrations (version) VALUES ('#{version_1}'); + SQL + + assert_successful_test_run('models/user_test.rb') + + output_2 = script('generate migration add_email_to_users') + version_2 = output_2.match(/(\d+)_add_email_to_users\.rb/)[1] + + app_file 'test/models/user_test.rb', <<-RUBY + require 'test_helper' + + class UserTest < ActiveSupport::TestCase + test "user" do + User.create! name: "Jon", email: "jon@doe.com" + end + end + RUBY + + app_file 'db/structure.sql', <<-SQL + CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL); + CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version"); + CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "email" varchar(255)); + INSERT INTO schema_migrations (version) VALUES ('#{version_1}'); + INSERT INTO schema_migrations (version) VALUES ('#{version_2}'); + SQL + + assert_successful_test_run('models/user_test.rb') + end + private def assert_unsuccessful_run(name, message) result = run_test_file(name) diff --git a/railties/test/rails_info_test.rb b/railties/test/rails_info_test.rb index 44a5fd1904..4bec302ff8 100644 --- a/railties/test/rails_info_test.rb +++ b/railties/test/rails_info_test.rb @@ -66,16 +66,6 @@ class InfoTest < ActiveSupport::TestCase end protected - def svn_info=(info) - Rails::Info.module_eval do - class << self - def svn_info - info - end - end - end - end - def properties Rails::Info.properties end |