Class: Low::Rack::SubdomainMap

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

Overview

‘SubdomainMap` is Rack middleware that delegates to other Rack apps based upon subdomain. It takes two arguments upon initialization:

  • ‘base`, the app to be called if there is no subdomain.

  • ‘map`, a hash that maps subdomain strings to apps.

Instance Method Summary collapse

Constructor Details

#initialize(base, map = {}) ⇒ SubdomainMap

Returns a new instance of SubdomainMap.



9
10
11
12
# File 'lib/low/rack/subdomain_map.rb', line 9

def initialize(base, map = {})
  @base = base
  @map = map
end

Instance Method Details

#call(env) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/low/rack/subdomain_map.rb', line 14

def call(env)
  # If the `SERVER_NAME` environment variable has a subdomain
  if env['SERVER_NAME'] =~ /(.*?)\.(?:.*)\..*/
    subdomain = $1
  end

  if subdomain
    # and we can find a corresponding app,
    if app = @map[subdomain]
      # call it and return the result.
      app.call(env)

    # Otherwise, return 403 Forbidden.
    else
      [403, {"Content-Type" => "text/plain"}, []]
    end

  # If there is no subdomain,
  else
    # call the base app and return the result.
    @base.call(env)
  end
end