class Bjork::TryStatic

The Bjork::TryStatic middleware delegates requests to Rack::Static middleware trying to match a static file

Examples

use Bjork::TryStatic,

:root => "public",  # static files root dir
:urls => %w[/],     # match all requests
:try => ['.html', 'index.html', '/index.html'] # try these postfixes sequentially

uses same options as Rack::Static with extra :try option which is an array
of postfixes to find desired file

Public Class Methods

new(app, options) click to toggle source
# File lib/bjork/try_static.rb, line 18
def initialize(app, options)
  @app = app
  @try = ['', *options[:try]]
  @static = ::Rack::Static.new(
    lambda { |_| [404, {}, []] },
    options
  )
end

Public Instance Methods

call(env) click to toggle source
# File lib/bjork/try_static.rb, line 27
def call(env)
  # TODO: Should we skip for all non-GET methods?
  # Skip for POST
  return @app.call(env) if env["REQUEST_METHOD"] == "POST"

  orig_path = env['PATH_INFO']
  found = nil

  @try.each do |path|
    resp = @static.call(env.merge!({'PATH_INFO' => orig_path + path}))
    break if 404 != resp[0] && found = resp
  end

  found or @app.call(env.merge!('PATH_INFO' => orig_path))
end