Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Last active August 29, 2015 14:00
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 JoshCheek/8a8836a4a171f11013bb to your computer and use it in GitHub Desktop.
Save JoshCheek/8a8836a4a171f11013bb to your computer and use it in GitHub Desktop.
A middleware I wrote to redirect requests to the herokuapp domain over to apply.turing.io
class YouKnowWeHaveASubdomainNowMiddleware
MovedPermanentlyCode = 301
def initialize(app, attributes)
self.app = app
self.from = attributes.fetch :from
self.to = attributes.fetch :to
end
def call(env)
request = Rack::Request.new(env)
if request.base_url == from
location = to + request.path
[MovedPermanentlyCode, {"Location" => location}, []]
else
app.call env
end
end
private
attr_accessor :app, :from, :to
end
require_relative '../test_helper'
class YouKnowWeHaveASubdomainNowMiddlewareTest < Minitest::Test
def app
@app ||= ->(env) { [200, env, "app"] }
end
FROM = 'http://asquared.herokuapp.com'
TO = 'http://apply.turing.io'
def middleware
@middleware ||= YouKnowWeHaveASubdomainNowMiddleware.new(app, from: FROM, to: TO)
end
def env_for(url, opts={})
Rack::MockRequest.env_for(url, opts)
end
def test_redirects_from_FROM_to_TO
code, headers = middleware.call env_for "#{FROM}/some/path"
assert_equal 301, code
assert_equal "#{TO}/some/path", headers['Location']
end
def test_does_not_redirect_if_from_is_not_FROM
code, headers, message = middleware.call env_for "#{TO}/some/path"
assert_equal 200, code
assert_equal 'app', message
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment