Class: Rack::Subdomain

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/subdomain.rb,
lib/rack/subdomain/version.rb

Constant Summary collapse

VERSION =
'0.5.0'

Instance Method Summary collapse

Constructor Details

#initialize(app, domain, options = {}, &block) ⇒ Subdomain

Returns a new instance of Subdomain.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/rack/subdomain.rb', line 5

def initialize(app, domain, options = {}, &block)
  # Maintain compatibility with previous rack-subdomain gem
  options = {to: options} if options.is_a? String

  @options = {except: ['', 'www']}.merge(options)

  @app = app
  @domain = domain
  @mappings = {}

  if @options[:to]
    map('*', @options[:to])
  elsif block_given?
    instance_eval &block
  else
    raise ArgumentError, "missing `:to` option or block to define mapping"
  end
end

Instance Method Details

#call(env) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/rack/subdomain.rb', line 24

def call(env)
  @env = env
  @subdomain = subdomain

  if @subdomain && !@subdomain.empty? && !@options[:except].include?(@subdomain)
    pattern, route = @mappings.detect do |pattern, route|
      pattern === subdomain
    end

    if route
      remap_with_substituted_path!(route.gsub(/\:subdomain/, @subdomain))
    end
  end

  @app.call(env)
end

#map(pattern, route) ⇒ Object

Raises:

  • (ArgumentError)


41
42
43
44
45
46
47
48
# File 'lib/rack/subdomain.rb', line 41

def map(pattern, route)
  map(pattern, route[:to]) and return if route.kind_of?(Hash)
  raise ArgumentError, "missing route" unless route

  pattern = /.*/ if pattern == '*'
  regexp = Regexp.new(pattern)
  @mappings[regexp] = route
end