module Rack class Subdomain def initialize(app, domain, map_to = nil) @domain = domain @app = app @map_to = map_to end def call(env) @env = env subdomain = fetch_subdomain set_params(subdomain) @app.call(env) end def fetch_subdomain subdomain = @env['SERVER_NAME'].sub(/\.?#{@domain}$/,'') ['', 'www'].include?(subdomain) ? nil : subdomain end def set_params(subdomain) request = Rack::Request.new(@env) if subdomain request[:subdomain] = subdomain map_to(subdomain) end end def map_to(subdomain) if @map_to @map_to.gsub!(":subdomain", subdomain) path_info = @env["PATH_INFO"] @env["PATH_INFO"] = "#{@map_to}#{path_info}" end end end end