Class: Rack::CanonicalHost

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

Constant Summary collapse

VERSION =
0.1

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of CanonicalHost.



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

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



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rack/canonical_host.rb', line 18

def call(env)
  @env = env 
  if request_host != @host && !@ignore.include?(request_host)
    uri        = URI.parse ''
    uri.host   = @host
    uri.query  = env['QUERY_STRING'] || ''
    uri.path   = env['REQUEST_PATH'] || ''
    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

#request_hostObject



14
15
16
# File 'lib/rack/canonical_host.rb', line 14

def request_host 
  @env['HTTP_HOST'].split(':').first
end