Skip to content

Instantly share code, notes, and snippets.

@christhekeele
Last active October 27, 2015 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christhekeele/f56e6512d92ed3af0427 to your computer and use it in GitHub Desktop.
Save christhekeele/f56e6512d92ed3af0427 to your computer and use it in GitHub Desktop.
# FORCE RAILS REDIRECTS TO HONOR CONTENT-TYPE HEADERS
# https://github.com/rails/rails/issues/17194
require 'action_controller/metal/redirecting'
module ActionController
module Redirecting
def redirect_to(options = {}, response_status = {}) #:doc:
raise ActionControllerError.new("Cannot redirect to nil!") unless options
raise ActionControllerError.new("Cannot redirect to a parameter hash!") if options.is_a?(ActionController::Parameters)
raise AbstractController::DoubleRenderError if response_body
self.status = _extract_redirect_to_status(options, response_status)
self.location = _compute_redirect_to_location(request, options)
self.response_body = _compute_response_body_from_content_type(request, location)
end
def _compute_response_body_from_content_type(request, location)
location = ERB::Util.unwrapped_html_escape(location)
case request.content_type
when /html$/
%(<html><body>You are being <a href="#{location}">redirected</a>.</body></html>)
when /^json/
JSON.dump({message: "You are being redirected to #{location}."})
when /^text/
%(You are being redirected to #{location}.)
else; ''; end
end
module_function :_compute_response_body_from_content_type
public :_compute_response_body_from_content_type
end
end
require 'action_dispatch/routing/redirection'
module ActionDispatch
module Routing
class Redirect < Endpoint
def serve(req)
req.check_path_parameters!
uri = URI.parse(path(req.path_parameters, req))
unless uri.host
if relative_path?(uri.path)
uri.path = "#{req.script_name}/#{uri.path}"
elsif uri.path.empty?
uri.path = req.script_name.empty? ? "/" : req.script_name
end
end
uri.scheme ||= req.scheme
uri.host ||= req.host
uri.port ||= req.port unless req.standard_port?
body = ActionController::Redirecting._compute_response_body_from_content_type(req, uri.to_s)
headers = {
'Location' => uri.to_s,
'Content-Type' => req.content_type,
'Content-Length' => body.length.to_s
}
[ status, headers, [body] ]
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment