Class: Rack::TryStatic

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/try_static.rb,
lib/rack/try_static/version.rb

Overview

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

Examples

use Rack::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

Constant Summary collapse

VERSION =
"1.1.1"

Instance Method Summary collapse

Constructor Details

#initialize(app, options) ⇒ TryStatic

Returns a new instance of TryStatic.



21
22
23
24
25
26
27
# File 'lib/rack/try_static.rb', line 21

def initialize(app, options)
  @app = app
  @try = ['', *options[:try]]
  @static = ::Rack::Static.new(
    lambda { |_| [404, {}, []] },
    options)
end

Instance Method Details

#call(env) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/rack/try_static.rb', line 29

def call(env)
  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