module Sinatra::Subdomain

Constants

SINATRA_V2

Attributes

app[RW]
subdomain[RW]

Public Class Methods

add_condition(last_route, condition) click to toggle source
# File lib/sinatra/subdomain.rb, line 88
def self.add_condition(last_route, condition)
  last_route[1] << condition
end
ip_address?(host) click to toggle source
# File lib/sinatra/subdomain.rb, line 54
def self.ip_address?(host)
  host =~ Resolv::IPv4::Regex || host =~ Resolv::IPv6::Regex
end
match_subdomain?(expected, actual) click to toggle source
# File lib/sinatra/subdomain.rb, line 58
def self.match_subdomain?(expected, actual)
  expected.any? do |expected_subdomain|
    case expected_subdomain
    when true
      !actual.nil?
    when Symbol
      actual.to_s == expected_subdomain.to_s
    else
      expected_subdomain === actual # rubocop:disable Style/CaseEquality
    end
  end
end
registered(app) click to toggle source
# File lib/sinatra/subdomain.rb, line 97
def self.registered(app)
  app.helpers Sinatra::Subdomain::Helpers
  app.set :tld_size, 1
end
route_added(verb, _path, _block) click to toggle source
# File lib/sinatra/subdomain.rb, line 71
def self.route_added(verb, _path, _block)
  return unless subdomain && app

  routes = app.instance_variable_get("@routes")
  last_route = routes[verb].last
  expected = [subdomain].flatten.compact

  condition = app.instance_eval do
    generate_method :subdomain_matcher do
      ::Sinatra::Subdomain.match_subdomain?(expected, subdomain)
    end
  end

  add_condition(last_route, condition)
end

Public Instance Methods

subdomain(expected_subdomain = true) { || ... } click to toggle source

This is how this works:

  1. Whenever you call `subdomain(&block)`, this is the method that's going to be executed.

  2. For each `subdomain` block, we set the app and subdomain condition as `Sinatra::Subdomain.app` and `Sinatra::Subdomain.subdomain`.

  3. Then, we yield the block, which will add the routes as needed.

  4. After each route is added, Sinatra triggers a hook called `:route_added`, handled by the `routed_added` method below.

  5. The `routed_added` method will hijack the routes, adding the subdomain condition.

# File lib/sinatra/subdomain.rb, line 40
def subdomain(expected_subdomain = true)
  ::Sinatra::Subdomain.tap do |mod|
    mod.app = self
    mod.subdomain = expected_subdomain
  end

  yield

  ::Sinatra::Subdomain.tap do |mod|
    mod.app = nil
    mod.subdomain = nil
  end
end