Class: Rack::CanonicalHost

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/canonical_host.rb

Constant Summary collapse

VERSION =
0.2

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ CanonicalHost

Returns a new instance of CanonicalHost.



5
6
7
8
9
10
# File 'lib/rack/canonical_host.rb', line 5

def initialize(app, options = {}) 
  @app    = app
  @host   = options.fetch(:host)
  @scheme = options.fetch(:scheme) { 'http' }
  @ignore = options.fetch(:ignore) { [] }
end

Instance Method Details

#call(env) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/rack/canonical_host.rb', line 12

def call(env)
  request = rack_request(env)
  
  if request.host != @host && !@ignore.include?(request.host)
    uri = URI.parse request.url
    uri.host   = @host
    uri.scheme = @scheme

    status  = 301 
    headers = {'Location' => uri.to_s, 'Content-Type' => 'text/plain'}
    body    = ["Redirecting to canonical URL #{uri}"]

    [status, headers, body]
  else 
    @app.call(env)
  end
end