Class: Klenod::Rack::AssetApp

Inherits:
Object
  • Object
show all
Defined in:
lib/klenod/rack/asset_app.rb

Constant Summary collapse

CACHE_CONTROL =
"public, max-age=31536000, immutable"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(source, app: nil, assets_dir: nil, path_prefix: "/assets/", base: nil) ⇒ AssetApp

Returns a new instance of AssetApp.



25
26
27
28
29
30
31
# File 'lib/klenod/rack/asset_app.rb', line 25

def initialize(source, app: nil, assets_dir: nil, path_prefix: "/assets/", base: nil)
  @source = source
  @app = app
  @assets_dir = assets_dir
  @base = base && Runtime::AssetUrl.normalize(base)
  @path_prefix = @base ? (Runtime::AssetUrl.path_prefix(@base) || path_prefix) : path_prefix
end

Instance Attribute Details

#app ⇒ Object (readonly)

Returns the value of attribute app.



33
34
35
# File 'lib/klenod/rack/asset_app.rb', line 33

def app
  @app
end

#assets_dir ⇒ Object (readonly)

Returns the value of attribute assets_dir.



33
34
35
# File 'lib/klenod/rack/asset_app.rb', line 33

def assets_dir
  @assets_dir
end

#base ⇒ Object (readonly)

Returns the value of attribute base.



33
34
35
# File 'lib/klenod/rack/asset_app.rb', line 33

def base
  @base
end

#path_prefix ⇒ Object (readonly)

Returns the value of attribute path_prefix.



33
34
35
# File 'lib/klenod/rack/asset_app.rb', line 33

def path_prefix
  @path_prefix
end

#source ⇒ Object (readonly)

Returns the value of attribute source.



33
34
35
# File 'lib/klenod/rack/asset_app.rb', line 33

def source
  @source
end

Instance Method Details

#call(env) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/klenod/rack/asset_app.rb', line 35

def call(env)
  response = response_for(env.fetch("PATH_INFO", ""), env)
  return response.rack_response if response
  return app.call(env) if app

  not_found.rack_response
end

#response_for(path, env = {}) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/klenod/rack/asset_app.rb', line 43

def response_for(path, env = {})
  return nil unless asset_path?(path)

  asset = asset_for(asset_output_path(path))
  brotli_available = brotli_asset_available?(asset)
  compressed = brotli_available && accepts_brotli?(env.fetch("HTTP_ACCEPT_ENCODING", ""))
  body = compressed ? brotli_asset_bytes(asset) : asset_bytes(asset)
  headers = {
    "content-type" => asset.content_type,
    "content-length" => body.bytesize.to_s,
    "cache-control" => CACHE_CONTROL
  }
  link = preload_link_header(asset)
  headers["link"] = link if link
  headers["vary"] = "Accept-Encoding" if brotli_available
  if compressed
    headers["content-encoding"] = "br"
  end

  Response.new(
    200,
    headers,
    body
  )
rescue KeyError, Errno::ENOENT
  not_found
end