diff options
Diffstat (limited to 'actionpack')
78 files changed, 621 insertions, 519 deletions
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md index 3123fc9786..425a9d9e87 100644 --- a/actionpack/CHANGELOG.md +++ b/actionpack/CHANGELOG.md @@ -1,15 +1,27 @@ +* Remove deprecated `ActionController::Metal.call`. + + *Rafael Mendonça França* + +* Remove deprecated `ActionController::Metal#env`. + + *Rafael Mendonça França* + +* Make `with_routing` test helper work when testing controllers inheriting from `ActionController::API` + + *Julia López* + * Use accept header in integration tests with `as: :json` - Instead of appending the `format` to the request path. Rails will figure + Instead of appending the `format` to the request path, Rails will figure out the format from the header instead. This allows devs to use `:as` on routes that don't have a format. - + Fixes #27144. *Kasper Timm Hansen* -* Reset a new session directly after its creation in ActionDispatch::IntegrationTest#open_session. +* Reset a new session directly after its creation in `ActionDispatch::IntegrationTest#open_session`. Fixes #22742. diff --git a/actionpack/MIT-LICENSE b/actionpack/MIT-LICENSE index 8573eb1225..ac810e86d0 100644 --- a/actionpack/MIT-LICENSE +++ b/actionpack/MIT-LICENSE @@ -1,4 +1,4 @@ -Copyright (c) 2004-2016 David Heinemeier Hansson +Copyright (c) 2004-2017 David Heinemeier Hansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the diff --git a/actionpack/lib/abstract_controller/caching.rb b/actionpack/lib/abstract_controller/caching.rb index d222880922..26e3f08bc1 100644 --- a/actionpack/lib/abstract_controller/caching.rb +++ b/actionpack/lib/abstract_controller/caching.rb @@ -52,9 +52,9 @@ module AbstractController self.class._view_cache_dependencies.map { |dep| instance_exec(&dep) }.compact end - protected + private # Convenience accessor. - def cache(key, options = {}, &block) + def cache(key, options = {}, &block) # :doc: if cache_configured? cache_store.fetch(ActiveSupport::Cache.expand_cache_key(key, :controller), options, &block) else diff --git a/actionpack/lib/abstract_controller/collector.rb b/actionpack/lib/abstract_controller/collector.rb index 57714b0588..40ae5aa1ca 100644 --- a/actionpack/lib/abstract_controller/collector.rb +++ b/actionpack/lib/abstract_controller/collector.rb @@ -19,7 +19,7 @@ module AbstractController generate_method_for_mime(mime) unless instance_methods.include?(mime.to_sym) end - protected + private def method_missing(symbol, &block) unless mime_constant = Mime[symbol] diff --git a/actionpack/lib/abstract_controller/rendering.rb b/actionpack/lib/abstract_controller/rendering.rb index d339580435..54af938a93 100644 --- a/actionpack/lib/abstract_controller/rendering.rb +++ b/actionpack/lib/abstract_controller/rendering.rb @@ -109,6 +109,9 @@ module AbstractController def _process_format(format) end + def _process_variant(options) + end + def _set_html_content_type # :nodoc: end @@ -119,10 +122,7 @@ module AbstractController # :api: private def _normalize_render(*args, &block) options = _normalize_args(*args, &block) - #TODO: remove defined? when we restore AP <=> AV dependency - if defined?(request) && !request.nil? && request.variant.present? - options[:variant] = request.variant - end + _process_variant(options) _normalize_options(options) options end diff --git a/actionpack/lib/action_controller/metal.rb b/actionpack/lib/action_controller/metal.rb index ed93a2f09c..337718afc0 100644 --- a/actionpack/lib/action_controller/metal.rb +++ b/actionpack/lib/action_controller/metal.rb @@ -118,11 +118,6 @@ module ActionController class Metal < AbstractController::Base abstract! - def env - @_request.env - end - deprecate :env - # Returns the last part of the controller's name, underscored, without the ending # <tt>Controller</tt>. For instance, PostsController returns <tt>posts</tt>. # Namespaces are left out, so Admin::PostsController returns <tt>posts</tt> as well. @@ -139,8 +134,8 @@ module ActionController end end - def self.encoding_for_param(action, param) # :nodoc: - ::Encoding::UTF_8 + def self.binary_params_for?(action) # :nodoc: + false end # Delegates to the class' <tt>controller_name</tt> @@ -232,14 +227,6 @@ module ActionController middleware_stack end - # Makes the controller a Rack endpoint that runs the action in the given - # +env+'s +action_dispatch.request.path_parameters+ key. - def self.call(env) - req = ActionDispatch::Request.new env - action(req.path_parameters[:action]).call(env) - end - class << self; deprecate :call; end - # Returns a Rack endpoint for the given action name. def self.action(name) if middleware_stack.any? diff --git a/actionpack/lib/action_controller/metal/data_streaming.rb b/actionpack/lib/action_controller/metal/data_streaming.rb index f089c8423b..731e03e2fc 100644 --- a/actionpack/lib/action_controller/metal/data_streaming.rb +++ b/actionpack/lib/action_controller/metal/data_streaming.rb @@ -11,7 +11,7 @@ module ActionController #:nodoc: DEFAULT_SEND_FILE_TYPE = "application/octet-stream".freeze #:nodoc: DEFAULT_SEND_FILE_DISPOSITION = "attachment".freeze #:nodoc: - protected + private # Sends the file. This uses a server-appropriate method (such as X-Sendfile) # via the Rack::Sendfile middleware. The header to use is set via # +config.action_dispatch.x_sendfile_header+. @@ -70,7 +70,6 @@ module ActionController #:nodoc: send_file_headers! options self.status = options[:status] || 200 - self.content_type = options[:type] if options.key?(:type) self.content_type = options[:content_type] if options.key?(:content_type) response.send_file path end @@ -109,10 +108,12 @@ module ActionController #:nodoc: render options.slice(:status, :content_type).merge(body: data) end - private def send_file_headers!(options) type_provided = options.has_key?(:type) + self.content_type = DEFAULT_SEND_FILE_TYPE + response.sending_file = true + content_type = options.fetch(:type, DEFAULT_SEND_FILE_TYPE) raise ArgumentError, ":type option required" if content_type.nil? @@ -137,8 +138,6 @@ module ActionController #:nodoc: headers["Content-Transfer-Encoding"] = "binary" - response.sending_file = true - # Fix a problem with IE 6.0 on opening downloaded files: # If Cache-Control: no-cache is set (which Rails does by default), # IE removes the file it just downloaded from its cache immediately diff --git a/actionpack/lib/action_controller/metal/flash.rb b/actionpack/lib/action_controller/metal/flash.rb index 65351284b9..347fbf0e74 100644 --- a/actionpack/lib/action_controller/metal/flash.rb +++ b/actionpack/lib/action_controller/metal/flash.rb @@ -42,7 +42,7 @@ module ActionController #:nodoc: end end - protected + private def redirect_to(options = {}, response_status_and_flash = {}) #:doc: self.class._flash_types.each do |flash_type| if type = response_status_and_flash.delete(flash_type) diff --git a/actionpack/lib/action_controller/metal/head.rb b/actionpack/lib/action_controller/metal/head.rb index 4dff23dd85..0c50894bce 100644 --- a/actionpack/lib/action_controller/metal/head.rb +++ b/actionpack/lib/action_controller/metal/head.rb @@ -37,7 +37,7 @@ module ActionController if include_content?(response_code) self.content_type = content_type || (Mime[formats.first] if formats) - self.response.charset = false + response.charset = false end true diff --git a/actionpack/lib/action_controller/metal/http_authentication.rb b/actionpack/lib/action_controller/metal/http_authentication.rb index 5bf0a99fe4..0575360068 100644 --- a/actionpack/lib/action_controller/metal/http_authentication.rb +++ b/actionpack/lib/action_controller/metal/http_authentication.rb @@ -28,7 +28,7 @@ module ActionController # class ApplicationController < ActionController::Base # before_action :set_account, :authenticate # - # protected + # private # def set_account # @account = Account.find_by(url_name: request.subdomains.first) # end @@ -363,7 +363,7 @@ module ActionController # class ApplicationController < ActionController::Base # before_action :set_account, :authenticate # - # protected + # private # def set_account # @account = Account.find_by(url_name: request.subdomains.first) # end diff --git a/actionpack/lib/action_controller/metal/instrumentation.rb b/actionpack/lib/action_controller/metal/instrumentation.rb index f83396ae55..924686218f 100644 --- a/actionpack/lib/action_controller/metal/instrumentation.rb +++ b/actionpack/lib/action_controller/metal/instrumentation.rb @@ -83,14 +83,14 @@ module ActionController # end # # :api: plugin - def cleanup_view_runtime #:nodoc: + def cleanup_view_runtime yield end # Every time after an action is processed, this method is invoked # with the payload, so you can add more information. # :api: plugin - def append_info_to_payload(payload) #:nodoc: + def append_info_to_payload(payload) payload[:view_runtime] = view_runtime end diff --git a/actionpack/lib/action_controller/metal/parameter_encoding.rb b/actionpack/lib/action_controller/metal/parameter_encoding.rb index c457fd0d06..962532ff09 100644 --- a/actionpack/lib/action_controller/metal/parameter_encoding.rb +++ b/actionpack/lib/action_controller/metal/parameter_encoding.rb @@ -1,5 +1,5 @@ module ActionController - # Allows encoding to be specified per parameter per action. + # Specify binary encoding for parameters for a given action. module ParameterEncoding extend ActiveSupport::Concern @@ -13,17 +13,36 @@ module ActionController @_parameter_encodings = {} end - def encoding_for_param(action, param) # :nodoc: - if @_parameter_encodings[action.to_s] && @_parameter_encodings[action.to_s][param.to_s] - @_parameter_encodings[action.to_s][param.to_s] - else - super - end + def binary_params_for?(action) # :nodoc: + @_parameter_encodings[action.to_s] end - def parameter_encoding(action, param_name, encoding) - @_parameter_encodings[action.to_s] ||= {} - @_parameter_encodings[action.to_s][param_name.to_s] = encoding + # Specify that a given action's parameters should all be encoded as + # ASCII-8BIT (it "skips" the encoding default of UTF-8). + # + # For example, a controller would use it like this: + # + # class RepositoryController < ActionController::Base + # skip_parameter_encoding :show + # + # def show + # @repo = Repository.find_by_filesystem_path params[:file_path] + # + # # `repo_name` is guaranteed to be UTF-8, but was ASCII-8BIT, so + # # tag it as such + # @repo_name = params[:repo_name].force_encoding 'UTF-8' + # end + # + # def index + # @repositories = Repository.all + # end + # end + # + # The show action in the above controller would have all parameter values + # encoded as ASCII-8BIT. This is useful in the case where an application + # must handle data but encoding of the data is unknown, like file system data. + def skip_parameter_encoding(action) + @_parameter_encodings[action.to_s] = true end end end diff --git a/actionpack/lib/action_controller/metal/params_wrapper.rb b/actionpack/lib/action_controller/metal/params_wrapper.rb index 86e817fe16..7fc898f034 100644 --- a/actionpack/lib/action_controller/metal/params_wrapper.rb +++ b/actionpack/lib/action_controller/metal/params_wrapper.rb @@ -135,7 +135,7 @@ module ActionController # # This method also does namespace lookup. Foo::Bar::UsersController will # try to find Foo::Bar::User, Foo::User and finally User. - def _default_wrap_model #:nodoc: + def _default_wrap_model return nil if klass.anonymous? model_name = klass.name.sub(/Controller$/, "").classify diff --git a/actionpack/lib/action_controller/metal/redirecting.rb b/actionpack/lib/action_controller/metal/redirecting.rb index 30798c1d99..4dfcf4da28 100644 --- a/actionpack/lib/action_controller/metal/redirecting.rb +++ b/actionpack/lib/action_controller/metal/redirecting.rb @@ -50,7 +50,7 @@ module ActionController # redirect_to post_url(@post), status: 301, flash: { updated_post_id: @post.id } # redirect_to({ action: 'atom' }, alert: "Something serious happened") # - def redirect_to(options = {}, response_status = {}) #:doc: + def redirect_to(options = {}, response_status = {}) raise ActionControllerError.new("Cannot redirect to nil!") unless options raise AbstractController::DoubleRenderError if response_body diff --git a/actionpack/lib/action_controller/metal/renderers.rb b/actionpack/lib/action_controller/metal/renderers.rb index f8a037189c..733aca195d 100644 --- a/actionpack/lib/action_controller/metal/renderers.rb +++ b/actionpack/lib/action_controller/metal/renderers.rb @@ -104,7 +104,7 @@ module ActionController # # Since <tt>ActionController::Metal</tt> controllers cannot render, the controller # must include <tt>AbstractController::Rendering</tt>, <tt>ActionController::Rendering</tt>, - # and <tt>ActionController::Renderers</tt>, and have at lest one renderer. + # and <tt>ActionController::Renderers</tt>, and have at least one renderer. # # Rather than including <tt>ActionController::Renderers::All</tt> and including all renderers, # you may specify which renderers to include by passing the renderer name or names to diff --git a/actionpack/lib/action_controller/metal/rendering.rb b/actionpack/lib/action_controller/metal/rendering.rb index 56cfb4fbba..6b17719381 100644 --- a/actionpack/lib/action_controller/metal/rendering.rb +++ b/actionpack/lib/action_controller/metal/rendering.rb @@ -54,6 +54,12 @@ module ActionController private + def _process_variant(options) + if defined?(request) && !request.nil? && request.variant.present? + options[:variant] = request.variant + end + end + def _render_in_priorities(options) RENDER_FORMATS_IN_PRIORITY.each do |format| return options[format] if options.key?(format) @@ -73,14 +79,14 @@ module ActionController end # Normalize arguments by catching blocks and setting them on :update. - def _normalize_args(action = nil, options = {}, &blk) #:nodoc: + def _normalize_args(action = nil, options = {}, &blk) options = super options[:update] = blk if block_given? options end # Normalize both text and status options. - def _normalize_options(options) #:nodoc: + def _normalize_options(options) _normalize_text(options) if options[:html] @@ -103,12 +109,12 @@ module ActionController end # Process controller specific options, as status, content-type and location. - def _process_options(options) #:nodoc: + def _process_options(options) status, content_type, location = options.values_at(:status, :content_type, :location) self.status = status if status self.content_type = content_type if content_type - self.headers["Location"] = url_for(location) if location + headers["Location"] = url_for(location) if location super end diff --git a/actionpack/lib/action_controller/metal/request_forgery_protection.rb b/actionpack/lib/action_controller/metal/request_forgery_protection.rb index 3d3c121280..e8965a6561 100644 --- a/actionpack/lib/action_controller/metal/request_forgery_protection.rb +++ b/actionpack/lib/action_controller/metal/request_forgery_protection.rb @@ -152,7 +152,7 @@ module ActionController #:nodoc: request.cookie_jar = NullCookieJar.build(request, {}) end - protected + private class NullSessionHash < Rack::Session::Abstract::SessionHash #:nodoc: def initialize(req) @@ -197,7 +197,7 @@ module ActionController #:nodoc: end end - protected + private # The actual before_action that is used to verify the CSRF token. # Don't override this directly. Provide your own forgery protection # strategy instead. If you override, you'll disable same-origin @@ -208,7 +208,7 @@ module ActionController #:nodoc: # enabled on an action, this before_action flags its after_action to # verify that JavaScript responses are for XHR requests, ensuring they # follow the browser's same-origin policy. - def verify_authenticity_token + def verify_authenticity_token # :doc: mark_for_same_origin_verification! if !verified_request? @@ -219,7 +219,7 @@ module ActionController #:nodoc: end end - def handle_unverified_request + def handle_unverified_request # :doc: forgery_protection_strategy.new(self).handle_unverified_request end @@ -233,7 +233,7 @@ module ActionController #:nodoc: # If `verify_authenticity_token` was run (indicating that we have # forgery protection enabled for this request) then also verify that # we aren't serving an unauthorized cross-origin response. - def verify_same_origin_request + def verify_same_origin_request # :doc: if marked_for_same_origin_verification? && non_xhr_javascript_response? if logger && log_warning_on_csrf_failure logger.warn CROSS_ORIGIN_JAVASCRIPT_WARNING @@ -243,18 +243,18 @@ module ActionController #:nodoc: end # GET requests are checked for cross-origin JavaScript after rendering. - def mark_for_same_origin_verification! + def mark_for_same_origin_verification! # :doc: @marked_for_same_origin_verification = request.get? end # If the `verify_authenticity_token` before_action ran, verify that # JavaScript responses are only served to same-origin GET requests. - def marked_for_same_origin_verification? + def marked_for_same_origin_verification? # :doc: @marked_for_same_origin_verification ||= false end # Check for cross-origin JavaScript responses. - def non_xhr_javascript_response? + def non_xhr_javascript_response? # :doc: content_type =~ %r(\Atext/javascript) && !request.xhr? end @@ -265,20 +265,20 @@ module ActionController #:nodoc: # * Is it a GET or HEAD request? Gets should be safe and idempotent # * Does the form_authenticity_token match the given token value from the params? # * Does the X-CSRF-Token header match the form_authenticity_token - def verified_request? + def verified_request? # :doc: !protect_against_forgery? || request.get? || request.head? || (valid_request_origin? && any_authenticity_token_valid?) end # Checks if any of the authenticity tokens from the request are valid. - def any_authenticity_token_valid? + def any_authenticity_token_valid? # :doc: request_authenticity_tokens.any? do |token| valid_authenticity_token?(session, token) end end # Possible authenticity tokens sent in the request. - def request_authenticity_tokens + def request_authenticity_tokens # :doc: [form_authenticity_param, request.x_csrf_token] end @@ -290,7 +290,7 @@ module ActionController #:nodoc: # Creates a masked version of the authenticity token that varies # on each request. The masking is used to mitigate SSL attacks # like BREACH. - def masked_authenticity_token(session, form_options: {}) + def masked_authenticity_token(session, form_options: {}) # :doc: action, method = form_options.values_at(:action, :method) raw_token = if per_form_csrf_tokens && action && method @@ -309,7 +309,7 @@ module ActionController #:nodoc: # Checks the client's masked token to see if it matches the # session token. Essentially the inverse of # +masked_authenticity_token+. - def valid_authenticity_token?(session, encoded_masked_token) + def valid_authenticity_token?(session, encoded_masked_token) # :doc: if encoded_masked_token.nil? || encoded_masked_token.empty? || !encoded_masked_token.is_a?(String) return false end @@ -340,7 +340,7 @@ module ActionController #:nodoc: end end - def unmask_token(masked_token) + def unmask_token(masked_token) # :doc: # Split the token into the one-time pad and the encrypted # value and decrypt it one_time_pad = masked_token[0...AUTHENTICITY_TOKEN_LENGTH] @@ -348,11 +348,11 @@ module ActionController #:nodoc: xor_byte_strings(one_time_pad, encrypted_csrf_token) end - def compare_with_real_token(token, session) + def compare_with_real_token(token, session) # :doc: ActiveSupport::SecurityUtils.secure_compare(token, real_csrf_token(session)) end - def valid_per_form_csrf_token?(token, session) + def valid_per_form_csrf_token?(token, session) # :doc: if per_form_csrf_tokens correct_token = per_form_csrf_token( session, @@ -366,12 +366,12 @@ module ActionController #:nodoc: end end - def real_csrf_token(session) + def real_csrf_token(session) # :doc: session[:_csrf_token] ||= SecureRandom.base64(AUTHENTICITY_TOKEN_LENGTH) Base64.strict_decode64(session[:_csrf_token]) end - def per_form_csrf_token(session, action_path, method) + def per_form_csrf_token(session, action_path, method) # :doc: OpenSSL::HMAC.digest( OpenSSL::Digest::SHA256.new, real_csrf_token(session), @@ -379,25 +379,25 @@ module ActionController #:nodoc: ) end - def xor_byte_strings(s1, s2) + def xor_byte_strings(s1, s2) # :doc: s2_bytes = s2.bytes s1.each_byte.with_index { |c1, i| s2_bytes[i] ^= c1 } s2_bytes.pack("C*") end # The form's authenticity parameter. Override to provide your own. - def form_authenticity_param + def form_authenticity_param # :doc: params[request_forgery_protection_token] end # Checks if the controller allows forgery protection. - def protect_against_forgery? + def protect_against_forgery? # :doc: allow_forgery_protection end # Checks if the request originated from the same origin by looking at the # Origin header. - def valid_request_origin? + def valid_request_origin? # :doc: if forgery_protection_origin_check # We accept blank origin headers because some user agents don't send it. request.origin.nil? || request.origin == request.base_url @@ -406,7 +406,7 @@ module ActionController #:nodoc: end end - def normalize_action_path(action_path) + def normalize_action_path(action_path) # :doc: uri = URI.parse(action_path) uri.path.chomp("/") end diff --git a/actionpack/lib/action_controller/metal/streaming.rb b/actionpack/lib/action_controller/metal/streaming.rb index 481f19f1ef..877a08b222 100644 --- a/actionpack/lib/action_controller/metal/streaming.rb +++ b/actionpack/lib/action_controller/metal/streaming.rb @@ -193,10 +193,10 @@ module ActionController #:nodoc: module Streaming extend ActiveSupport::Concern - protected + private # Set proper cache control and transfer encoding when streaming - def _process_options(options) #:nodoc: + def _process_options(options) super if options[:stream] if request.version == "HTTP/1.0" @@ -210,7 +210,7 @@ module ActionController #:nodoc: end # Call render_body if we are streaming instead of usual +render+. - def _render_template(options) #:nodoc: + def _render_template(options) if options.delete(:stream) Rack::Chunked::Body.new view_renderer.render_body(view_context, options) else diff --git a/actionpack/lib/action_controller/metal/strong_parameters.rb b/actionpack/lib/action_controller/metal/strong_parameters.rb index acfeca1fcb..6e8df02fb9 100644 --- a/actionpack/lib/action_controller/metal/strong_parameters.rb +++ b/actionpack/lib/action_controller/metal/strong_parameters.rb @@ -150,7 +150,7 @@ module ActionController # permitted flag. def ==(other) if other.respond_to?(:permitted?) - self.permitted? == other.permitted? && self.parameters == other.parameters + permitted? == other.permitted? && parameters == other.parameters else @parameters == other end diff --git a/actionpack/lib/action_controller/test_case.rb b/actionpack/lib/action_controller/test_case.rb index c639178776..57dd605b51 100644 --- a/actionpack/lib/action_controller/test_case.rb +++ b/actionpack/lib/action_controller/test_case.rb @@ -354,7 +354,7 @@ module ActionController end def controller_class - if current_controller_class = self._controller_class + if current_controller_class = _controller_class current_controller_class else self.controller_class = determine_default_controller_class(name) @@ -389,9 +389,7 @@ module ActionController # Note that the request method is not verified. The different methods are # available to make the tests more expressive. def get(action, **args) - res = process(action, method: "GET", **args) - cookies.update res.cookies - res + process(action, method: "GET", **args) end # Simulate a POST request with the given parameters and set/volley the response. @@ -515,12 +513,11 @@ module ActionController @request = @controller.request @response = @controller.response - @request.delete_header "HTTP_COOKIE" - if @request.have_cookie_jar? unless @request.cookie_jar.committed? @request.cookie_jar.write(@response) cookies.update(@request.cookie_jar.instance_variable_get(:@cookies)) + cookies.update(@response.cookies) end end @response.prepare! diff --git a/actionpack/lib/action_dispatch.rb b/actionpack/lib/action_dispatch.rb index 7931e53c3e..028177ace2 100644 --- a/actionpack/lib/action_dispatch.rb +++ b/actionpack/lib/action_dispatch.rb @@ -1,5 +1,5 @@ #-- -# Copyright (c) 2004-2016 David Heinemeier Hansson +# Copyright (c) 2004-2017 David Heinemeier Hansson # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/actionpack/lib/action_dispatch/http/filter_parameters.rb b/actionpack/lib/action_dispatch/http/filter_parameters.rb index e5874a39f6..e584b84d92 100644 --- a/actionpack/lib/action_dispatch/http/filter_parameters.rb +++ b/actionpack/lib/action_dispatch/http/filter_parameters.rb @@ -51,28 +51,28 @@ module ActionDispatch @filtered_path ||= query_string.empty? ? path : "#{path}?#{filtered_query_string}" end - protected + private - def parameter_filter + def parameter_filter # :doc: parameter_filter_for fetch_header("action_dispatch.parameter_filter") { return NULL_PARAM_FILTER } end - def env_filter + def env_filter # :doc: user_key = fetch_header("action_dispatch.parameter_filter") { return NULL_ENV_FILTER } parameter_filter_for(Array(user_key) + ENV_MATCH) end - def parameter_filter_for(filters) + def parameter_filter_for(filters) # :doc: ParameterFilter.new(filters) end KV_RE = "[^&;=]+" PAIR_RE = %r{(#{KV_RE})=(#{KV_RE})} - def filtered_query_string + def filtered_query_string # :doc: query_string.gsub(PAIR_RE) do |_| parameter_filter.filter([[$1, $2]]).first.join("=") end diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb index e5f20003a3..c4fe3a5c09 100644 --- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb +++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb @@ -150,20 +150,20 @@ module ActionDispatch order.include?(Mime::ALL) ? format : nil end - protected + private BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/ - def valid_accept_header + def valid_accept_header # :doc: (xhr? && (accept.present? || content_mime_type)) || (accept.present? && accept !~ BROWSER_LIKE_ACCEPTS) end - def use_accept_header + def use_accept_header # :doc: !self.class.ignore_accept_header end - def format_from_path_extension + def format_from_path_extension # :doc: path = get_header("action_dispatch.original_path") || get_header("PATH_INFO") if match = path && path.match(/\.(\w+)\z/) Mime[match.captures.first] diff --git a/actionpack/lib/action_dispatch/http/mime_type.rb b/actionpack/lib/action_dispatch/http/mime_type.rb index 58eb8d0baf..6b718e3682 100644 --- a/actionpack/lib/action_dispatch/http/mime_type.rb +++ b/actionpack/lib/action_dispatch/http/mime_type.rb @@ -278,6 +278,8 @@ module Mime def all?; false; end + # TODO Change this to private once we've dropped Ruby 2.2 support. + # Workaround for Ruby 2.2 "private attribute?" warning. protected attr_reader :string, :synonyms @@ -295,7 +297,7 @@ module Mime end end - def respond_to_missing?(method, include_private = false) #:nodoc: + def respond_to_missing?(method, include_private = false) method.to_s.ends_with? "?" end end diff --git a/actionpack/lib/action_dispatch/http/parameters.rb b/actionpack/lib/action_dispatch/http/parameters.rb index ddd15b748b..8f21eca440 100644 --- a/actionpack/lib/action_dispatch/http/parameters.rb +++ b/actionpack/lib/action_dispatch/http/parameters.rb @@ -22,6 +22,7 @@ module ActionDispatch included do class << self + # Returns the parameter parsers. attr_reader :parameter_parsers end @@ -29,7 +30,16 @@ module ActionDispatch end module ClassMethods - def parameter_parsers=(parsers) # :nodoc: + # Configure the parameter parser for a given mime type. + # + # It accepts a hash where the key is the symbol of the mime type + # and the value is a proc. + # + # original_parsers = ActionDispatch::Request.parameter_parsers + # xml_parser = -> (raw_post) { Hash.from_xml(raw_post) || {} } + # new_parsers = original_parsers.merge(xml: xml_parser) + # ActionDispatch::Request.parameter_parsers = new_parsers + def parameter_parsers=(parsers) @parameter_parsers = parsers.transform_keys { |key| key.respond_to?(:symbol) ? key.symbol : key } end end @@ -45,7 +55,7 @@ module ActionDispatch query_parameters.dup end params.merge!(path_parameters) - params = set_custom_encoding(params) + params = set_binary_encoding(params) set_header("action_dispatch.request.parameters", params) params end @@ -73,21 +83,16 @@ module ActionDispatch private - def set_custom_encoding(params) + def set_binary_encoding(params) action = params[:action] - params.each do |k, v| - if v.is_a?(String) && v.encoding != encoding_template(action, k) - params[k] = v.force_encoding(encoding_template(action, k)) + if controller_class.binary_params_for?(action) + ActionDispatch::Request::Utils.each_param_value(params) do |param| + param.force_encoding ::Encoding::ASCII_8BIT end end - params end - def encoding_template(action, param) - controller_class.encoding_for_param(action, param) - end - def parse_formatted_parameters(parsers) return yield if content_length.zero? || content_mime_type.nil? diff --git a/actionpack/lib/action_dispatch/http/request.rb b/actionpack/lib/action_dispatch/http/request.rb index 9986d6e1e9..19fa42ce12 100644 --- a/actionpack/lib/action_dispatch/http/request.rb +++ b/actionpack/lib/action_dispatch/http/request.rb @@ -69,7 +69,7 @@ module ActionDispatch PASS_NOT_FOUND = Class.new { # :nodoc: def self.action(_); self; end def self.call(_); [404, { "X-Cascade" => "pass" }, []]; end - def self.encoding_for_param(action, param); ::Encoding::UTF_8; end + def self.binary_params_for?(action); false; end } def controller_class @@ -85,6 +85,9 @@ module ActionDispatch end end + # Returns true if the request has a header matching the given key parameter. + # + # request.key? :ip_spoofing_check # => true def key?(key) has_header? key end diff --git a/actionpack/lib/action_dispatch/http/response.rb b/actionpack/lib/action_dispatch/http/response.rb index f71c6afd6c..dc159596c4 100644 --- a/actionpack/lib/action_dispatch/http/response.rb +++ b/actionpack/lib/action_dispatch/http/response.rb @@ -227,7 +227,9 @@ module ActionDispatch # :nodoc: return unless content_type new_header_info = parse_content_type(content_type.to_s) prev_header_info = parsed_content_type_header - set_content_type new_header_info.mime_type, new_header_info.charset || prev_header_info.charset || self.class.default_charset + charset = new_header_info.charset || prev_header_info.charset + charset ||= self.class.default_charset unless prev_header_info.mime_type + set_content_type new_header_info.mime_type, charset end # Sets the HTTP response's content MIME type. For example, in the controller @@ -423,7 +425,7 @@ module ActionDispatch # :nodoc: def set_content_type(content_type, charset) type = (content_type || "").dup - type << "; charset=#{charset}" if charset + type << "; charset=#{charset.to_s.downcase}" if charset set_header CONTENT_TYPE, type end diff --git a/actionpack/lib/action_dispatch/journey/formatter.rb b/actionpack/lib/action_dispatch/journey/formatter.rb index 20ff4441a0..f3b8e82d32 100644 --- a/actionpack/lib/action_dispatch/journey/formatter.rb +++ b/actionpack/lib/action_dispatch/journey/formatter.rb @@ -36,7 +36,7 @@ module ActionDispatch route.parts.reverse_each do |key| break if defaults[key].nil? && parameterized_parts[key].present? - break if parameterized_parts[key].to_s != defaults[key].to_s + next if parameterized_parts[key].to_s != defaults[key].to_s break if required_parts.include?(key) parameterized_parts.delete(key) @@ -92,7 +92,11 @@ module ActionDispatch else routes = non_recursive(cache, options) - hash = routes.group_by { |_, r| r.score(options) } + supplied_keys = options.each_with_object({}) do |(k, v), h| + h[k.to_s] = true if v + end + + hash = routes.group_by { |_, r| r.score(supplied_keys) } hash.keys.sort.reverse_each do |score| break if score < 0 diff --git a/actionpack/lib/action_dispatch/journey/parser.rb b/actionpack/lib/action_dispatch/journey/parser.rb index ee91b11b42..db42b64c4b 100644 --- a/actionpack/lib/action_dispatch/journey/parser.rb +++ b/actionpack/lib/action_dispatch/journey/parser.rb @@ -1,198 +1,199 @@ # # DO NOT MODIFY!!!! -# This file is automatically generated by Racc 1.4.11 +# This file is automatically generated by Racc 1.4.14 # from Racc grammer file "". # -require "racc/parser.rb" +require 'racc/parser.rb' + +# :stopdoc: require "action_dispatch/journey/parser_extras" module ActionDispatch - # :stopdoc: module Journey class Parser < Racc::Parser - ##### State transition tables begin ### - - racc_action_table = [ - 13, 15, 14, 7, 21, 16, 8, 19, 13, 15, - 14, 7, 17, 16, 8, 13, 15, 14, 7, 24, - 16, 8, 13, 15, 14, 7, 19, 16, 8 ] - - racc_action_check = [ - 2, 2, 2, 2, 17, 2, 2, 2, 0, 0, - 0, 0, 1, 0, 0, 19, 19, 19, 19, 20, - 19, 19, 7, 7, 7, 7, 22, 7, 7 ] - - racc_action_pointer = [ - 6, 12, -2, nil, nil, nil, nil, 20, nil, nil, - nil, nil, nil, nil, nil, nil, nil, 4, nil, 13, - 13, nil, 17, nil, nil ] - - racc_action_default = [ - -19, -19, -2, -3, -4, -5, -6, -19, -10, -11, - -12, -13, -14, -15, -16, -17, -18, -19, -1, -19, - -19, 25, -8, -9, -7 ] - - racc_goto_table = [ - 1, 22, 18, 23, nil, nil, nil, 20 ] - - racc_goto_check = [ - 1, 2, 1, 3, nil, nil, nil, 1 ] - - racc_goto_pointer = [ - nil, 0, -18, -16, nil, nil, nil, nil, nil, nil, - nil ] - - racc_goto_default = [ - nil, nil, 2, 3, 4, 5, 6, 9, 10, 11, - 12 ] - - racc_reduce_table = [ - 0, 0, :racc_error, - 2, 11, :_reduce_1, - 1, 11, :_reduce_2, - 1, 11, :_reduce_none, - 1, 12, :_reduce_none, - 1, 12, :_reduce_none, - 1, 12, :_reduce_none, - 3, 15, :_reduce_7, - 3, 13, :_reduce_8, - 3, 13, :_reduce_9, - 1, 16, :_reduce_10, - 1, 14, :_reduce_none, - 1, 14, :_reduce_none, - 1, 14, :_reduce_none, - 1, 14, :_reduce_none, - 1, 19, :_reduce_15, - 1, 17, :_reduce_16, - 1, 18, :_reduce_17, - 1, 20, :_reduce_18 ] - - racc_reduce_n = 19 - - racc_shift_n = 25 - - racc_token_table = { - false => 0, - :error => 1, - :SLASH => 2, - :LITERAL => 3, - :SYMBOL => 4, - :LPAREN => 5, - :RPAREN => 6, - :DOT => 7, - :STAR => 8, - :OR => 9 } - - racc_nt_base = 10 - - racc_use_result_var = false - - Racc_arg = [ - racc_action_table, - racc_action_check, - racc_action_default, - racc_action_pointer, - racc_goto_table, - racc_goto_check, - racc_goto_default, - racc_goto_pointer, - racc_nt_base, - racc_reduce_table, - racc_token_table, - racc_shift_n, - racc_reduce_n, - racc_use_result_var ] - - Racc_token_to_s_table = [ - "$end", - "error", - "SLASH", - "LITERAL", - "SYMBOL", - "LPAREN", - "RPAREN", - "DOT", - "STAR", - "OR", - "$start", - "expressions", - "expression", - "or", - "terminal", - "group", - "star", - "symbol", - "literal", - "slash", - "dot" ] - - Racc_debug_parser = false - - ##### State transition tables end ##### - - # reduce 0 omitted - - def _reduce_1(val, _values) - Cat.new(val.first, val.last) - end - - def _reduce_2(val, _values) - val.first - end - - # reduce 3 omitted - - # reduce 4 omitted - - # reduce 5 omitted - - # reduce 6 omitted - - def _reduce_7(val, _values) - Group.new(val[1]) - end - - def _reduce_8(val, _values) - Or.new([val.first, val.last]) - end - - def _reduce_9(val, _values) - Or.new([val.first, val.last]) - end - - def _reduce_10(val, _values) - Star.new(Symbol.new(val.last)) - end - - # reduce 11 omitted - - # reduce 12 omitted - - # reduce 13 omitted - - # reduce 14 omitted - - def _reduce_15(val, _values) - Slash.new("/") - end - - def _reduce_16(val, _values) - Symbol.new(val.first) - end - - def _reduce_17(val, _values) - Literal.new(val.first) - end - - def _reduce_18(val, _values) - Dot.new(val.first) - end - - def _reduce_none(val, _values) - val[0] - end +##### State transition tables begin ### + +racc_action_table = [ + 13, 15, 14, 7, 19, 16, 8, 19, 13, 15, + 14, 7, 17, 16, 8, 13, 15, 14, 7, 21, + 16, 8, 13, 15, 14, 7, 24, 16, 8 ] + +racc_action_check = [ + 2, 2, 2, 2, 22, 2, 2, 2, 19, 19, + 19, 19, 1, 19, 19, 7, 7, 7, 7, 17, + 7, 7, 0, 0, 0, 0, 20, 0, 0 ] + +racc_action_pointer = [ + 20, 12, -2, nil, nil, nil, nil, 13, nil, nil, + nil, nil, nil, nil, nil, nil, nil, 19, nil, 6, + 20, nil, -5, nil, nil ] + +racc_action_default = [ + -19, -19, -2, -3, -4, -5, -6, -19, -10, -11, + -12, -13, -14, -15, -16, -17, -18, -19, -1, -19, + -19, 25, -8, -9, -7 ] + +racc_goto_table = [ + 1, 22, 18, 23, nil, nil, nil, 20 ] + +racc_goto_check = [ + 1, 2, 1, 3, nil, nil, nil, 1 ] + +racc_goto_pointer = [ + nil, 0, -18, -16, nil, nil, nil, nil, nil, nil, + nil ] + +racc_goto_default = [ + nil, nil, 2, 3, 4, 5, 6, 9, 10, 11, + 12 ] + +racc_reduce_table = [ + 0, 0, :racc_error, + 2, 11, :_reduce_1, + 1, 11, :_reduce_2, + 1, 11, :_reduce_none, + 1, 12, :_reduce_none, + 1, 12, :_reduce_none, + 1, 12, :_reduce_none, + 3, 15, :_reduce_7, + 3, 13, :_reduce_8, + 3, 13, :_reduce_9, + 1, 16, :_reduce_10, + 1, 14, :_reduce_none, + 1, 14, :_reduce_none, + 1, 14, :_reduce_none, + 1, 14, :_reduce_none, + 1, 19, :_reduce_15, + 1, 17, :_reduce_16, + 1, 18, :_reduce_17, + 1, 20, :_reduce_18 ] + +racc_reduce_n = 19 + +racc_shift_n = 25 + +racc_token_table = { + false => 0, + :error => 1, + :SLASH => 2, + :LITERAL => 3, + :SYMBOL => 4, + :LPAREN => 5, + :RPAREN => 6, + :DOT => 7, + :STAR => 8, + :OR => 9 } + +racc_nt_base = 10 + +racc_use_result_var = false + +Racc_arg = [ + racc_action_table, + racc_action_check, + racc_action_default, + racc_action_pointer, + racc_goto_table, + racc_goto_check, + racc_goto_default, + racc_goto_pointer, + racc_nt_base, + racc_reduce_table, + racc_token_table, + racc_shift_n, + racc_reduce_n, + racc_use_result_var ] + +Racc_token_to_s_table = [ + "$end", + "error", + "SLASH", + "LITERAL", + "SYMBOL", + "LPAREN", + "RPAREN", + "DOT", + "STAR", + "OR", + "$start", + "expressions", + "expression", + "or", + "terminal", + "group", + "star", + "symbol", + "literal", + "slash", + "dot" ] + +Racc_debug_parser = false + +##### State transition tables end ##### + +# reduce 0 omitted + +def _reduce_1(val, _values) + Cat.new(val.first, val.last) +end + +def _reduce_2(val, _values) + val.first +end + +# reduce 3 omitted + +# reduce 4 omitted + +# reduce 5 omitted + +# reduce 6 omitted + +def _reduce_7(val, _values) + Group.new(val[1]) +end + +def _reduce_8(val, _values) + Or.new([val.first, val.last]) +end + +def _reduce_9(val, _values) + Or.new([val.first, val.last]) +end + +def _reduce_10(val, _values) + Star.new(Symbol.new(val.last)) +end + +# reduce 11 omitted + +# reduce 12 omitted + +# reduce 13 omitted + +# reduce 14 omitted + +def _reduce_15(val, _values) + Slash.new(val.first) +end + +def _reduce_16(val, _values) + Symbol.new(val.first) +end + +def _reduce_17(val, _values) + Literal.new(val.first) +end + +def _reduce_18(val, _values) + Dot.new(val.first) +end + +def _reduce_none(val, _values) + val[0] +end + end # class Parser - end # module Journey - # :startdoc: -end # module ActionDispatch + end # module Journey + end # module ActionDispatch diff --git a/actionpack/lib/action_dispatch/journey/parser.y b/actionpack/lib/action_dispatch/journey/parser.y index d3f7c4d765..f9b1a7a958 100644 --- a/actionpack/lib/action_dispatch/journey/parser.y +++ b/actionpack/lib/action_dispatch/journey/parser.y @@ -30,7 +30,7 @@ rule | dot ; slash - : SLASH { Slash.new('/') } + : SLASH { Slash.new(val.first) } ; symbol : SYMBOL { Symbol.new(val.first) } @@ -45,5 +45,6 @@ rule end ---- header +# :stopdoc: -require 'action_dispatch/journey/parser_extras' +require "action_dispatch/journey/parser_extras" diff --git a/actionpack/lib/action_dispatch/journey/route.rb b/actionpack/lib/action_dispatch/journey/route.rb index 0cc8d83ac8..f2ac4818d8 100644 --- a/actionpack/lib/action_dispatch/journey/route.rb +++ b/actionpack/lib/action_dispatch/journey/route.rb @@ -96,13 +96,18 @@ module ActionDispatch required_parts + required_defaults.keys end - def score(constraints) + def score(supplied_keys) required_keys = path.required_names - supplied_keys = constraints.map { |k, v| v && k.to_s }.compact - return -1 unless (required_keys - supplied_keys).empty? + required_keys.each do |k| + return -1 unless supplied_keys.include?(k) + end + + score = 0 + path.names.each do |k| + score += 1 if supplied_keys.include?(k) + end - score = (supplied_keys & path.names).length score + (required_defaults.length * 2) end diff --git a/actionpack/lib/action_dispatch/journey/router/utils.rb b/actionpack/lib/action_dispatch/journey/router/utils.rb index ce5d350763..d641642338 100644 --- a/actionpack/lib/action_dispatch/journey/router/utils.rb +++ b/actionpack/lib/action_dispatch/journey/router/utils.rb @@ -58,12 +58,12 @@ module ActionDispatch uri.gsub(ESCAPED) { |match| [match[1, 2].hex].pack("C") }.force_encoding(encoding) end - protected - def escape(component, pattern) + private + def escape(component, pattern) # :doc: component.gsub(pattern) { |unsafe| percent_encode(unsafe) }.force_encoding(US_ASCII) end - def percent_encode(unsafe) + def percent_encode(unsafe) # :doc: safe = EMPTY.dup unsafe.each_byte { |b| safe << DEC2HEX[b] } safe diff --git a/actionpack/lib/action_dispatch/journey/scanner.rb b/actionpack/lib/action_dispatch/journey/scanner.rb index 4b8c8ab063..7dbb39b26d 100644 --- a/actionpack/lib/action_dispatch/journey/scanner.rb +++ b/actionpack/lib/action_dispatch/journey/scanner.rb @@ -1,3 +1,4 @@ +# frozen_string_literal: true require "strscan" module ActionDispatch @@ -35,22 +36,23 @@ module ActionDispatch def scan case # / - when text = @ss.scan(/\//) - [:SLASH, text] + when @ss.skip(/\//) + [:SLASH, "/"] + when @ss.skip(/\(/) + [:LPAREN, "("] + when @ss.skip(/\)/) + [:RPAREN, ")"] + when @ss.skip(/\|/) + [:OR, "|"] + when @ss.skip(/\./) + [:DOT, "."] + when text = @ss.scan(/:\w+/) + [:SYMBOL, text] when text = @ss.scan(/\*\w+/) [:STAR, text] - when text = @ss.scan(/(?<!\\)\(/) - [:LPAREN, text] - when text = @ss.scan(/(?<!\\)\)/) - [:RPAREN, text] - when text = @ss.scan(/\|/) - [:OR, text] - when text = @ss.scan(/\./) - [:DOT, text] - when text = @ss.scan(/(?<!\\):\w+/) - [:SYMBOL, text] - when text = @ss.scan(/(?:[\w%\-~!$&'*+,;=@]|\\:|\\\(|\\\))+/) - [:LITERAL, text.tr('\\', "")] + when text = @ss.scan(/(?:[\w%\-~!$&'*+,;=@]|\\[:()])+/) + text.tr! "\\", "" + [:LITERAL, text] # any char when text = @ss.scan(/./) [:LITERAL, text] diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb index 6dddcc6ee1..cbe2f4be4d 100644 --- a/actionpack/lib/action_dispatch/middleware/flash.rb +++ b/actionpack/lib/action_dispatch/middleware/flash.rb @@ -281,7 +281,8 @@ module ActionDispatch @now end - def stringify_array(array) + private + def stringify_array(array) # :doc: array.map do |item| item.kind_of?(Symbol) ? item.to_s : item end diff --git a/actionpack/lib/action_dispatch/middleware/remote_ip.rb b/actionpack/lib/action_dispatch/middleware/remote_ip.rb index 523eeb5b05..9f1ae80b97 100644 --- a/actionpack/lib/action_dispatch/middleware/remote_ip.rb +++ b/actionpack/lib/action_dispatch/middleware/remote_ip.rb @@ -153,9 +153,9 @@ module ActionDispatch @ip ||= calculate_ip end - protected + private - def ips_from(header) + def ips_from(header) # :doc: return [] unless header # Split the comma-separated list into an array of strings ips = header.strip.split(/[,\s]+/) @@ -171,7 +171,7 @@ module ActionDispatch end end - def filter_proxies(ips) + def filter_proxies(ips) # :doc: ips.reject do |ip| @proxies.any? { |proxy| proxy === ip } end diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb index 49b82e7128..97c937b0b1 100644 --- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb @@ -27,17 +27,16 @@ module ActionDispatch sid end - protected + private - def initialize_sid + def initialize_sid # :doc: @default_options.delete(:sidbits) @default_options.delete(:secure_random) end - private - def make_request(env) - ActionDispatch::Request.new env - end + def make_request(env) + ActionDispatch::Request.new env + end end module StaleSessionCheck diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index 5c71f0fc48..5d10129d21 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -33,7 +33,7 @@ module ActionDispatch paths = [path, "#{path}#{ext}", "#{path}/#{@index}#{ext}"] if match = paths.detect { |p| - path = File.join(@root, p.force_encoding("UTF-8".freeze)) + path = File.join(@root, p.force_encoding(Encoding::UTF_8)) begin File.file?(path) && File.readable?(path) rescue SystemCallError diff --git a/actionpack/lib/action_dispatch/request/utils.rb b/actionpack/lib/action_dispatch/request/utils.rb index 282bdbd2be..01bc871e5f 100644 --- a/actionpack/lib/action_dispatch/request/utils.rb +++ b/actionpack/lib/action_dispatch/request/utils.rb @@ -4,6 +4,17 @@ module ActionDispatch mattr_accessor :perform_deep_munge self.perform_deep_munge = true + def self.each_param_value(params, &block) + case params + when Array + params.each { |element| each_param_value(element, &block) } + when Hash + params.each_value { |value| each_param_value(value, &block) } + when String + block.call params + end + end + def self.normalize_encode_params(params) if perform_deep_munge NoNilParamEncoder.normalize_encode_params params diff --git a/actionpack/lib/action_dispatch/routing.rb b/actionpack/lib/action_dispatch/routing.rb index fe8bf6a35c..c554ce98bc 100644 --- a/actionpack/lib/action_dispatch/routing.rb +++ b/actionpack/lib/action_dispatch/routing.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/string/filters' +require "active_support/core_ext/string/filters" module ActionDispatch # The routing module provides URL rewriting in native Ruby. It's a way to diff --git a/actionpack/lib/action_dispatch/routing/mapper.rb b/actionpack/lib/action_dispatch/routing/mapper.rb index 4efde09b8b..83652bd34c 100644 --- a/actionpack/lib/action_dispatch/routing/mapper.rb +++ b/actionpack/lib/action_dispatch/routing/mapper.rb @@ -238,7 +238,7 @@ module ActionDispatch options[:controller] ||= /.+?/ end - if to.respond_to? :call + if to.respond_to?(:action) || to.respond_to?(:call) options else to_endpoint = split_to to @@ -290,16 +290,14 @@ module ActionDispatch end def app(blocks) - if to.is_a?(Class) && to < ActionController::Metal + if to.respond_to?(:action) Routing::RouteSet::StaticDispatcher.new to + elsif to.respond_to?(:call) + Constraints.new(to, blocks, Constraints::CALL) + elsif blocks.any? + Constraints.new(dispatcher(defaults.key?(:controller)), blocks, Constraints::SERVE) else - if to.respond_to?(:call) - Constraints.new(to, blocks, Constraints::CALL) - elsif blocks.any? - Constraints.new(dispatcher(defaults.key?(:controller)), blocks, Constraints::SERVE) - else - dispatcher(defaults.key?(:controller)) - end + dispatcher(defaults.key?(:controller)) end end @@ -996,65 +994,65 @@ module ActionDispatch end private - def merge_path_scope(parent, child) #:nodoc: + def merge_path_scope(parent, child) Mapper.normalize_path("#{parent}/#{child}") end - def merge_shallow_path_scope(parent, child) #:nodoc: + def merge_shallow_path_scope(parent, child) Mapper.normalize_path("#{parent}/#{child}") end - def merge_as_scope(parent, child) #:nodoc: + def merge_as_scope(parent, child) parent ? "#{parent}_#{child}" : child end - def merge_shallow_prefix_scope(parent, child) #:nodoc: + def merge_shallow_prefix_scope(parent, child) parent ? "#{parent}_#{child}" : child end - def merge_module_scope(parent, child) #:nodoc: + def merge_module_scope(parent, child) parent ? "#{parent}/#{child}" : child end - def merge_controller_scope(parent, child) #:nodoc: + def merge_controller_scope(parent, child) child end - def merge_action_scope(parent, child) #:nodoc: + def merge_action_scope(parent, child) child end - def merge_via_scope(parent, child) #:nodoc: + def merge_via_scope(parent, child) child end - def merge_format_scope(parent, child) #:nodoc: + def merge_format_scope(parent, child) child end - def merge_path_names_scope(parent, child) #:nodoc: + def merge_path_names_scope(parent, child) merge_options_scope(parent, child) end - def merge_constraints_scope(parent, child) #:nodoc: + def merge_constraints_scope(parent, child) merge_options_scope(parent, child) end - def merge_defaults_scope(parent, child) #:nodoc: + def merge_defaults_scope(parent, child) merge_options_scope(parent, child) end - def merge_blocks_scope(parent, child) #:nodoc: + def merge_blocks_scope(parent, child) merged = parent ? parent.dup : [] merged << child if child merged end - def merge_options_scope(parent, child) #:nodoc: + def merge_options_scope(parent, child) (parent || {}).merge(child) end - def merge_shallow_scope(parent, child) #:nodoc: + def merge_shallow_scope(parent, child) child ? true : false end @@ -1619,13 +1617,13 @@ module ActionDispatch end end - protected + private - def parent_resource #:nodoc: + def parent_resource @scope[:scope_level_resource] end - def apply_common_behavior_for(method, resources, options, &block) #:nodoc: + def apply_common_behavior_for(method, resources, options, &block) if resources.length > 1 resources.each { |r| send(method, r, options, &block) } return true @@ -1658,39 +1656,39 @@ module ActionDispatch false end - def apply_action_options(options) # :nodoc: + def apply_action_options(options) return options if action_options? options options.merge scope_action_options end - def action_options?(options) #:nodoc: + def action_options?(options) options[:only] || options[:except] end - def scope_action_options #:nodoc: + def scope_action_options @scope[:action_options] || {} end - def resource_scope? #:nodoc: + def resource_scope? @scope.resource_scope? end - def resource_method_scope? #:nodoc: + def resource_method_scope? @scope.resource_method_scope? end - def nested_scope? #:nodoc: + def nested_scope? @scope.nested? end - def with_scope_level(kind) + def with_scope_level(kind) # :doc: @scope = @scope.new_level(kind) yield ensure @scope = @scope.parent end - def resource_scope(resource) #:nodoc: + def resource_scope(resource) @scope = @scope.new(scope_level_resource: resource) controller(resource.resource_scope) { yield } @@ -1698,7 +1696,7 @@ module ActionDispatch @scope = @scope.parent end - def nested_options #:nodoc: + def nested_options options = { as: parent_resource.member_name } options[:constraints] = { parent_resource.nested_param => param_constraint @@ -1707,25 +1705,25 @@ module ActionDispatch options end - def shallow_nesting_depth #:nodoc: + def shallow_nesting_depth @scope.find_all { |node| node.frame[:scope_level_resource] }.count { |node| node.frame[:scope_level_resource].shallow? } end - def param_constraint? #:nodoc: + def param_constraint? @scope[:constraints] && @scope[:constraints][parent_resource.param].is_a?(Regexp) end - def param_constraint #:nodoc: + def param_constraint @scope[:constraints][parent_resource.param] end - def canonical_action?(action) #:nodoc: + def canonical_action?(action) resource_method_scope? && CANONICAL_ACTIONS.include?(action.to_s) end - def shallow_scope #:nodoc: + def shallow_scope scope = { as: @scope[:shallow_prefix], path: @scope[:shallow_path] } @scope = @scope.new scope @@ -1735,7 +1733,7 @@ module ActionDispatch @scope = @scope.parent end - def path_for_action(action, path) #:nodoc: + def path_for_action(action, path) return "#{@scope[:path]}/#{path}" if path if canonical_action?(action) @@ -1745,11 +1743,11 @@ module ActionDispatch end end - def action_path(name) #:nodoc: + def action_path(name) @scope[:path_names][name.to_sym] || name end - def prefix_name_for_action(as, action) #:nodoc: + def prefix_name_for_action(as, action) if as prefix = as elsif !canonical_action?(action) @@ -1761,7 +1759,7 @@ module ActionDispatch end end - def name_for_action(as, action) #:nodoc: + def name_for_action(as, action) prefix = prefix_name_for_action(as, action) name_prefix = @scope[:as] @@ -1787,7 +1785,7 @@ module ActionDispatch end end - def set_member_mappings_for_resource + def set_member_mappings_for_resource # :doc: member do get :edit if parent_resource.actions.include?(:edit) get :show if parent_resource.actions.include?(:show) @@ -1799,12 +1797,10 @@ module ActionDispatch end end - def api_only? + def api_only? # :doc: @set.api_only? end - private - def path_scope(path) @scope = @scope.new(path: merge_path_scope(@scope[:path], path)) yield @@ -1868,7 +1864,7 @@ module ActionDispatch path =~ %r{^/?[-\w]+/[-\w/]+$} end - def decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) # :nodoc: + def decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) if on = options.delete(:on) send(on) { decomposed_match(path, controller, options, _path, to, via, formatted, anchor, options_constraints) } else @@ -1883,7 +1879,7 @@ module ActionDispatch end end - def add_route(action, controller, options, _path, to, via, formatted, anchor, options_constraints) # :nodoc: + def add_route(action, controller, options, _path, to, via, formatted, anchor, options_constraints) path = path_for_action(action, _path) raise ArgumentError, "path is required" if path.blank? diff --git a/actionpack/lib/action_dispatch/routing/url_for.rb b/actionpack/lib/action_dispatch/routing/url_for.rb index a1ac5a2b6c..3e564f13d8 100644 --- a/actionpack/lib/action_dispatch/routing/url_for.rb +++ b/actionpack/lib/action_dispatch/routing/url_for.rb @@ -198,14 +198,16 @@ module ActionDispatch _routes.optimize_routes_generation? && default_url_options.empty? end - def _with_routes(routes) + private + + def _with_routes(routes) # :doc: old_routes, @_routes = @_routes, routes yield ensure @_routes = old_routes end - def _routes_context + def _routes_context # :doc: self end end diff --git a/actionpack/lib/action_dispatch/testing/assertions.rb b/actionpack/lib/action_dispatch/testing/assertions.rb index b362931ef7..4ea18d671d 100644 --- a/actionpack/lib/action_dispatch/testing/assertions.rb +++ b/actionpack/lib/action_dispatch/testing/assertions.rb @@ -12,7 +12,7 @@ module ActionDispatch include Rails::Dom::Testing::Assertions def html_document - @html_document ||= if @response.content_type.to_s =~ /xml\z/ + @html_document ||= if @response.content_type.to_s.end_with?("xml") Nokogiri::XML::Document.parse(@response.body) else Nokogiri::HTML::Document.parse(@response.body) diff --git a/actionpack/lib/action_dispatch/testing/assertions/routing.rb b/actionpack/lib/action_dispatch/testing/assertions/routing.rb index 454dcb9307..37c1ca02b6 100644 --- a/actionpack/lib/action_dispatch/testing/assertions/routing.rb +++ b/actionpack/lib/action_dispatch/testing/assertions/routing.rb @@ -152,8 +152,11 @@ module ActionDispatch _routes = @routes @controller.singleton_class.include(_routes.url_helpers) - @controller.view_context_class = Class.new(@controller.view_context_class) do - include _routes.url_helpers + + if @controller.respond_to? :view_context_class + @controller.view_context_class = Class.new(@controller.view_context_class) do + include _routes.url_helpers + end end end yield @routes diff --git a/actionpack/lib/action_pack.rb b/actionpack/lib/action_pack.rb index ee6dabd133..eec622e085 100644 --- a/actionpack/lib/action_pack.rb +++ b/actionpack/lib/action_pack.rb @@ -1,5 +1,5 @@ #-- -# Copyright (c) 2004-2016 David Heinemeier Hansson +# Copyright (c) 2004-2017 David Heinemeier Hansson # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the diff --git a/actionpack/test/abstract_unit.rb b/actionpack/test/abstract_unit.rb index 11a9092527..7c113426a5 100644 --- a/actionpack/test/abstract_unit.rb +++ b/actionpack/test/abstract_unit.rb @@ -7,8 +7,8 @@ require "active_support/core_ext/kernel/reporting" # These are the normal settings that will be set up by Railties # TODO: Have these tests support other combinations of these values silence_warnings do - Encoding.default_internal = "UTF-8" - Encoding.default_external = "UTF-8" + Encoding.default_internal = Encoding::UTF_8 + Encoding.default_external = Encoding::UTF_8 end require "drb" @@ -259,9 +259,9 @@ module ActionDispatch host = uri_or_host.host unless path path ||= uri_or_host.path - params = { "PATH_INFO" => path, - "REQUEST_METHOD" => method, - "HTTP_HOST" => host } + params = { "PATH_INFO" => path, + "REQUEST_METHOD" => method, + "HTTP_HOST" => host } routes.call(params) end diff --git a/actionpack/test/controller/action_pack_assertions_test.rb b/actionpack/test/controller/action_pack_assertions_test.rb index b08f1f1707..9ab152fc5c 100644 --- a/actionpack/test/controller/action_pack_assertions_test.rb +++ b/actionpack/test/controller/action_pack_assertions_test.rb @@ -128,6 +128,16 @@ module Admin end end +class ApiOnlyController < ActionController::API + def nothing + head :ok + end + + def redirect_to_new_route + redirect_to new_route_url + end +end + class ActionPackAssertionsControllerTest < ActionController::TestCase def test_render_file_absolute_path get :render_file_absolute_path @@ -170,6 +180,20 @@ class ActionPackAssertionsControllerTest < ActionController::TestCase end end + def test_with_routing_works_with_api_only_controllers + @controller = ApiOnlyController.new + + with_routing do |set| + set.draw do + get "new_route", to: "api_only#nothing" + get "redirect_to_new_route", to: "api_only#redirect_to_new_route" + end + + process :redirect_to_new_route + assert_redirected_to "http://test.host/new_route" + end + end + def test_assert_redirect_to_named_route_failure with_routing do |set| set.draw do diff --git a/actionpack/test/controller/filters_test.rb b/actionpack/test/controller/filters_test.rb index e0fa1fbab8..f9701585a9 100644 --- a/actionpack/test/controller/filters_test.rb +++ b/actionpack/test/controller/filters_test.rb @@ -55,7 +55,7 @@ class FilterTest < ActionController::TestCase end end - protected + private (1..3).each do |i| define_method "try_#{i}" do instance_variable_set :@try, i @@ -296,7 +296,7 @@ class FilterTest < ActionController::TestCase render inline: "ran action" end - protected + private def find_user @ran_filter ||= [] @ran_filter << "find_user" @@ -428,7 +428,7 @@ class FilterTest < ActionController::TestCase render plain: "bar" end - protected + private def first @first = true end @@ -1040,7 +1040,7 @@ class YieldingAroundFiltersTest < ActionController::TestCase assert_equal 3, controller.instance_variable_get(:@try) end - protected + private def test_process(controller, action = "show") @controller = controller.is_a?(Class) ? controller.new : controller process(action) diff --git a/actionpack/test/controller/flash_hash_test.rb b/actionpack/test/controller/flash_hash_test.rb index 6b3abdd5be..45b598a594 100644 --- a/actionpack/test/controller/flash_hash_test.rb +++ b/actionpack/test/controller/flash_hash_test.rb @@ -63,10 +63,10 @@ module ActionDispatch assert_equal({ "flashes" => { "foo" => "bar" }, "discard" => [] }, @hash.to_session_value) @hash.discard("foo") - assert_equal(nil, @hash.to_session_value) + assert_nil(@hash.to_session_value) @hash.sweep - assert_equal(nil, @hash.to_session_value) + assert_nil(@hash.to_session_value) end def test_from_session_value @@ -75,7 +75,7 @@ module ActionDispatch session = Marshal.load(Base64.decode64(rails_3_2_cookie)) hash = Flash::FlashHash.from_session_value(session["flash"]) assert_equal({ "greeting" => "Hello" }, hash.to_hash) - assert_equal(nil, hash.to_session_value) + assert_nil(hash.to_session_value) end def test_from_session_value_on_json_serializer @@ -84,7 +84,7 @@ module ActionDispatch hash = Flash::FlashHash.from_session_value(session["flash"]) assert_equal({ "greeting" => "Hello" }, hash.to_hash) - assert_equal(nil, hash.to_session_value) + assert_nil(hash.to_session_value) assert_equal "Hello", hash[:greeting] assert_equal "Hello", hash["greeting"] end diff --git a/actionpack/test/controller/http_token_authentication_test.rb b/actionpack/test/controller/http_token_authentication_test.rb index 3842136682..09d2793c9a 100644 --- a/actionpack/test/controller/http_token_authentication_test.rb +++ b/actionpack/test/controller/http_token_authentication_test.rb @@ -166,8 +166,7 @@ class HttpTokenAuthenticationTest < ActionController::TestCase 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) + assert_nil actual end test "raw_params returns a tuple of two key value pair strings" do diff --git a/actionpack/test/controller/integration_test.rb b/actionpack/test/controller/integration_test.rb index d3aa81a0f7..cd1415b56c 100644 --- a/actionpack/test/controller/integration_test.rb +++ b/actionpack/test/controller/integration_test.rb @@ -269,8 +269,8 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest test "response cookies are added to the cookie jar for the next request" do with_test_route_set do - self.cookies["cookie_1"] = "sugar" - self.cookies["cookie_2"] = "oatmeal" + cookies["cookie_1"] = "sugar" + cookies["cookie_2"] = "oatmeal" get "/cookie_monster" assert_equal "cookie_1=; path=/\ncookie_3=chocolate; path=/", headers["Set-Cookie"] assert_equal({ "cookie_1" => "", "cookie_2" => "oatmeal", "cookie_3" => "chocolate" }, cookies.to_hash) @@ -289,7 +289,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest assert_response :success assert_equal "bar", body - assert_equal nil, headers["Set-Cookie"] + assert_nil headers["Set-Cookie"] assert_equal({ "foo" => "bar" }, cookies.to_hash) end end @@ -308,7 +308,7 @@ class IntegrationProcessTest < ActionDispatch::IntegrationTest assert_response :success assert_equal "bar", body - assert_equal nil, headers["Set-Cookie"] + assert_nil headers["Set-Cookie"] assert_equal({ "foo" => "bar" }, cookies.to_hash) end end diff --git a/actionpack/test/controller/mime/accept_format_test.rb b/actionpack/test/controller/mime/accept_format_test.rb index a2834c9f39..a22fa39051 100644 --- a/actionpack/test/controller/mime/accept_format_test.rb +++ b/actionpack/test/controller/mime/accept_format_test.rb @@ -40,7 +40,7 @@ class PostController < AbstractPostController respond_to(:html, :iphone, :js) end -protected +private def with_iphone request.format = "iphone" if request.env["HTTP_ACCEPT"] == "text/iphone" diff --git a/actionpack/test/controller/mime/respond_to_test.rb b/actionpack/test/controller/mime/respond_to_test.rb index c5f8165d04..818dc119eb 100644 --- a/actionpack/test/controller/mime/respond_to_test.rb +++ b/actionpack/test/controller/mime/respond_to_test.rb @@ -273,7 +273,7 @@ class RespondToController < ActionController::Base end end - protected + private def set_layout case action_name when "all_types_with_layout", "iphone_with_html_response_type" diff --git a/actionpack/test/controller/new_base/bare_metal_test.rb b/actionpack/test/controller/new_base/bare_metal_test.rb index 9956f0b107..054757fab3 100644 --- a/actionpack/test/controller/new_base/bare_metal_test.rb +++ b/actionpack/test/controller/new_base/bare_metal_test.rb @@ -52,7 +52,7 @@ module BareMetalTest controller.set_request!(ActionDispatch::Request.empty) controller.set_response!(BareController.make_response!(controller.request)) controller.index - assert_equal nil, controller.response_body + assert_nil controller.response_body end end diff --git a/actionpack/test/controller/new_base/base_test.rb b/actionpack/test/controller/new_base/base_test.rb index 3765d406fc..b891df4c0f 100644 --- a/actionpack/test/controller/new_base/base_test.rb +++ b/actionpack/test/controller/new_base/base_test.rb @@ -25,7 +25,7 @@ module Dispatching render body: "actions: #{action_methods.to_a.sort.join(', ')}" end - protected + private def authenticate end end diff --git a/actionpack/test/controller/new_base/render_context_test.rb b/actionpack/test/controller/new_base/render_context_test.rb index b64468a94e..25b73ac78c 100644 --- a/actionpack/test/controller/new_base/render_context_test.rb +++ b/actionpack/test/controller/new_base/render_context_test.rb @@ -26,16 +26,14 @@ module RenderContext render action: "hello_world", layout: "basic" end - protected - - # 3) Set view_context to self - def view_context - self - end + protected def __controller_method__ + "controller context!" + end - def __controller_method__ - "controller context!" - end + # 3) Set view_context to self + private def view_context + self + end end class RenderContextTest < Rack::TestCase diff --git a/actionpack/test/controller/new_base/render_streaming_test.rb b/actionpack/test/controller/new_base/render_streaming_test.rb index 64b799f826..1177b8b03e 100644 --- a/actionpack/test/controller/new_base/render_streaming_test.rb +++ b/actionpack/test/controller/new_base/render_streaming_test.rb @@ -101,12 +101,12 @@ module RenderStreaming assert_body "Hello world, I'm here!" assert_status 200 assert_equal "22", headers["Content-Length"] - assert_equal nil, headers["Transfer-Encoding"] + assert_nil headers["Transfer-Encoding"] end def assert_streaming!(cache = "no-cache") assert_status 200 - assert_equal nil, headers["Content-Length"] + assert_nil headers["Content-Length"] assert_equal "chunked", headers["Transfer-Encoding"] assert_equal cache, headers["Cache-Control"] end diff --git a/actionpack/test/controller/parameter_encoding_test.rb b/actionpack/test/controller/parameter_encoding_test.rb index 7840b4f5c4..234d0bddd1 100644 --- a/actionpack/test/controller/parameter_encoding_test.rb +++ b/actionpack/test/controller/parameter_encoding_test.rb @@ -1,9 +1,8 @@ require "abstract_unit" class ParameterEncodingController < ActionController::Base - parameter_encoding :test_bar, :bar, Encoding::ASCII_8BIT - parameter_encoding :test_baz, :baz, Encoding::ISO_8859_1 - parameter_encoding :test_baz_to_ascii, :baz, Encoding::ASCII_8BIT + skip_parameter_encoding :test_bar + skip_parameter_encoding :test_all_values_encoding def test_foo render body: params[:foo].encoding @@ -13,16 +12,8 @@ class ParameterEncodingController < ActionController::Base render body: params[:bar].encoding end - def test_baz - render body: params[:baz].encoding - end - - def test_no_change_to_baz - render body: params[:baz].encoding - end - - def test_baz_to_ascii - render body: params[:baz].encoding + def test_all_values_encoding + render body: ::JSON.dump(params.values.map(&:encoding).map(&:name)) end end @@ -36,32 +27,18 @@ class ParameterEncodingTest < ActionController::TestCase assert_equal "UTF-8", @response.body end - test "properly transcodes ASCII_8BIT parameters into declared encodings" do + test "properly encodes ASCII_8BIT parameters into binary" do post :test_bar, params: { "foo" => "foo", "bar" => "bar", "baz" => "baz" } assert_response :success assert_equal "ASCII-8BIT", @response.body end - test "properly transcodes ISO_8859_1 parameters into declared encodings" do - post :test_baz, params: { "foo" => "foo", "bar" => "bar", "baz" => "baz" } - - assert_response :success - assert_equal "ISO-8859-1", @response.body - end - - test "does not transcode parameters when not specified" do - post :test_no_change_to_baz, params: { "foo" => "foo", "bar" => "bar", "baz" => "baz" } + test "properly encodes all ASCII_8BIT parameters into binary" do + post :test_all_values_encoding, params: { "foo" => "foo", "bar" => "bar", "baz" => "baz" } assert_response :success - assert_equal "UTF-8", @response.body - end - - test "respects different encoding declarations for a param per action" do - post :test_baz_to_ascii, params: { "foo" => "foo", "bar" => "bar", "baz" => "baz" } - - assert_response :success - assert_equal "ASCII-8BIT", @response.body + assert_equal ["ASCII-8BIT"], JSON.parse(@response.body).uniq end test "does not raise an error when passed a param declared as ASCII-8BIT that contains invalid bytes" do diff --git a/actionpack/test/controller/parameters/parameters_permit_test.rb b/actionpack/test/controller/parameters/parameters_permit_test.rb index 92e134d313..b62a3d6d7b 100644 --- a/actionpack/test/controller/parameters/parameters_permit_test.rb +++ b/actionpack/test/controller/parameters/parameters_permit_test.rb @@ -141,7 +141,7 @@ class ParametersPermitTest < ActiveSupport::TestCase permitted = params.permit(:a, c: [], b: []) assert_equal 1, permitted[:a] assert_equal [1, 2, 3], permitted[:b] - assert_equal nil, permitted[:c] + assert_nil permitted[:c] end test "key to empty array: arrays of permitted scalars pass" do @@ -216,7 +216,7 @@ class ParametersPermitTest < ActiveSupport::TestCase test "fetch with a default value of a hash does not mutate the object" do params = ActionController::Parameters.new({}) params.fetch :foo, {} - assert_equal nil, params[:foo] + assert_nil params[:foo] end test "hashes in array values get wrapped" do @@ -254,8 +254,8 @@ class ParametersPermitTest < ActiveSupport::TestCase end test "fetch doesnt raise ParameterMissing exception if there is a default that is nil" do - assert_equal nil, @params.fetch(:foo, nil) - assert_equal nil, @params.fetch(:foo) { nil } + assert_nil @params.fetch(:foo, nil) + assert_nil @params.fetch(:foo) { nil } end test "KeyError in fetch block should not be covered up" do diff --git a/actionpack/test/controller/params_wrapper_test.rb b/actionpack/test/controller/params_wrapper_test.rb index 46a2ab8ccf..faa57c4559 100644 --- a/actionpack/test/controller/params_wrapper_test.rb +++ b/actionpack/test/controller/params_wrapper_test.rb @@ -50,7 +50,7 @@ class ParamsWrapperTest < ActionController::TestCase with_default_wrapper_options do @request.env["CONTENT_TYPE"] = "application/json" post :parse, params: { "username" => "sikachu" } - assert_equal @request.filtered_parameters, "controller" => "params_wrapper_test/users", "action" => "parse", "username" => "sikachu", "user" => { "username" => "sikachu" } + assert_equal({ "controller" => "params_wrapper_test/users", "action" => "parse", "username" => "sikachu", "user" => { "username" => "sikachu" } }, @request.filtered_parameters) end end diff --git a/actionpack/test/controller/redirect_test.rb b/actionpack/test/controller/redirect_test.rb index 0e61b92bcf..e4e968dfdb 100644 --- a/actionpack/test/controller/redirect_test.rb +++ b/actionpack/test/controller/redirect_test.rb @@ -123,7 +123,7 @@ class RedirectController < ActionController::Base def rescue_errors(e) raise e end - protected + private def dashbord_url(id, message) url_for action: "dashboard", params: { "id" => id, "message" => message } end diff --git a/actionpack/test/controller/request/test_request_test.rb b/actionpack/test/controller/request/test_request_test.rb index da6fa1388b..b67ae72c0a 100644 --- a/actionpack/test/controller/request/test_request_test.rb +++ b/actionpack/test/controller/request/test_request_test.rb @@ -8,7 +8,7 @@ class ActionController::TestRequestTest < ActionController::TestCase def test_mutating_session_options_does_not_affect_default_options @request.session_options[:myparam] = 123 - assert_equal nil, ActionController::TestSession::DEFAULT_OPTIONS[:myparam] + assert_nil ActionController::TestSession::DEFAULT_OPTIONS[:myparam] end def test_content_length_has_bytes_count_value @@ -17,8 +17,8 @@ class ActionController::TestRequestTest < ActionController::TestCase @request.set_header "CONTENT_TYPE", "application/json" @request.assign_parameters(@routes, "test", "create", non_ascii_parameters, "/test", [:data, :controller, :action]) - assert_equal(@request.get_header("CONTENT_LENGTH"), - StringIO.new(non_ascii_parameters.to_json).length.to_s) + assert_equal(StringIO.new(non_ascii_parameters.to_json).length.to_s, + @request.get_header("CONTENT_LENGTH")) end ActionDispatch::Session::AbstractStore::DEFAULT_OPTIONS.each_key do |option| diff --git a/actionpack/test/controller/request_forgery_protection_test.rb b/actionpack/test/controller/request_forgery_protection_test.rb index 90d5ab3c67..d645ddfdbe 100644 --- a/actionpack/test/controller/request_forgery_protection_test.rb +++ b/actionpack/test/controller/request_forgery_protection_test.rb @@ -92,7 +92,7 @@ class PrependProtectForgeryBaseController < ActionController::Base render inline: "OK" end - protected + private def add_called_callback(name) @called_callbacks ||= [] diff --git a/actionpack/test/controller/rescue_test.rb b/actionpack/test/controller/rescue_test.rb index a98e6479b7..9ae22c4554 100644 --- a/actionpack/test/controller/rescue_test.rb +++ b/actionpack/test/controller/rescue_test.rb @@ -149,7 +149,7 @@ class RescueController < ActionController::Base raise RangeError end - protected + private def deny_access head :forbidden end @@ -327,7 +327,7 @@ class RescueTest < ActionDispatch::IntegrationTest raise "b00m" end - protected + private def show_errors(exception) render plain: exception.message end diff --git a/actionpack/test/controller/resources_test.rb b/actionpack/test/controller/resources_test.rb index 0b3dc6c41f..fad34dacce 100644 --- a/actionpack/test/controller/resources_test.rb +++ b/actionpack/test/controller/resources_test.rb @@ -1089,7 +1089,7 @@ class ResourcesTest < ActionController::TestCase end end - protected + private def with_restful_routing(*args) options = args.extract_options! collection_methods = options.delete(:collection) diff --git a/actionpack/test/controller/send_file_test.rb b/actionpack/test/controller/send_file_test.rb index a28283f4d6..9e6b975fe2 100644 --- a/actionpack/test/controller/send_file_test.rb +++ b/actionpack/test/controller/send_file_test.rb @@ -241,10 +241,17 @@ class SendFileTest < ActionController::TestCase assert_equal "text/calendar; charset=utf-8", response.headers["Content-Type"] end + def test_send_file_charset_with_type_options_key_without_charset + @controller = SendFileWithActionControllerLive.new + @controller.options = { type: "image/png" } + response = process("file") + assert_equal "image/png", response.headers["Content-Type"] + end + def test_send_file_charset_with_content_type_options_key @controller = SendFileWithActionControllerLive.new @controller.options = { content_type: "text/calendar" } response = process("file") - assert_equal "text/calendar; charset=utf-8", response.headers["Content-Type"] + assert_equal "text/calendar", response.headers["Content-Type"] end end diff --git a/actionpack/test/controller/test_case_test.rb b/actionpack/test/controller/test_case_test.rb index 05aa4ff6ad..874f9c3c42 100644 --- a/actionpack/test/controller/test_case_test.rb +++ b/actionpack/test/controller/test_case_test.rb @@ -100,11 +100,11 @@ HTML end def test_xml_output - response.content_type = "application/xml" + response.content_type = params[:response_as] render plain: <<XML <?xml version="1.0" encoding="UTF-8"?> <root> - <area>area is an empty tag in HTML, raising an error if not in xml mode</area> + <area><p>area is an empty tag in HTML, so it won't contain this content</p></area> </root> XML end @@ -374,18 +374,18 @@ XML assert_equal "OK", @response.body end - def test_should_not_impose_childless_html_tags_in_xml - process :test_xml_output + def test_should_impose_childless_html_tags_in_html + process :test_xml_output, params: { response_as: "text/html" } - begin - $stderr = StringIO.new - assert_select "area" #This will cause a warning if content is processed as HTML - $stderr.rewind && err = $stderr.read - ensure - $stderr = STDERR - end + # <area> auto-closes, so the <p> becomes a sibling + assert_select "root > area + p" + end + + def test_should_not_impose_childless_html_tags_in_xml + process :test_xml_output, params: { response_as: "application/xml" } - assert err.empty?, err.inspect + # <area> is not special, so the <p> is its child + assert_select "root > area > p" end def test_assert_generates diff --git a/actionpack/test/controller/url_for_test.rb b/actionpack/test/controller/url_for_test.rb index 4b6f33c545..862dcf01c3 100644 --- a/actionpack/test/controller/url_for_test.rb +++ b/actionpack/test/controller/url_for_test.rb @@ -26,7 +26,7 @@ module AbstractController action: :index } }.url_helpers - self.default_url_options[:host] = "example.com" + default_url_options[:host] = "example.com" } path = klass.new.fun_path(controller: :articles, @@ -487,6 +487,27 @@ module AbstractController end end + def test_default_params_first_empty + with_routing do |set| + set.draw do + get "(:param1)/test(/:param2)" => "index#index", + defaults: { + param1: 1, + param2: 2 + }, + constraints: { + param1: /\d*/, + param2: /\d+/ + } + end + + kls = Class.new { include set.url_helpers } + kls.default_url_options[:host] = "www.basecamphq.com" + + assert_equal "http://www.basecamphq.com/test", kls.new.url_for(controller: "index", param1: "1") + end + end + private def extract_params(url) url.split("?", 2).last.split("&").sort diff --git a/actionpack/test/dispatch/cookies_test.rb b/actionpack/test/dispatch/cookies_test.rb index af3036d448..73ad677419 100644 --- a/actionpack/test/dispatch/cookies_test.rb +++ b/actionpack/test/dispatch/cookies_test.rb @@ -272,6 +272,10 @@ class CookiesTest < ActionController::TestCase def noop head :ok end + + def encrypted_cookie + cookies.encrypted["foo"] + end end tests TestController @@ -391,6 +395,15 @@ class CookiesTest < ActionController::TestCase assert_equal false, cookies.deleted?("another") end + # Ensure all HTTP methods have their cookies updated + [:get, :post, :patch, :put, :delete, :head].each do |method| + define_method("test_deleting_cookie_#{method}") do + request.cookies[:user_name] = "Joe" + public_send method, :logout + assert_nil cookies[:user_name] + end + end + def test_deleted_cookie_predicate_with_mismatching_options cookies[:user_name] = "Joe" cookies.delete("user_name", path: "/path") @@ -940,8 +953,8 @@ class CookiesTest < ActionController::TestCase @request.headers["Cookie"] = "user_id=45" get :get_signed_cookie - assert_equal nil, @controller.send(:cookies).signed[:user_id] - assert_equal nil, @response.cookies["user_id"] + assert_nil @controller.send(:cookies).signed[:user_id] + assert_nil @response.cookies["user_id"] end def test_legacy_signed_cookie_is_treated_as_nil_by_encrypted_cookie_jar_if_tampered @@ -951,8 +964,8 @@ class CookiesTest < ActionController::TestCase @request.headers["Cookie"] = "foo=baz" get :get_encrypted_cookie - assert_equal nil, @controller.send(:cookies).encrypted[:foo] - assert_equal nil, @response.cookies["foo"] + assert_nil @controller.send(:cookies).encrypted[:foo] + assert_nil @response.cookies["foo"] end def test_cookie_with_all_domain_option @@ -1189,6 +1202,12 @@ class CookiesTest < ActionController::TestCase assert_equal "david", cookies[:user_name] end + def test_cookies_are_not_cleared + cookies.encrypted["foo"] = "bar" + get :noop + assert_equal "bar", @controller.encrypted_cookie + end + private def assert_cookie_header(expected) header = @response.headers["Set-Cookie"] diff --git a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb index eb4bb14ed1..01c5ff1429 100644 --- a/actionpack/test/dispatch/request/multipart_params_parsing_test.rb +++ b/actionpack/test/dispatch/request/multipart_params_parsing_test.rb @@ -129,7 +129,7 @@ class MultipartParamsParsingTest < ActionDispatch::IntegrationTest params = parse_multipart("none") assert_equal %w(submit-name), params.keys.sort assert_equal "Larry", params["submit-name"] - assert_equal nil, params["files"] + assert_nil params["files"] end test "parses empty upload file" do diff --git a/actionpack/test/dispatch/request_test.rb b/actionpack/test/dispatch/request_test.rb index 2f41851598..e11b93b4f0 100644 --- a/actionpack/test/dispatch/request_test.rb +++ b/actionpack/test/dispatch/request_test.rb @@ -18,7 +18,7 @@ class BaseRequestTest < ActiveSupport::TestCase ActionDispatch::Http::URL.url_for(options) end - protected + private def stub_request(env = {}) ip_spoofing_check = env.key?(:ip_spoofing_check) ? env.delete(:ip_spoofing_check) : true @trusted_proxies ||= nil @@ -94,13 +94,13 @@ class RequestIP < BaseRequestTest assert_equal "3.4.5.6", request.remote_ip request = stub_request "HTTP_X_FORWARDED_FOR" => "unknown,192.168.0.1" - assert_equal nil, request.remote_ip + assert_nil request.remote_ip request = stub_request "HTTP_X_FORWARDED_FOR" => "9.9.9.9, 3.4.5.6, 172.31.4.4, 10.0.0.1" assert_equal "3.4.5.6", request.remote_ip request = stub_request "HTTP_X_FORWARDED_FOR" => "not_ip_address" - assert_equal nil, request.remote_ip + assert_nil request.remote_ip end test "remote ip spoof detection" do @@ -154,7 +154,7 @@ class RequestIP < BaseRequestTest assert_equal "fe80:0000:0000:0000:0202:b3ff:fe1e:8329", request.remote_ip request = stub_request "HTTP_X_FORWARDED_FOR" => "unknown,::1" - assert_equal nil, request.remote_ip + assert_nil request.remote_ip request = stub_request "HTTP_X_FORWARDED_FOR" => "2001:0db8:85a3:0000:0000:8a2e:0370:7334, fe80:0000:0000:0000:0202:b3ff:fe1e:8329, ::1, fc00::, fc01::, fdff" assert_equal "fe80:0000:0000:0000:0202:b3ff:fe1e:8329", request.remote_ip @@ -163,7 +163,7 @@ class RequestIP < BaseRequestTest assert_equal "FE00::", request.remote_ip request = stub_request "HTTP_X_FORWARDED_FOR" => "not_ip_address" - assert_equal nil, request.remote_ip + assert_nil request.remote_ip end test "remote ip v6 spoof detection" do @@ -200,7 +200,7 @@ class RequestIP < BaseRequestTest assert_equal "3.4.5.6", request.remote_ip request = stub_request "HTTP_X_FORWARDED_FOR" => "67.205.106.73,unknown" - assert_equal nil, request.remote_ip + assert_nil request.remote_ip request = stub_request "HTTP_X_FORWARDED_FOR" => "9.9.9.9, 3.4.5.6, 10.0.0.1, 67.205.106.73" assert_equal "3.4.5.6", request.remote_ip @@ -222,7 +222,7 @@ class RequestIP < BaseRequestTest assert_equal "::1", request.remote_ip request = stub_request "HTTP_X_FORWARDED_FOR" => "unknown,fe80:0000:0000:0000:0202:b3ff:fe1e:8329" - assert_equal nil, request.remote_ip + assert_nil request.remote_ip request = stub_request "HTTP_X_FORWARDED_FOR" => "fe80:0000:0000:0000:0202:b3ff:fe1e:8329,2001:0db8:85a3:0000:0000:8a2e:0370:7334" assert_equal "2001:0db8:85a3:0000:0000:8a2e:0370:7334", request.remote_ip @@ -345,7 +345,7 @@ class RequestPort < BaseRequestTest test "optional port" do request = stub_request "HTTP_HOST" => "www.example.org:80" - assert_equal nil, request.optional_port + assert_nil request.optional_port request = stub_request "HTTP_HOST" => "www.example.org:8080" assert_equal 8080, request.optional_port @@ -537,7 +537,7 @@ class RequestCGI < BaseRequestTest assert_equal "Basic", request.auth_type assert_equal 0, request.content_length - assert_equal nil, request.content_mime_type + assert_nil request.content_mime_type assert_equal "CGI/1.1", request.gateway_interface assert_equal "*/*", request.accept assert_equal "UTF-8", request.accept_charset @@ -957,7 +957,7 @@ class RequestMimeType < BaseRequestTest end test "no content type" do - assert_equal nil, stub_request.content_mime_type + assert_nil stub_request.content_mime_type end test "content type is XML" do @@ -978,7 +978,7 @@ class RequestMimeType < BaseRequestTest "HTTP_X_REQUESTED_WITH" => "XMLHttpRequest" ) - assert_equal nil, request.negotiate_mime([Mime[:xml], Mime[:json]]) + assert_nil request.negotiate_mime([Mime[:xml], Mime[:json]]) assert_equal Mime[:html], request.negotiate_mime([Mime[:xml], Mime[:html]]) assert_equal Mime[:html], request.negotiate_mime([Mime[:xml], Mime::ALL]) end @@ -1192,7 +1192,7 @@ class RequestEtag < BaseRequestTest test "doesn't match absent If-None-Match" do request = stub_request - assert_equal nil, request.if_none_match + assert_nil request.if_none_match assert_equal [], request.if_none_match_etags assert_not request.etag_matches?("foo") diff --git a/actionpack/test/dispatch/response_test.rb b/actionpack/test/dispatch/response_test.rb index 2df70704a1..7433c5ce0c 100644 --- a/actionpack/test/dispatch/response_test.rb +++ b/actionpack/test/dispatch/response_test.rb @@ -74,7 +74,7 @@ class ResponseTest < ActiveSupport::TestCase @response.body = "Hello, World!" # even though there's no explicitly set content-type, - assert_equal nil, @response.content_type + assert_nil @response.content_type # after the action reads back @response.body, assert_equal "Hello, World!", @response.body @@ -111,8 +111,8 @@ class ResponseTest < ActiveSupport::TestCase end def test_empty_content_type_returns_nil - @response.headers['Content-Type'] = "" - assert_equal nil, @response.content_type + @response.headers["Content-Type"] = "" + assert_nil @response.content_type end test "simple output" do diff --git a/actionpack/test/dispatch/routing_test.rb b/actionpack/test/dispatch/routing_test.rb index 92d323f292..53758a4fbc 100644 --- a/actionpack/test/dispatch/routing_test.rb +++ b/actionpack/test/dispatch/routing_test.rb @@ -1603,7 +1603,7 @@ class TestRoutingMapper < ActionDispatch::IntegrationTest get "account/login", to: redirect("/login") end - previous_host, self.host = self.host, "www.example.com:3000" + previous_host, self.host = host, "www.example.com:3000" get "/account/login" verify_redirect "http://www.example.com:3000/login" @@ -4189,7 +4189,7 @@ class TestConstraintsAccessingParameters < ActionDispatch::IntegrationTest test "parameters are reset between constraint checks" do get "/bar" - assert_equal nil, @request.params[:foo] + assert_nil @request.params[:foo] assert_equal "bar", @request.params[:bar] end end diff --git a/actionpack/test/dispatch/session/cache_store_test.rb b/actionpack/test/dispatch/session/cache_store_test.rb index a60629a7ee..859059063f 100644 --- a/actionpack/test/dispatch/session/cache_store_test.rb +++ b/actionpack/test/dispatch/session/cache_store_test.rb @@ -142,20 +142,20 @@ class CacheStoreTest < ActionDispatch::IntegrationTest get "/get_session_value" assert_response :success - assert_equal nil, headers["Set-Cookie"], "should not resend the cookie again if session_id cookie is already exists" + assert_nil headers["Set-Cookie"], "should not resend the cookie again if session_id cookie is already exists" end end def test_prevents_session_fixation with_test_route_set do - assert_equal nil, @cache.read("_session_id:0xhax") + assert_nil @cache.read("_session_id:0xhax") cookies["_session_id"] = "0xhax" get "/set_session_value" assert_response :success assert_not_equal "0xhax", cookies["_session_id"] - assert_equal nil, @cache.read("_session_id:0xhax") + assert_nil @cache.read("_session_id:0xhax") assert_equal({ "foo" => "bar" }, @cache.read("_session_id:#{cookies['_session_id']}")) end end diff --git a/actionpack/test/dispatch/session/cookie_store_test.rb b/actionpack/test/dispatch/session/cookie_store_test.rb index 013d289c6d..2a1053be16 100644 --- a/actionpack/test/dispatch/session/cookie_store_test.rb +++ b/actionpack/test/dispatch/session/cookie_store_test.rb @@ -108,7 +108,7 @@ class CookieStoreTest < ActionDispatch::IntegrationTest with_test_route_set(secure: true) do get "/set_session_value" assert_response :success - assert_equal nil, headers["Set-Cookie"] + assert_nil headers["Set-Cookie"] end end @@ -169,7 +169,7 @@ class CookieStoreTest < ActionDispatch::IntegrationTest with_test_route_set do get "/no_session_access" assert_response :success - assert_equal nil, headers["Set-Cookie"] + assert_nil headers["Set-Cookie"] end end @@ -179,7 +179,7 @@ class CookieStoreTest < ActionDispatch::IntegrationTest "fef868465920f415f2c0652d6910d3af288a0367" get "/no_session_access" assert_response :success - assert_equal nil, headers["Set-Cookie"] + assert_nil headers["Set-Cookie"] end end diff --git a/actionpack/test/dispatch/session/mem_cache_store_test.rb b/actionpack/test/dispatch/session/mem_cache_store_test.rb index c2d0719b4e..121e9ebef7 100644 --- a/actionpack/test/dispatch/session/mem_cache_store_test.rb +++ b/actionpack/test/dispatch/session/mem_cache_store_test.rb @@ -157,7 +157,7 @@ class MemCacheStoreTest < ActionDispatch::IntegrationTest get "/get_session_value" assert_response :success - assert_equal nil, headers["Set-Cookie"], "should not resend the cookie again if session_id cookie is already exists" + assert_nil headers["Set-Cookie"], "should not resend the cookie again if session_id cookie is already exists" end rescue Dalli::RingError => ex skip ex.message, ex.backtrace diff --git a/actionpack/test/dispatch/static_test.rb b/actionpack/test/dispatch/static_test.rb index 3facbf59c2..d8bc96e3e0 100644 --- a/actionpack/test/dispatch/static_test.rb +++ b/actionpack/test/dispatch/static_test.rb @@ -177,9 +177,9 @@ module StaticTests last_modified = File.mtime(File.join(@root, "#{file_name}.gz")) response = get(file_name, "HTTP_ACCEPT_ENCODING" => "gzip", "HTTP_IF_MODIFIED_SINCE" => last_modified.httpdate) assert_equal 304, response.status - assert_equal nil, response.headers["Content-Type"] - assert_equal nil, response.headers["Content-Encoding"] - assert_equal nil, response.headers["Vary"] + assert_nil response.headers["Content-Type"] + assert_nil response.headers["Content-Encoding"] + assert_nil response.headers["Vary"] end def test_serves_files_with_headers diff --git a/actionpack/test/dispatch/test_request_test.rb b/actionpack/test/dispatch/test_request_test.rb index b479af781d..85a6df4975 100644 --- a/actionpack/test/dispatch/test_request_test.rb +++ b/actionpack/test/dispatch/test_request_test.rb @@ -30,7 +30,7 @@ class TestRequestTest < ActiveSupport::TestCase req = ActionDispatch::TestRequest.create({}) assert_equal({}, req.cookies) - assert_equal nil, req.env["HTTP_COOKIE"] + assert_nil req.env["HTTP_COOKIE"] req.cookie_jar["user_name"] = "david" assert_cookies({ "user_name" => "david" }, req.cookie_jar) diff --git a/actionpack/test/journey/route_test.rb b/actionpack/test/journey/route_test.rb index d2a8163ffb..8fd73970b8 100644 --- a/actionpack/test/journey/route_test.rb +++ b/actionpack/test/journey/route_test.rb @@ -96,7 +96,7 @@ module ActionDispatch path = Path::Pattern.from_string "/:controller(/:action(/:id))(.:format)" generic = Route.build "name", nil, path, constraints, [], {} - knowledge = { id: 20, controller: "pages", action: "show" } + knowledge = { "id" => true, "controller" => true, "action" => true } routes = [specific, generic] |