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) new_path_info = "#{@map_to}#{@env["PATH_INFO"]}" @env["PATH_INFO"] = new_path_info new_request_uri = new_path_info.dup if @env["QUERY_STRING"] new_request_uri << "?" << @env["QUERY_STRING"] end @env["REQUEST_URI"] = new_request_uri end end end end