Created
April 27, 2011 20:12
-
-
Save danielberlinger/945080 to your computer and use it in GitHub Desktop.
Extendable Metal Redirects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.DS_Store |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.