Skip to content

Instantly share code, notes, and snippets.

@danielberlinger
Created April 27, 2011 20:12
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 danielberlinger/945080 to your computer and use it in GitHub Desktop.
Save danielberlinger/945080 to your computer and use it in GitHub Desktop.
Extendable Metal Redirects
# 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
@danielberlinger
Copy link
Author

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