Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Extendable Metal Redirects
.DS_Store
# Some code and ideas borrowed from https://github.com/p8/redirect
# Add this to the metal folder in a Rails project
# Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
class SpecialRedirects
def self.our_redirects
# example of setting a temp redirect (or other server response code)
[
# ['/test', 'http://www.test.com', {:code => 302}]
# [/\/speaker(\S*)/, "http://speaker.something.com$1"]
# ["http://www.something.com/learn-whatever", "http://www.something.com/Learn-Whatever"]
]
end
def self.fullurl(env)
"http://#{env['SERVER_NAME']}#{env['PATH_INFO']}".downcase
end
class RData
attr_reader :catch_url, :redirect_url, :code, :content_type
def initialize(catch_url, redirect_url, options = {})
@catch_url = catch_url
@redirect_url = redirect_url
@code = options[:code] || default_code
@content_type = options[:content_type] || "text/html"
end
def default_code
301
end
end
def self.call(env)
@redirects ||= our_redirects.collect do |r|
RData.new(*r)
end
@redirects.each do |r|
if fullurl(env).match(r.catch_url)
redirect_url = r.redirect_url
if $1
redirect_url.gsub!('$1', $1)
end
return [r.code, {"Location" => redirect_url, "Content-Type" => r.content_type}, "Redirecting to: #{redirect_url}"]
end
end
[404, {"Content-Type" => "text/html"}, ["Not Found"]]
end
end
Owner

danielberlinger commented Apr 27, 2011

This code could be further extended by storing the array as a set in Redis etc. which would permit redirects to be added without code changes. For us, as of this writing, that was a YAGNI issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment