Class: ActionDispatch::FileHandler

Inherits:
Object
  • Object
show all
Defined in:
lib/action_dispatch/middleware/static.rb

Overview

Action Dispatch FileHandler

This endpoint serves static files from disk using Rack::Files.

URL paths are matched with static files according to expected conventions: path, path.html, path/index.html.

Precompressed versions of these files are checked first. Brotli (.br) and gzip (.gz) files are supported. If path.br exists, this endpoint returns that file with a content-encoding: br header.

If no matching file is found, this endpoint responds 404 Not Found.

Pass the root directory to search for matching files, an optional index: "index" to change the default path/index.html, and optional additional response headers.

Constant Summary collapse

PRECOMPRESSED =

Accept-Encoding value -> file extension

{
  "br" => ".br",
  "gzip" => ".gz",
  "identity" => nil
}

Instance Method Summary collapse

Constructor Details

#initialize(root, index: "index", headers: {}, precompressed: %i[ br gzip ], compressible_content_types: /\A(?:text\/|application\/javascript)/) ⇒ FileHandler

Returns a new instance of FileHandler.



53
54
55
56
57
58
59
60
61
# File 'lib/action_dispatch/middleware/static.rb', line 53

def initialize(root, index: "index", headers: {}, precompressed: %i[ br gzip ], compressible_content_types: /\A(?:text\/|application\/javascript)/)
  @root = root.chomp("/").b
  @index = index

  @precompressed = Array(precompressed).map(&:to_s) | %w[ identity ]
  @compressible_content_types = compressible_content_types

  @file_server = ::Rack::Files.new(@root, headers)
end

Instance Method Details

#attempt(env) ⇒ Object



67
68
69
70
71
72
73
74
75
# File 'lib/action_dispatch/middleware/static.rb', line 67

def attempt(env)
  request = Rack::Request.new env

  if request.get? || request.head?
    if found = find_file(request.path_info, accept_encoding: request.accept_encoding)
      serve request, *found
    end
  end
end

#call(env) ⇒ Object



63
64
65
# File 'lib/action_dispatch/middleware/static.rb', line 63

def call(env)
  attempt(env) || @file_server.call(env)
end