class Ballast::Middlewares::DefaultHost

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

Public Class Methods

new(app, path) click to toggle source

Creates a new middleware instance.

@param app [Object] A Rack application. @param path [String] The path of a YAML file with default hosts definition per environment.

# File lib/ballast/middlewares/default_host.rb, line 15
def initialize(app, path)
  @app = app
  @hosts = YAML.load_file(path)
end

Public Instance Methods

call(env) click to toggle source

Executes the middleware.

@param env [Hash] A Rack environment.

# 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