Class: Paquette::SubdomainRouter

Inherits:
Object
  • Object
show all
Defined in:
lib/paquette/subdomain_router.rb

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ SubdomainRouter

Returns a new instance of SubdomainRouter.



6
7
8
9
10
11
12
13
# File 'lib/paquette/subdomain_router.rb', line 6

def initialize(&block)
  @mappings = {}
  @fallback = nil

  if block_given?
    block.call(self)
  end
end

Instance Method Details

#call(env) ⇒ Object



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

def call(env)
  request = Rack::Request.new(env)
  host = request.host

  # Extract subdomain from host
  subdomain = extract_subdomain(host)

  if subdomain && @mappings[subdomain]
    app = @mappings[subdomain]
    if app.respond_to?(:call)
      app.call(env)
    else
      # If it's a class, instantiate it
      app.new.call(env)
    end
  elsif @fallback
    @fallback.call(env)
  else
    [404, {}, ["Subdomain not found"]]
  end
end

#fallback(to:) ⇒ Object



41
42
43
# File 'lib/paquette/subdomain_router.rb', line 41

def fallback(to:)
  @fallback = to
end

#map(subdomain, to:) ⇒ Object



37
38
39
# File 'lib/paquette/subdomain_router.rb', line 37

def map(subdomain, to:)
  @mappings[subdomain] = to
end