Class: Rack::Domain

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

Overview

This Rack middleware allows to intercept requests and route them to different apps based on the domain (full, with subdomains and the TLD).

Examples:

Using a regexp

# Match the 'lobster' subdomain.
use Rack::Domain, /^lobster\./, run: Rack::Lobster.new

Using a string

# Match only if the current domain is github.com:
use Rack::Domain, 'github.com', run: MyGitHubClone

Using an array of strings and regexps

use Rack::Domain, ['lobst.er', /^lobster\./], run: Rack::Lobster.new

Using an on-the-fly app build with a Rack::Builder block:

use Rack::Domain, /^api/ do
  use Rack::Logger
  run MyApi
end

Constant Summary collapse

VERSION =

The version of this gem.

'1.0.0'

Instance Method Summary collapse

Constructor Details

#initialize(next_app, filter, opts = {}, &block) ⇒ Domain

Create a new instance of this middleware. Note that this method is the method called by Rack::Builder#use.

Parameters:

  • next_app (#call)

    The next app on the stack, filled automatically by Rack when building the middlware chain.

  • filter (String, Regexp, Array<String, Regexp>)

    The filter used to, well, filter the domain. If filter is a String, it will be matched as the entire domain; if it's a regexp, it will be matched as a regexp. If it's an array of strings and regexps, it will match if any of the elements of the array matches the domain as specified above.

  • opts (Hash) (defaults to: {})

    An hash of options.

Options Hash (opts):

  • :run (#call, nil)

    The Rack app to run if the domain matches the filter. If you don't want to pass a ready application, you can pass a block with Rack::Builder syntax which will create a Rack app on-the-fly.

Raises:

  • (ArgumentError)

    if both a building block and an app to run were passed to this function.



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

def initialize(next_app, filter, opts = {}, &block)
  if opts[:run] && block_given?
    fail ArgumentError, 'Pass either an app to run or a block, not both'
  end

  @next_app = next_app
  @filter = filter
  @app_to_run = opts[:run]
  @dsl_block = block
end

Instance Method Details

#call(env) ⇒ Object

The call method as per the Rack middleware specification.

Parameters:

  • env (Hash)

    The environment passed around in the middlware chain.



54
55
56
57
58
# File 'lib/rack/domain.rb', line 54

def call(env)
  @domain = Rack::Request.new(env).host
  app = domain_matches? ? app_or_dsl_block : @next_app
  app.call(env)
end