Skip to content

Instantly share code, notes, and snippets.

@mocoso
Created September 26, 2012 09:10
Show Gist options
  • Save mocoso/3786936 to your computer and use it in GitHub Desktop.
Save mocoso/3786936 to your computer and use it in GitHub Desktop.
A rack based 'redirector'

A rack based 'redirector'

require './redirector'
run Redirector.app
source :rubygems
gem 'rack'
gem 'rack-rewrite'
gem 'activesupport'
group :test do
gem 'rspec'
gem 'rack-test'
end
GEM
remote: http://rubygems.org/
specs:
activesupport (3.2.8)
i18n (~> 0.6)
multi_json (~> 1.0)
diff-lcs (1.1.3)
i18n (0.6.1)
multi_json (1.3.6)
rack (1.4.1)
rack-rewrite (1.2.1)
rack-test (0.6.1)
rack (>= 1.0)
rspec (2.11.0)
rspec-core (~> 2.11.0)
rspec-expectations (~> 2.11.0)
rspec-mocks (~> 2.11.0)
rspec-core (2.11.1)
rspec-expectations (2.11.3)
diff-lcs (~> 1.1.3)
rspec-mocks (2.11.3)
PLATFORMS
ruby
DEPENDENCIES
activesupport
rack
rack-rewrite
rack-test
rspec
require 'rack/rewrite'
require 'rack/rewrite/rule'
require 'active_support/core_ext'
# Monkey patch Rack::Rewrite to sprinkle some sugar over 'with_options'
module Rack
class Rewrite
class RuleSet
def domain(domain, &block)
with_options :host => domain, &block
end
end
end
end
module Redirector
def self.app
base_app = lambda { raise 'Request should have been redirected' }
Rack::Rewrite.new(base_app) do
domain %r{wenttojump\.com} do |wenttojump|
wenttojump.r301 %r{(.*)}, 'http://econsultancy.com/jump/london/about/photos'
end
domain %r{jump} do |jump|
jump.r301 %r{(.*)}, 'http://econsultancy.com/jump/london$1'
end
r301 %r{(.*)}, 'http://econsultancy.com$1'
end
end
end
require 'rack/test'
require './redirector'
describe Redirector do
include Rack::Test::Methods
def app
@app = Redirector.app
end
describe 'cometojump.com' do
it { should_redirect 'http://cometojump.com', 'http://econsultancy.com/jump/london/' }
end
describe 'wenttojump.com' do
it { should_redirect 'http://wenttojump.com', 'http://econsultancy.com/jump/london/about/photos' }
end
describe 'e-consultancy.com' do
it { should_redirect 'http://e-consultancy.com/reports', 'http://econsultancy.com/reports' }
end
def should_redirect(source, destination)
get source
follow_redirect!
last_request.url.should == destination
end
end
@lmars
Copy link

lmars commented Sep 26, 2012

Nice 😉

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