diff options
Diffstat (limited to 'actionpack/lib/action_dispatch/middleware')
20 files changed, 385 insertions, 472 deletions
diff --git a/actionpack/lib/action_dispatch/middleware/callbacks.rb b/actionpack/lib/action_dispatch/middleware/callbacks.rb index c782779b34..fef246532b 100644 --- a/actionpack/lib/action_dispatch/middleware/callbacks.rb +++ b/actionpack/lib/action_dispatch/middleware/callbacks.rb @@ -15,8 +15,8 @@ module ActionDispatch ActiveSupport::Reloader.to_complete(*args, &block) end - deprecate to_prepare: 'use ActiveSupport::Reloader.to_prepare instead', - to_cleanup: 'use ActiveSupport::Reloader.to_complete instead' + deprecate to_prepare: "use ActiveSupport::Reloader.to_prepare instead", + to_cleanup: "use ActiveSupport::Reloader.to_complete instead" def before(*args, &block) set_callback(:call, :before, *args, &block) diff --git a/actionpack/lib/action_dispatch/middleware/cookies.rb b/actionpack/lib/action_dispatch/middleware/cookies.rb index f2f3150b56..956c53e813 100644 --- a/actionpack/lib/action_dispatch/middleware/cookies.rb +++ b/actionpack/lib/action_dispatch/middleware/cookies.rb @@ -1,13 +1,13 @@ -require 'active_support/core_ext/hash/keys' -require 'active_support/key_generator' -require 'active_support/message_verifier' -require 'active_support/json' -require 'rack/utils' +require "active_support/core_ext/hash/keys" +require "active_support/key_generator" +require "active_support/message_verifier" +require "active_support/json" +require "rack/utils" module ActionDispatch class Request def cookie_jar - fetch_header('action_dispatch.cookies'.freeze) do + fetch_header("action_dispatch.cookies".freeze) do self.cookie_jar = Cookies::CookieJar.build(self, cookies) end end @@ -20,11 +20,11 @@ module ActionDispatch } def have_cookie_jar? - has_header? 'action_dispatch.cookies'.freeze + has_header? "action_dispatch.cookies".freeze end def cookie_jar=(jar) - set_header 'action_dispatch.cookies'.freeze, jar + set_header "action_dispatch.cookies".freeze, jar end def key_generator @@ -179,7 +179,7 @@ module ActionDispatch # Returns a jar that'll automatically generate a signed representation of cookie value and verify it when reading from # the cookie again. This is useful for creating cookies with values that the user is not supposed to change. If a signed - # cookie was tampered with by the user (or a 3rd party), nil will be returned. + # cookie was tampered with by the user (or a 3rd party), +nil+ will be returned. # # If +secrets.secret_key_base+ and +secrets.secret_token+ (deprecated) are both set, # legacy cookies signed with the old key generator will be transparently upgraded. @@ -202,7 +202,7 @@ module ActionDispatch end # Returns a jar that'll automatically encrypt cookie values before sending them to the client and will decrypt them for read. - # If the cookie was tampered with by the user (or a 3rd party), nil will be returned. + # If the cookie was tampered with by the user (or a 3rd party), +nil+ will be returned. # # If +secrets.secret_key_base+ and +secrets.secret_token+ (deprecated) are both set, # legacy cookies signed with the old key generator will be transparently upgraded. @@ -237,9 +237,9 @@ module ActionDispatch private - def upgrade_legacy_signed_cookies? - request.secret_token.present? && request.secret_key_base.present? - end + def upgrade_legacy_signed_cookies? + request.secret_token.present? && request.secret_key_base.present? + end end # Passing the ActiveSupport::MessageEncryptor::NullSerializer downstream @@ -332,19 +332,19 @@ module ActionDispatch def update_cookies_from_jar request_jar = @request.cookie_jar.instance_variable_get(:@cookies) - set_cookies = request_jar.reject { |k,_| @delete_cookies.key?(k) } + set_cookies = request_jar.reject { |k, _| @delete_cookies.key?(k) } @cookies.update set_cookies if set_cookies end def to_header - @cookies.map { |k,v| "#{escape(k)}=#{escape(v)}" }.join '; ' + @cookies.map { |k, v| "#{escape(k)}=#{escape(v)}" }.join "; " end def handle_options(options) #:nodoc: options[:path] ||= "/" - if options[:domain] == :all || options[:domain] == 'all' + if options[:domain] == :all || options[:domain] == "all" # if there is a provided tld length then we use it otherwise default domain regexp domain_regexp = options[:tld_length] ? /([^.]+\.?){#{options[:tld_length]}}$/ : DOMAIN_REGEXP @@ -355,7 +355,7 @@ module ActionDispatch end elsif options[:domain].is_a? Array # if host matches one of the supplied domains without a dot in front of it - options[:domain] = options[:domain].find {|domain| request.host.include? domain.sub(/^\./, '') } + options[:domain] = options[:domain].find { |domain| request.host.include? domain.sub(/^\./, "") } end end @@ -367,12 +367,12 @@ module ActionDispatch value = options[:value] else value = options - options = { :value => value } + options = { value: value } end handle_options(options) - if @cookies[name.to_s] != value or options[:expires] + if @cookies[name.to_s] != value || options[:expires] @cookies[name.to_s] = value @set_cookies[name.to_s] = options @delete_cookies.delete(name.to_s) @@ -406,7 +406,7 @@ module ActionDispatch # Removes all cookies on the client machine by calling <tt>delete</tt> for each cookie def clear(options = {}) - @cookies.each_key{ |k| delete(k, options) } + @cookies.each_key { |k| delete(k, options) } end def write(headers) @@ -420,26 +420,26 @@ module ActionDispatch private - def escape(string) - ::Rack::Utils.escape(string) - end + def escape(string) + ::Rack::Utils.escape(string) + end - def make_set_cookie_header(header) - header = @set_cookies.inject(header) { |m, (k, v)| - if write_cookie?(v) - ::Rack::Utils.add_cookie_to_header(m, k, v) - else - m - end - } - @delete_cookies.inject(header) { |m, (k, v)| - ::Rack::Utils.add_remove_cookie_to_header(m, k, v) - } - end + def make_set_cookie_header(header) + header = @set_cookies.inject(header) { |m, (k, v)| + if write_cookie?(v) + ::Rack::Utils.add_cookie_to_header(m, k, v) + else + m + end + } + @delete_cookies.inject(header) { |m, (k, v)| + ::Rack::Utils.add_remove_cookie_to_header(m, k, v) + } + end - def write_cookie?(cookie) - request.ssl? || !cookie[:secure] || always_write_cookie - end + def write_cookie?(cookie) + request.ssl? || !cookie[:secure] || always_write_cookie + end end class AbstractCookieJar # :nodoc: @@ -528,7 +528,7 @@ module ActionDispatch end def digest - request.cookies_digest || 'SHA1' + request.cookies_digest || "SHA1" end def key_generator @@ -576,8 +576,8 @@ module ActionDispatch "Read the upgrade documentation to learn more about this new config option." end - secret = key_generator.generate_key(request.encrypted_cookie_salt || '') - sign_secret = key_generator.generate_key(request.encrypted_signed_cookie_salt || '') + secret = key_generator.generate_key(request.encrypted_cookie_salt || "")[0, ActiveSupport::MessageEncryptor.key_len] + sign_secret = key_generator.generate_key(request.encrypted_signed_cookie_salt || "") @encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer) end diff --git a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb index 8974258cf7..1c720c5a8e 100644 --- a/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/debug_exceptions.rb @@ -1,16 +1,16 @@ -require 'action_dispatch/http/request' -require 'action_dispatch/middleware/exception_wrapper' -require 'action_dispatch/routing/inspector' -require 'action_view' -require 'action_view/base' +require "action_dispatch/http/request" +require "action_dispatch/middleware/exception_wrapper" +require "action_dispatch/routing/inspector" +require "action_view" +require "action_view/base" -require 'pp' +require "pp" module ActionDispatch # This middleware is responsible for logging exceptions and # showing a debugging page in case the request is local. class DebugExceptions - RESCUES_TEMPLATE_PATH = File.expand_path('../templates', __FILE__) + RESCUES_TEMPLATE_PATH = File.expand_path("../templates", __FILE__) class DebugView < ActionView::Base def debug_params(params) @@ -19,7 +19,7 @@ module ActionDispatch clean_params.delete("controller") if clean_params.empty? - 'None' + "None" else PP.pp(clean_params, "", 200) end @@ -27,9 +27,9 @@ module ActionDispatch def debug_headers(headers) if headers.present? - headers.inspect.gsub(',', ",\n") + headers.inspect.gsub(",", ",\n") else - 'None' + "None" end end @@ -38,7 +38,9 @@ module ActionDispatch end def render(*) - if logger = ActionView::Base.logger + logger = ActionView::Base.logger + + if logger && logger.respond_to?(:silence) logger.silence { super } else super @@ -56,7 +58,7 @@ module ActionDispatch request = ActionDispatch::Request.new env _, headers, body = response = @app.call(env) - if headers['X-Cascade'] == 'pass' + if headers["X-Cascade"] == "pass" body.close if body.respond_to?(:close) raise ActionController::RoutingError, "No route matches [#{env['REQUEST_METHOD']}] #{env['PATH_INFO'].inspect}" end @@ -69,129 +71,133 @@ module ActionDispatch private - def render_exception(request, exception) - backtrace_cleaner = request.get_header('action_dispatch.backtrace_cleaner') - wrapper = ExceptionWrapper.new(backtrace_cleaner, exception) - log_error(request, wrapper) + def render_exception(request, exception) + backtrace_cleaner = request.get_header("action_dispatch.backtrace_cleaner") + wrapper = ExceptionWrapper.new(backtrace_cleaner, exception) + log_error(request, wrapper) - if request.get_header('action_dispatch.show_detailed_exceptions') - content_type = request.formats.first + if request.get_header("action_dispatch.show_detailed_exceptions") + content_type = request.formats.first - if api_request?(content_type) - render_for_api_request(content_type, wrapper) + if api_request?(content_type) + render_for_api_request(content_type, wrapper) + else + render_for_browser_request(request, wrapper) + end else - render_for_browser_request(request, wrapper) + raise exception end - else - raise exception end - end - def render_for_browser_request(request, wrapper) - template = create_template(request, wrapper) - file = "rescues/#{wrapper.rescue_template}" + def render_for_browser_request(request, wrapper) + template = create_template(request, wrapper) + file = "rescues/#{wrapper.rescue_template}" - if request.xhr? - body = template.render(template: file, layout: false, formats: [:text]) - format = "text/plain" - else - body = template.render(template: file, layout: 'rescues/layout') - format = "text/html" + if request.xhr? + body = template.render(template: file, layout: false, formats: [:text]) + format = "text/plain" + else + body = template.render(template: file, layout: "rescues/layout") + format = "text/html" + end + render(wrapper.status_code, body, format) end - render(wrapper.status_code, body, format) - end - - def render_for_api_request(content_type, wrapper) - body = { - status: wrapper.status_code, - error: Rack::Utils::HTTP_STATUS_CODES.fetch( - wrapper.status_code, - Rack::Utils::HTTP_STATUS_CODES[500] - ), - exception: wrapper.exception.inspect, - traces: wrapper.traces - } - to_format = "to_#{content_type.to_sym}" + def render_for_api_request(content_type, wrapper) + body = { + status: wrapper.status_code, + error: Rack::Utils::HTTP_STATUS_CODES.fetch( + wrapper.status_code, + Rack::Utils::HTTP_STATUS_CODES[500] + ), + exception: wrapper.exception.inspect, + traces: wrapper.traces + } + + to_format = "to_#{content_type.to_sym}" + + if content_type && body.respond_to?(to_format) + formatted_body = body.public_send(to_format) + format = content_type + else + formatted_body = body.to_json + format = Mime[:json] + end - if content_type && body.respond_to?(to_format) - formatted_body = body.public_send(to_format) - format = content_type - else - formatted_body = body.to_json - format = Mime[:json] + render(wrapper.status_code, formatted_body, format) end - render(wrapper.status_code, formatted_body, format) - end + def create_template(request, wrapper) + traces = wrapper.traces - def create_template(request, wrapper) - traces = wrapper.traces + trace_to_show = "Application Trace" + if traces[trace_to_show].empty? && wrapper.rescue_template != "routing_error" + trace_to_show = "Full Trace" + end - trace_to_show = 'Application Trace' - if traces[trace_to_show].empty? && wrapper.rescue_template != 'routing_error' - trace_to_show = 'Full Trace' - end + if source_to_show = traces[trace_to_show].first + source_to_show_id = source_to_show[:id] + end - if source_to_show = traces[trace_to_show].first - source_to_show_id = source_to_show[:id] + DebugView.new([RESCUES_TEMPLATE_PATH], + request: request, + exception: wrapper.exception, + traces: traces, + show_source_idx: source_to_show_id, + trace_to_show: trace_to_show, + routes_inspector: routes_inspector(wrapper.exception), + source_extracts: wrapper.source_extracts, + line_number: wrapper.line_number, + file: wrapper.file + ) end - DebugView.new([RESCUES_TEMPLATE_PATH], - request: request, - exception: wrapper.exception, - traces: traces, - show_source_idx: source_to_show_id, - trace_to_show: trace_to_show, - routes_inspector: routes_inspector(wrapper.exception), - source_extracts: wrapper.source_extracts, - line_number: wrapper.line_number, - file: wrapper.file - ) - end - - def render(status, body, format) - [status, {'Content-Type' => "#{format}; charset=#{Response.default_charset}", 'Content-Length' => body.bytesize.to_s}, [body]] - end + def render(status, body, format) + [status, { "Content-Type" => "#{format}; charset=#{Response.default_charset}", "Content-Length" => body.bytesize.to_s }, [body]] + end - def log_error(request, wrapper) - logger = logger(request) - return unless logger + def log_error(request, wrapper) + logger = logger(request) + return unless logger - exception = wrapper.exception + exception = wrapper.exception - trace = wrapper.application_trace - trace = wrapper.framework_trace if trace.empty? + trace = wrapper.application_trace + trace = wrapper.framework_trace if trace.empty? - ActiveSupport::Deprecation.silence do - logger.fatal " " - logger.fatal "#{exception.class} (#{exception.message}):" - log_array logger, exception.annoted_source_code if exception.respond_to?(:annoted_source_code) - logger.fatal " " - log_array logger, trace + ActiveSupport::Deprecation.silence do + logger.fatal " " + logger.fatal "#{exception.class} (#{exception.message}):" + log_array logger, exception.annoted_source_code if exception.respond_to?(:annoted_source_code) + logger.fatal " " + log_array logger, trace + end end - end - def log_array(logger, array) - array.map { |line| logger.fatal line } - end + def log_array(logger, array) + if logger.formatter && logger.formatter.respond_to?(:tags_text) + logger.fatal array.join("\n#{logger.formatter.tags_text}") + else + logger.fatal array.join("\n") + end + end - def logger(request) - request.logger || ActionView::Base.logger || stderr_logger - end + def logger(request) + request.logger || ActionView::Base.logger || stderr_logger + end - def stderr_logger - @stderr_logger ||= ActiveSupport::Logger.new($stderr) - end + def stderr_logger + @stderr_logger ||= ActiveSupport::Logger.new($stderr) + end - def routes_inspector(exception) - if @routes_app.respond_to?(:routes) && (exception.is_a?(ActionController::RoutingError) || exception.is_a?(ActionView::Template::Error)) - ActionDispatch::Routing::RoutesInspector.new(@routes_app.routes.routes) + def routes_inspector(exception) + if @routes_app.respond_to?(:routes) && (exception.is_a?(ActionController::RoutingError) || exception.is_a?(ActionView::Template::Error)) + ActionDispatch::Routing::RoutesInspector.new(@routes_app.routes.routes) + end end - end - def api_request?(content_type) - @response_format == :api && !content_type.html? - end + def api_request?(content_type) + @response_format == :api && !content_type.html? + end end end diff --git a/actionpack/lib/action_dispatch/middleware/debug_locks.rb b/actionpack/lib/action_dispatch/middleware/debug_locks.rb index 13254d08de..74b952528e 100644 --- a/actionpack/lib/action_dispatch/middleware/debug_locks.rb +++ b/actionpack/lib/action_dispatch/middleware/debug_locks.rb @@ -21,7 +21,7 @@ module ActionDispatch # This middleware exposes operational details of the server, with no access # control. It should only be enabled when in use, and removed thereafter. class DebugLocks - def initialize(app, path = '/rails/locks') + def initialize(app, path = "/rails/locks") @app = app @path = path end @@ -30,7 +30,7 @@ module ActionDispatch req = ActionDispatch::Request.new env if req.get? - path = req.path_info.chomp('/'.freeze) + path = req.path_info.chomp("/".freeze) if path == @path return render_details(req) end @@ -61,16 +61,16 @@ module ActionDispatch str = threads.map do |thread, info| if info[:exclusive] - lock_state = 'Exclusive' + lock_state = "Exclusive" elsif info[:sharing] > 0 - lock_state = 'Sharing' + lock_state = "Sharing" lock_state << " x#{info[:sharing]}" if info[:sharing] > 1 else - lock_state = 'No lock' + lock_state = "No lock" end if info[:waiting] - lock_state << ' (yielded share)' + lock_state << " (yielded share)" end msg = "Thread #{info[:index]} [0x#{thread.__id__.to_s(16)} #{thread.status || 'dead'}] #{lock_state}\n" @@ -86,11 +86,11 @@ module ActionDispatch end blockers = threads.values.select { |binfo| blocked_by?(info, binfo, threads.values) } - msg << " blocked by: #{blockers.map {|i| i[:index] }.join(', ')}\n" if blockers.any? + msg << " blocked by: #{blockers.map { |i| i[:index] }.join(', ')}\n" if blockers.any? end blockees = threads.values.select { |binfo| blocked_by?(binfo, info, threads.values) } - msg << " blocking: #{blockees.map {|i| i[:index] }.join(', ')}\n" if blockees.any? + msg << " blocking: #{blockees.map { |i| i[:index] }.join(', ')}\n" if blockees.any? msg << "\n#{info[:backtrace].join("\n")}\n" if info[:backtrace] end.join("\n\n---\n\n\n") diff --git a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb index 59edc66086..397f0a8b92 100644 --- a/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb +++ b/actionpack/lib/action_dispatch/middleware/exception_wrapper.rb @@ -1,33 +1,33 @@ -require 'active_support/core_ext/module/attribute_accessors' -require 'rack/utils' +require "active_support/core_ext/module/attribute_accessors" +require "rack/utils" module ActionDispatch class ExceptionWrapper cattr_accessor :rescue_responses @@rescue_responses = Hash.new(:internal_server_error) @@rescue_responses.merge!( - 'ActionController::RoutingError' => :not_found, - 'AbstractController::ActionNotFound' => :not_found, - 'ActionController::MethodNotAllowed' => :method_not_allowed, - 'ActionController::UnknownHttpMethod' => :method_not_allowed, - 'ActionController::NotImplemented' => :not_implemented, - 'ActionController::UnknownFormat' => :not_acceptable, - 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity, - 'ActionController::InvalidCrossOriginRequest' => :unprocessable_entity, - 'ActionDispatch::ParamsParser::ParseError' => :bad_request, - 'ActionController::BadRequest' => :bad_request, - 'ActionController::ParameterMissing' => :bad_request, - 'Rack::Utils::ParameterTypeError' => :bad_request, - 'Rack::Utils::InvalidParameterError' => :bad_request + "ActionController::RoutingError" => :not_found, + "AbstractController::ActionNotFound" => :not_found, + "ActionController::MethodNotAllowed" => :method_not_allowed, + "ActionController::UnknownHttpMethod" => :method_not_allowed, + "ActionController::NotImplemented" => :not_implemented, + "ActionController::UnknownFormat" => :not_acceptable, + "ActionController::InvalidAuthenticityToken" => :unprocessable_entity, + "ActionController::InvalidCrossOriginRequest" => :unprocessable_entity, + "ActionDispatch::Http::Parameters::ParseError" => :bad_request, + "ActionController::BadRequest" => :bad_request, + "ActionController::ParameterMissing" => :bad_request, + "Rack::QueryParser::ParameterTypeError" => :bad_request, + "Rack::QueryParser::InvalidParameterError" => :bad_request ) cattr_accessor :rescue_templates - @@rescue_templates = Hash.new('diagnostics') + @@rescue_templates = Hash.new("diagnostics") @@rescue_templates.merge!( - 'ActionView::MissingTemplate' => 'missing_template', - 'ActionController::RoutingError' => 'routing_error', - 'AbstractController::ActionNotFound' => 'unknown_action', - 'ActionView::Template::Error' => 'template_error' + "ActionView::MissingTemplate" => "missing_template", + "ActionController::RoutingError" => "routing_error", + "AbstractController::ActionNotFound" => "unknown_action", + "ActionView::Template::Error" => "template_error" ) attr_reader :backtrace_cleaner, :exception, :line_number, :file @@ -100,49 +100,49 @@ module ActionDispatch private - def backtrace - Array(@exception.backtrace) - end + def backtrace + Array(@exception.backtrace) + end - def original_exception(exception) - if @@rescue_responses.has_key?(exception.cause.class.name) - exception.cause - else - exception + def original_exception(exception) + if @@rescue_responses.has_key?(exception.cause.class.name) + exception.cause + else + exception + end end - end - def clean_backtrace(*args) - if backtrace_cleaner - backtrace_cleaner.clean(backtrace, *args) - else - backtrace + def clean_backtrace(*args) + if backtrace_cleaner + backtrace_cleaner.clean(backtrace, *args) + else + backtrace + end end - end - def source_fragment(path, line) - return unless Rails.respond_to?(:root) && Rails.root - full_path = Rails.root.join(path) - if File.exist?(full_path) - File.open(full_path, "r") do |file| - start = [line - 3, 0].max - lines = file.each_line.drop(start).take(6) - Hash[*(start+1..(lines.count+start)).zip(lines).flatten] + def source_fragment(path, line) + return unless Rails.respond_to?(:root) && Rails.root + full_path = Rails.root.join(path) + if File.exist?(full_path) + File.open(full_path, "r") do |file| + start = [line - 3, 0].max + lines = file.each_line.drop(start).take(6) + Hash[*(start + 1..(lines.count + start)).zip(lines).flatten] + end end end - end - def extract_file_and_line_number(trace) - # Split by the first colon followed by some digits, which works for both - # Windows and Unix path styles. - file, line = trace.match(/^(.+?):(\d+).*$/, &:captures) || trace - [file, line.to_i] - end + def extract_file_and_line_number(trace) + # Split by the first colon followed by some digits, which works for both + # Windows and Unix path styles. + file, line = trace.match(/^(.+?):(\d+).*$/, &:captures) || trace + [file, line.to_i] + end - def expand_backtrace - @exception.backtrace.unshift( - @exception.to_s.split("\n") - ).flatten! - end + def expand_backtrace + @exception.backtrace.unshift( + @exception.to_s.split("\n") + ).flatten! + end end end diff --git a/actionpack/lib/action_dispatch/middleware/executor.rb b/actionpack/lib/action_dispatch/middleware/executor.rb index 06245b403b..3d43f97a2b 100644 --- a/actionpack/lib/action_dispatch/middleware/executor.rb +++ b/actionpack/lib/action_dispatch/middleware/executor.rb @@ -1,4 +1,4 @@ -require 'rack/body_proxy' +require "rack/body_proxy" module ActionDispatch class Executor diff --git a/actionpack/lib/action_dispatch/middleware/flash.rb b/actionpack/lib/action_dispatch/middleware/flash.rb index 80703940ed..cbe2f4be4d 100644 --- a/actionpack/lib/action_dispatch/middleware/flash.rb +++ b/actionpack/lib/action_dispatch/middleware/flash.rb @@ -1,4 +1,4 @@ -require 'active_support/core_ext/hash/keys' +require "active_support/core_ext/hash/keys" module ActionDispatch # The flash provides a way to pass temporary primitive-types (String, Array, Hash) between actions. Anything you place in the flash will be exposed @@ -36,7 +36,7 @@ module ActionDispatch # # See docs on the FlashHash class for more details about the flash. class Flash - KEY = 'action_dispatch.request.flash_hash'.freeze + KEY = "action_dispatch.request.flash_hash".freeze module RequestMethods # Access the contents of the flash. Use <tt>flash["notice"]</tt> to @@ -60,14 +60,14 @@ module ActionDispatch session = self.session || {} flash_hash = self.flash_hash - if flash_hash && (flash_hash.present? || session.key?('flash')) + if flash_hash && (flash_hash.present? || session.key?("flash")) session["flash"] = flash_hash.to_session_value self.flash = flash_hash.dup end if (!session.respond_to?(:loaded?) || session.loaded?) && # (reset_session uses {}, which doesn't implement #loaded?) - session.key?('flash') && session['flash'].nil? - session.delete('flash') + session.key?("flash") && session["flash"].nil? + session.delete("flash") end end @@ -118,8 +118,8 @@ module ActionDispatch end new(flashes, flashes.keys) when Hash # Rails 4.0 - flashes = value['flashes'] - if discard = value['discard'] + flashes = value["flashes"] + if discard = value["discard"] flashes.except!(*discard) end new(flashes, flashes.keys) @@ -129,11 +129,11 @@ module ActionDispatch end # Builds a hash containing the flashes to keep for the next request. - # If there are none to keep, returns nil. + # If there are none to keep, returns +nil+. def to_session_value #:nodoc: flashes_to_keep = @flashes.except(*@discard) return nil if flashes_to_keep.empty? - { 'discard' => [], 'flashes' => flashes_to_keep } + { "discard" => [], "flashes" => flashes_to_keep } end def initialize(flashes = {}, discard = []) #:nodoc: @@ -277,15 +277,16 @@ module ActionDispatch end protected - def now_is_loaded? - @now - end + def now_is_loaded? + @now + end - def stringify_array(array) - array.map do |item| - item.kind_of?(Symbol) ? item.to_s : item + private + def stringify_array(array) # :doc: + array.map do |item| + item.kind_of?(Symbol) ? item.to_s : item + end end - end end def self.new(app) app; end diff --git a/actionpack/lib/action_dispatch/middleware/params_parser.rb b/actionpack/lib/action_dispatch/middleware/params_parser.rb deleted file mode 100644 index faf3262b8f..0000000000 --- a/actionpack/lib/action_dispatch/middleware/params_parser.rb +++ /dev/null @@ -1,46 +0,0 @@ -require 'action_dispatch/http/request' - -module ActionDispatch - # ActionDispatch::ParamsParser works for all the requests having any Content-Length - # (like POST). It takes raw data from the request and puts it through the parser - # that is picked based on Content-Type header. - # - # In case of any error while parsing data ParamsParser::ParseError is raised. - class ParamsParser - # Raised when raw data from the request cannot be parsed by the parser - # defined for request's content mime type. - class ParseError < StandardError - - def initialize(message = nil, original_exception = nil) - if message - ActiveSupport::Deprecation.warn("Passing #message is deprecated and has no effect. " \ - "#{self.class} will automatically capture the message " \ - "of the original exception.", caller) - end - - if original_exception - ActiveSupport::Deprecation.warn("Passing #original_exception is deprecated and has no effect. " \ - "Exceptions will automatically capture the original exception.", caller) - end - - super($!.message) - end - - def original_exception - ActiveSupport::Deprecation.warn("#original_exception is deprecated. Use #cause instead.", caller) - cause - end - end - - # Create a new +ParamsParser+ middleware instance. - # - # The +parsers+ argument can take Hash of parsers where key is identifying - # content mime type, and value is a lambda that is going to process data. - def self.new(app, parsers = {}) - ActiveSupport::Deprecation.warn('ActionDispatch::ParamsParser is deprecated and will be removed in Rails 5.1. Configure the parameter parsing in ActionDispatch::Request.parameter_parsers.') - parsers = parsers.transform_keys { |key| key.respond_to?(:symbol) ? key.symbol : key } - ActionDispatch::Request.parameter_parsers = ActionDispatch::Request::DEFAULT_PARSERS.merge(parsers) - app - end - end -end diff --git a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb index 0f27984550..46f0f675b9 100644 --- a/actionpack/lib/action_dispatch/middleware/public_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/public_exceptions.rb @@ -20,36 +20,36 @@ module ActionDispatch request = ActionDispatch::Request.new(env) status = request.path_info[1..-1].to_i content_type = request.formats.first - body = { :status => status, :error => Rack::Utils::HTTP_STATUS_CODES.fetch(status, Rack::Utils::HTTP_STATUS_CODES[500]) } + body = { status: status, error: Rack::Utils::HTTP_STATUS_CODES.fetch(status, Rack::Utils::HTTP_STATUS_CODES[500]) } render(status, content_type, body) end private - def render(status, content_type, body) - format = "to_#{content_type.to_sym}" if content_type - if format && body.respond_to?(format) - render_format(status, content_type, body.public_send(format)) - else - render_html(status) + def render(status, content_type, body) + format = "to_#{content_type.to_sym}" if content_type + if format && body.respond_to?(format) + render_format(status, content_type, body.public_send(format)) + else + render_html(status) + end end - end - def render_format(status, content_type, body) - [status, {'Content-Type' => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}", - 'Content-Length' => body.bytesize.to_s}, [body]] - end + def render_format(status, content_type, body) + [status, { "Content-Type" => "#{content_type}; charset=#{ActionDispatch::Response.default_charset}", + "Content-Length" => body.bytesize.to_s }, [body]] + end - def render_html(status) - path = "#{public_path}/#{status}.#{I18n.locale}.html" - path = "#{public_path}/#{status}.html" unless (found = File.exist?(path)) + def render_html(status) + path = "#{public_path}/#{status}.#{I18n.locale}.html" + path = "#{public_path}/#{status}.html" unless (found = File.exist?(path)) - if found || File.exist?(path) - render_format(status, 'text/html', File.read(path)) - else - [404, { "X-Cascade" => "pass" }, []] + if found || File.exist?(path) + render_format(status, "text/html", File.read(path)) + else + [404, { "X-Cascade" => "pass" }, []] + end end - end end end diff --git a/actionpack/lib/action_dispatch/middleware/reloader.rb b/actionpack/lib/action_dispatch/middleware/reloader.rb index 112bde6596..90c64037aa 100644 --- a/actionpack/lib/action_dispatch/middleware/reloader.rb +++ b/actionpack/lib/action_dispatch/middleware/reloader.rb @@ -43,10 +43,10 @@ module ActionDispatch class << self attr_accessor :default_reloader # :nodoc: - deprecate to_prepare: 'use ActiveSupport::Reloader.to_prepare instead', - to_cleanup: 'use ActiveSupport::Reloader.to_complete instead', - prepare!: 'use Rails.application.reloader.prepare! instead', - cleanup!: 'use Rails.application.reloader.reload! instead of cleanup + prepare' + deprecate to_prepare: "use ActiveSupport::Reloader.to_prepare instead", + to_cleanup: "use ActiveSupport::Reloader.to_complete instead", + prepare!: "use Rails.application.reloader.prepare! instead", + cleanup!: "use Rails.application.reloader.reload! instead of cleanup + prepare" end self.default_reloader = ActiveSupport::Reloader diff --git a/actionpack/lib/action_dispatch/middleware/remote_ip.rb b/actionpack/lib/action_dispatch/middleware/remote_ip.rb index 31b75498b6..9f1ae80b97 100644 --- a/actionpack/lib/action_dispatch/middleware/remote_ip.rb +++ b/actionpack/lib/action_dispatch/middleware/remote_ip.rb @@ -1,4 +1,4 @@ -require 'ipaddr' +require "ipaddr" module ActionDispatch # This middleware calculates the IP address of the remote client that is @@ -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,13 +171,11 @@ module ActionDispatch end end - def filter_proxies(ips) + def filter_proxies(ips) # :doc: ips.reject do |ip| @proxies.any? { |proxy| proxy === ip } end end - end - end end diff --git a/actionpack/lib/action_dispatch/middleware/request_id.rb b/actionpack/lib/action_dispatch/middleware/request_id.rb index 1555ff72af..1925ffd9dd 100644 --- a/actionpack/lib/action_dispatch/middleware/request_id.rb +++ b/actionpack/lib/action_dispatch/middleware/request_id.rb @@ -1,9 +1,10 @@ -require 'securerandom' -require 'active_support/core_ext/string/access' +require "securerandom" +require "active_support/core_ext/string/access" module ActionDispatch - # Makes a unique request id available to the action_dispatch.request_id env variable (which is then accessible through - # ActionDispatch::Request#uuid or the alias ActionDispatch::Request#request_id) and sends the same id to the client via the X-Request-Id header. + # Makes a unique request id available to the +action_dispatch.request_id+ env variable (which is then accessible + # through <tt>ActionDispatch::Request#request_id</tt> or the alias <tt>ActionDispatch::Request#uuid</tt>) and sends + # the same id to the client via the X-Request-Id header. # # The unique request id is either based on the X-Request-Id header in the request, which would typically be generated # by a firewall, load balancer, or the web server, or, if this header is not available, a random uuid. If the @@ -12,7 +13,7 @@ module ActionDispatch # The unique request id can be used to trace a request end-to-end and would typically end up being part of log files # from multiple pieces of the stack. class RequestId - X_REQUEST_ID = "X-Request-Id".freeze # :nodoc: + X_REQUEST_ID = "X-Request-Id".freeze #:nodoc: def initialize(app) @app = app diff --git a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb index 5fb5953811..97c937b0b1 100644 --- a/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/abstract_store.rb @@ -1,34 +1,23 @@ -require 'rack/utils' -require 'rack/request' -require 'rack/session/abstract/id' -require 'action_dispatch/middleware/cookies' -require 'action_dispatch/request/session' +require "rack/utils" +require "rack/request" +require "rack/session/abstract/id" +require "action_dispatch/middleware/cookies" +require "action_dispatch/request/session" module ActionDispatch module Session class SessionRestoreError < StandardError #:nodoc: - - def initialize(const_error = nil) - if const_error - ActiveSupport::Deprecation.warn("Passing #original_exception is deprecated and has no effect. " \ - "Exceptions will automatically capture the original exception.", caller) - end - + def initialize super("Session contains objects whose class definition isn't available.\n" + "Remember to require the classes for all objects kept in the session.\n" + "(Original exception: #{$!.message} [#{$!.class}])\n") set_backtrace $!.backtrace end - - def original_exception - ActiveSupport::Deprecation.warn("#original_exception is deprecated. Use #cause instead.", caller) - cause - end end module Compatibility def initialize(app, options = {}) - options[:key] ||= '_session_id' + options[:key] ||= "_session_id" super end @@ -38,14 +27,13 @@ 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 @@ -94,9 +82,9 @@ module ActionDispatch private - def set_cookie(request, session_id, cookie) - request.cookie_jar[key] = cookie - end + def set_cookie(request, session_id, cookie) + request.cookie_jar[key] = cookie + end end end end diff --git a/actionpack/lib/action_dispatch/middleware/session/cache_store.rb b/actionpack/lib/action_dispatch/middleware/session/cache_store.rb index 589ae46e38..71274bc13a 100644 --- a/actionpack/lib/action_dispatch/middleware/session/cache_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/cache_store.rb @@ -1,4 +1,4 @@ -require 'action_dispatch/middleware/session/abstract_store' +require "action_dispatch/middleware/session/abstract_store" module ActionDispatch module Session @@ -19,7 +19,7 @@ module ActionDispatch # Get a session from the cache. def find_session(env, sid) - unless sid and session = @cache.read(cache_key(sid)) + unless sid && (session = @cache.read(cache_key(sid))) sid, session = generate_sid, {} end [sid, session] @@ -29,7 +29,7 @@ module ActionDispatch def write_session(env, sid, session, options) key = cache_key(sid) if session - @cache.write(key, session, :expires_in => options[:expire_after]) + @cache.write(key, session, expires_in: options[:expire_after]) else @cache.delete(key) end diff --git a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb index dec9c60ef2..57d325a9d8 100644 --- a/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/cookie_store.rb @@ -1,6 +1,6 @@ -require 'active_support/core_ext/hash/keys' -require 'action_dispatch/middleware/session/abstract_store' -require 'rack/session/cookie' +require "active_support/core_ext/hash/keys" +require "action_dispatch/middleware/session/abstract_store" +require "rack/session/cookie" module ActionDispatch module Session @@ -63,8 +63,8 @@ module ActionDispatch # Other useful options include <tt>:key</tt>, <tt>:secure</tt> and # <tt>:httponly</tt>. class CookieStore < AbstractStore - def initialize(app, options={}) - super(app, options.merge!(:cookie_only => true)) + def initialize(app, options = {}) + super(app, options.merge!(cookie_only: true)) end def delete_session(req, session_id, options) @@ -84,46 +84,46 @@ module ActionDispatch private - def extract_session_id(req) - stale_session_check! do - unpacked_cookie_data(req)["session_id"] + def extract_session_id(req) + stale_session_check! do + unpacked_cookie_data(req)["session_id"] + end end - end - def unpacked_cookie_data(req) - req.fetch_header("action_dispatch.request.unsigned_session_cookie") do |k| - v = stale_session_check! do - if data = get_cookie(req) - data.stringify_keys! + def unpacked_cookie_data(req) + req.fetch_header("action_dispatch.request.unsigned_session_cookie") do |k| + v = stale_session_check! do + if data = get_cookie(req) + data.stringify_keys! + end + data || {} end - data || {} + req.set_header k, v end - req.set_header k, v end - end - def persistent_session_id!(data, sid=nil) - data ||= {} - data["session_id"] ||= sid || generate_sid - data - end + def persistent_session_id!(data, sid = nil) + data ||= {} + data["session_id"] ||= sid || generate_sid + data + end - def write_session(req, sid, session_data, options) - session_data["session_id"] = sid - session_data - end + def write_session(req, sid, session_data, options) + session_data["session_id"] = sid + session_data + end - def set_cookie(request, session_id, cookie) - cookie_jar(request)[@key] = cookie - end + def set_cookie(request, session_id, cookie) + cookie_jar(request)[@key] = cookie + end - def get_cookie(req) - cookie_jar(req)[@key] - end + def get_cookie(req) + cookie_jar(req)[@key] + end - def cookie_jar(request) - request.cookie_jar.signed_or_encrypted - end + def cookie_jar(request) + request.cookie_jar.signed_or_encrypted + end end end end diff --git a/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb b/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb index cb19786f0b..ee2b1f26ad 100644 --- a/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb +++ b/actionpack/lib/action_dispatch/middleware/session/mem_cache_store.rb @@ -1,6 +1,6 @@ -require 'action_dispatch/middleware/session/abstract_store' +require "action_dispatch/middleware/session/abstract_store" begin - require 'rack/session/dalli' + require "rack/session/dalli" rescue LoadError => e $stderr.puts "You don't have dalli installed in your application. Please add it to your Gemfile and run bundle install" raise e diff --git a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb index 64695f9738..90f26a1c33 100644 --- a/actionpack/lib/action_dispatch/middleware/show_exceptions.rb +++ b/actionpack/lib/action_dispatch/middleware/show_exceptions.rb @@ -1,5 +1,5 @@ -require 'action_dispatch/http/request' -require 'action_dispatch/middleware/exception_wrapper' +require "action_dispatch/http/request" +require "action_dispatch/middleware/exception_wrapper" module ActionDispatch # This middleware rescues any exception returned by the application @@ -15,7 +15,7 @@ module ActionDispatch # If any exception happens inside the exceptions app, this middleware # catches the exceptions and returns a FAILSAFE_RESPONSE. class ShowExceptions - FAILSAFE_RESPONSE = [500, { 'Content-Type' => 'text/plain' }, + FAILSAFE_RESPONSE = [500, { "Content-Type" => "text/plain" }, ["500 Internal Server Error\n" \ "If you are the administrator of this website, then please read this web " \ "application's log file and/or the web server's log file to find out what " \ @@ -39,22 +39,22 @@ module ActionDispatch private - def render_exception(request, exception) - backtrace_cleaner = request.get_header 'action_dispatch.backtrace_cleaner' - wrapper = ExceptionWrapper.new(backtrace_cleaner, exception) - status = wrapper.status_code - request.set_header "action_dispatch.exception", wrapper.exception - request.set_header "action_dispatch.original_path", request.path_info - request.path_info = "/#{status}" - response = @exceptions_app.call(request.env) - response[1]['X-Cascade'] == 'pass' ? pass_response(status) : response - rescue Exception => failsafe_error - $stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}" - FAILSAFE_RESPONSE - end + def render_exception(request, exception) + backtrace_cleaner = request.get_header "action_dispatch.backtrace_cleaner" + wrapper = ExceptionWrapper.new(backtrace_cleaner, exception) + status = wrapper.status_code + request.set_header "action_dispatch.exception", wrapper.exception + request.set_header "action_dispatch.original_path", request.path_info + request.path_info = "/#{status}" + response = @exceptions_app.call(request.env) + response[1]["X-Cascade"] == "pass" ? pass_response(status) : response + rescue Exception => failsafe_error + $stderr.puts "Error during failsafe response: #{failsafe_error}\n #{failsafe_error.backtrace * "\n "}" + FAILSAFE_RESPONSE + end - def pass_response(status) - [status, {"Content-Type" => "text/html; charset=#{Response.default_charset}", "Content-Length" => "0"}, []] - end + def pass_response(status) + [status, { "Content-Type" => "text/html; charset=#{Response.default_charset}", "Content-Length" => "0" }, []] + end end end diff --git a/actionpack/lib/action_dispatch/middleware/ssl.rb b/actionpack/lib/action_dispatch/middleware/ssl.rb index ab3077b308..557721c301 100644 --- a/actionpack/lib/action_dispatch/middleware/ssl.rb +++ b/actionpack/lib/action_dispatch/middleware/ssl.rb @@ -18,9 +18,9 @@ module ActionDispatch # Enabled by default. Configure `config.ssl_options` with `hsts: false` to disable. # # Set `config.ssl_options` with `hsts: { … }` to configure HSTS: - # * `expires`: How long, in seconds, these settings will stick. Defaults to - # `180.days` (recommended). The minimum required to qualify for browser - # preload lists is `18.weeks`. + # * `expires`: How long, in seconds, these settings will stick. The minimum + # required to qualify for browser preload lists is `18.weeks`. Defaults to + # `180.days` (recommended). # * `subdomains`: Set to `true` to tell the browser to apply these settings # to all subdomains. This protects your cookies from interception by a # vulnerable site on a subdomain. Defaults to `true`. @@ -29,6 +29,7 @@ module ActionDispatch # first visit* since it hasn't seen your HSTS header yet. To close this # gap, browser vendors include a baked-in list of HSTS-enabled sites. # Go to https://hstspreload.appspot.com to submit your site for inclusion. + # Defaults to `false`. # # To turn off HSTS, omitting the header is not enough. Browsers will remember the # original HSTS directive until it expires. Instead, use the header to tell browsers to @@ -44,35 +45,17 @@ module ActionDispatch HSTS_EXPIRES_IN = 15552000 def self.default_hsts_options - { expires: HSTS_EXPIRES_IN, subdomains: false, preload: false } + { expires: HSTS_EXPIRES_IN, subdomains: true, preload: false } end - def initialize(app, redirect: {}, hsts: {}, secure_cookies: true, **options) + def initialize(app, redirect: {}, hsts: {}, secure_cookies: true) @app = app - if options[:host] || options[:port] - ActiveSupport::Deprecation.warn <<-end_warning.strip_heredoc - The `:host` and `:port` options are moving within `:redirect`: - `config.ssl_options = { redirect: { host: …, port: … } }`. - end_warning - @redirect = options.slice(:host, :port) - else - @redirect = redirect - end + @redirect = redirect @exclude = @redirect && @redirect[:exclude] || proc { !@redirect } @secure_cookies = secure_cookies - if hsts != true && hsts != false && hsts[:subdomains].nil? - hsts[:subdomains] = false - - ActiveSupport::Deprecation.warn <<-end_warning.strip_heredoc - In Rails 5.1, The `:subdomains` option of HSTS config will be treated as true if - unspecified. Set `config.ssl_options = { hsts: { subdomains: false } }` to opt out - of this behavior. - end_warning - end - @hsts_header = build_hsts_header(normalize_hsts_options(hsts)) end @@ -92,7 +75,7 @@ module ActionDispatch private def set_hsts_header!(headers) - headers['Strict-Transport-Security'.freeze] ||= @hsts_header + headers["Strict-Transport-Security".freeze] ||= @hsts_header end def normalize_hsts_options(options) @@ -118,10 +101,10 @@ module ActionDispatch end def flag_cookies_as_secure!(headers) - if cookies = headers['Set-Cookie'.freeze] + if cookies = headers["Set-Cookie".freeze] cookies = cookies.split("\n".freeze) - headers['Set-Cookie'.freeze] = cookies.map { |cookie| + headers["Set-Cookie".freeze] = cookies.map { |cookie| if cookie !~ /;\s*secure\s*(;|$)/i "#{cookie}; secure" else @@ -132,12 +115,20 @@ module ActionDispatch end def redirect_to_https(request) - [ @redirect.fetch(:status, 301), - { 'Content-Type' => 'text/html', - 'Location' => https_location_for(request) }, + [ @redirect.fetch(:status, redirection_status(request)), + { "Content-Type" => "text/html", + "Location" => https_location_for(request) }, @redirect.fetch(:body, []) ] end + def redirection_status(request) + if request.get? || request.head? + 301 # Issue a permanent redirect via a GET request. + else + 307 # Issue a fresh request redirect to preserve the HTTP method. + end + end + def https_location_for(request) host = @redirect[:host] || request.host port = @redirect[:port] || request.port diff --git a/actionpack/lib/action_dispatch/middleware/stack.rb b/actionpack/lib/action_dispatch/middleware/stack.rb index 0b4bee5462..6949b31e75 100644 --- a/actionpack/lib/action_dispatch/middleware/stack.rb +++ b/actionpack/lib/action_dispatch/middleware/stack.rb @@ -88,7 +88,6 @@ module ActionDispatch end def delete(target) - target = get_class target middlewares.delete_if { |m| m.klass == target } end @@ -102,32 +101,14 @@ module ActionDispatch private - def assert_index(index, where) - index = get_class index - i = index.is_a?(Integer) ? index : middlewares.index { |m| m.klass == index } - raise "No such middleware to insert #{where}: #{index.inspect}" unless i - i - end - - def get_class(klass) - if klass.is_a?(String) || klass.is_a?(Symbol) - classcache = ActiveSupport::Dependencies::Reference - converted_klass = classcache[klass.to_s] - ActiveSupport::Deprecation.warn <<-eowarn -Passing strings or symbols to the middleware builder is deprecated, please change -them to actual class references. For example: - - "#{klass}" => #{converted_klass} - - eowarn - converted_klass - else - klass + def assert_index(index, where) + i = index.is_a?(Integer) ? index : middlewares.index { |m| m.klass == index } + raise "No such middleware to insert #{where}: #{index.inspect}" unless i + i end - end - def build_middleware(klass, args, block) - Middleware.new(get_class(klass), args, block) - end + def build_middleware(klass, args, block) + Middleware.new(klass, args, block) + end end end diff --git a/actionpack/lib/action_dispatch/middleware/static.rb b/actionpack/lib/action_dispatch/middleware/static.rb index 2c5721dc22..5c71f0fc48 100644 --- a/actionpack/lib/action_dispatch/middleware/static.rb +++ b/actionpack/lib/action_dispatch/middleware/static.rb @@ -1,5 +1,5 @@ -require 'rack/utils' -require 'active_support/core_ext/uri' +require "rack/utils" +require "active_support/core_ext/uri" module ActionDispatch # This middleware returns a file's contents from disk in the body response. @@ -13,8 +13,8 @@ module ActionDispatch # located at `public/assets/application.js` if the file exists. If the file # does not exist, a 404 "File not Found" response will be returned. class FileHandler - def initialize(root, index: 'index', headers: {}) - @root = root.chomp('/') + def initialize(root, index: "index", headers: {}) + @root = root.chomp("/") @file_server = ::Rack::File.new(@root, headers) @index = index end @@ -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("UTF-8".freeze)) begin File.file?(path) && File.readable?(path) rescue SystemCallError @@ -46,7 +46,7 @@ module ActionDispatch end def call(env) - serve ActionDispatch::Request.new env + serve(Rack::Request.new(env)) end def serve(request) @@ -59,13 +59,13 @@ module ActionDispatch if status == 304 return [status, headers, body] end - headers['Content-Encoding'] = 'gzip' - headers['Content-Type'] = content_type(path) + headers["Content-Encoding"] = "gzip" + headers["Content-Type"] = content_type(path) else status, headers, body = @file_server.call(request.env) end - headers['Vary'] = 'Accept-Encoding' if gzip_path + headers["Vary"] = "Accept-Encoding" if gzip_path return [status, headers, body] ensure @@ -78,11 +78,11 @@ module ActionDispatch end def content_type(path) - ::Rack::Mime.mime_type(::File.extname(path), 'text/plain'.freeze) + ::Rack::Mime.mime_type(::File.extname(path), "text/plain".freeze) end def gzip_encoding_accepted?(request) - request.accept_encoding =~ /\bgzip\b/i + request.accept_encoding.any? { |enc, quality| enc =~ /\bgzip\b/i } end def gzip_file_path(path) @@ -106,23 +106,16 @@ module ActionDispatch # produce a directory traversal using this middleware. Only 'GET' and 'HEAD' # requests will result in a file being returned. class Static - def initialize(app, path, deprecated_cache_control = :not_set, index: 'index', headers: {}) - if deprecated_cache_control != :not_set - ActiveSupport::Deprecation.warn("The `cache_control` argument is deprecated," \ - "replaced by `headers: { 'Cache-Control' => #{deprecated_cache_control} }`, " \ - " and will be removed in Rails 5.1.") - headers['Cache-Control'.freeze] = deprecated_cache_control - end - + def initialize(app, path, index: "index", headers: {}) @app = app @file_handler = FileHandler.new(path, index: index, headers: headers) end def call(env) - req = ActionDispatch::Request.new env + req = Rack::Request.new env if req.get? || req.head? - path = req.path_info.chomp('/'.freeze) + path = req.path_info.chomp("/".freeze) if match = @file_handler.match?(path) req.path_info = match return @file_handler.serve(req) |