class Browser::Middleware
def assets?(request)
def assets?(request) request.path.match(ASSETS_REGEX) end
def call(env)
def call(env) request = Rack::Request.new(env) # Only apply verification on HTML requests. # This ensures that images, CSS and JavaScript # will be rendered. return run_app(env) unless process?(request) path = catch(:redirected) do Context.new(request).instance_eval(&@block) end # No path, no match. return run_app(env) unless path resolve_redirection(env, request.path, path) end
def html?(request)
def html?(request) request.env["HTTP_ACCEPT"].to_s.match(ACCEPT_REGEX) end
def initialize(app, &block)
def initialize(app, &block) raise ArgumentError, "Browser::Middleware requires a block" unless block @app = app @block = block end
def process?(request)
def process?(request) html?(request) && !assets?(request) end
def redirect(path)
def redirect(path) [302, {"Content-Type" => "text/html", "Location" => path}, []] end
def resolve_redirection(env, current_path, path)
def resolve_redirection(env, current_path, path) uri = URI.parse(path) if uri.path == current_path run_app(env) else redirect(path) end end
def run_app(env)
def run_app(env) @app.call(env) end