Class: Ballast::Middlewares::DefaultHost

Inherits:
Object
  • Object
show all
Defined in:
lib/ballast/middlewares/default_host.rb

Overview

Converts the host of an IP based request to the default host.

Instance Method Summary collapse

Constructor Details

#initialize(app, path) ⇒ DefaultHost

Creates a new middleware instance.

Parameters:

  • app (Object)

    A Rack application.

  • path (String)

    The path of a YAML file with default hosts definition per environment.



15
16
17
18
# File 'lib/ballast/middlewares/default_host.rb', line 15

def initialize(app, path)
  @app = app
  @hosts = YAML.load_file(path)
end

Instance Method Details

#call(env) ⇒ Object

Executes the middleware.

Parameters:

  • env (Hash)

    A Rack environment.



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/ballast/middlewares/default_host.rb', line 23

def call(env)
  old_host = env["SERVER_NAME"].ensure_string
  new_host = @hosts[ENV.fetch("RACK_ENV", "production")]

  if old_host =~ /^\d/ && new_host
    env["ORIG_SERVER_NAME"] = old_host
    env["ORIG_HTTP_HOST"] = env["HTTP_HOST"].dup
    env["SERVER_NAME"] = new_host
    env["HTTP_HOST"].gsub!(old_host, new_host)
  end

  @app.call(env)
end