Class: Locomotive::Steam::Middlewares::Cache

Inherits:
ThreadSafe
  • Object
show all
Includes:
Locomotive::Steam::Middlewares::Concerns::Helpers
Defined in:
lib/locomotive/steam/middlewares/cache.rb

Constant Summary collapse

CACHEABLE_RESPONSE_CODES =
[200, 301, 404, 410].freeze
CACHEABLE_REQUEST_METHODS =
%w(GET HEAD).freeze
DEFAULT_CACHE_CONTROL =
'max-age=0, s-maxage=3600, public, must-revalidate'.freeze
DEFAULT_CACHE_VARY =
'Accept-Language'.freeze
NO_CACHE_CONTROL =
'max-age=0, private, must-revalidate'.freeze

Constants included from Locomotive::Steam::Middlewares::Concerns::Helpers

Locomotive::Steam::Middlewares::Concerns::Helpers::CACHE_HEADERS, Locomotive::Steam::Middlewares::Concerns::Helpers::HTML_CONTENT_TYPE, Locomotive::Steam::Middlewares::Concerns::Helpers::HTML_MIME_TYPES

Instance Attribute Summary

Attributes inherited from ThreadSafe

#env

Instance Method Summary collapse

Methods included from Locomotive::Steam::Middlewares::Concerns::Helpers

#html?, #inject_cookies, #json?, #log, #make_local_path, #modify_path, #mounted_on, #redirect_to, #render_response

Methods inherited from ThreadSafe

#call, #decorate_entry, #default_liquid_context, #default_locale, #liquid_assigns, #live_editing?, #locale, #locales, #merge_with_params, #next, #page, #params, #path, #repositories, #request, #services, #session, #site

Instance Method Details

#_callObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/locomotive/steam/middlewares/cache.rb', line 18

def _call
  if cacheable?
    key = cache_key

    # TODO: only for debugging
    # log("HTTP keys: #{env.select { |key, _| key.starts_with?('HTTP_') }}".light_blue)

    # Test if the ETag or Last Modified has been modified. If not, return a 304 response
    if stale?(key)
      render_response(nil, 304, nil)
      return
    end

    # we have to tell the CDN (or any proxy) what the expiration & validation strategy are
    env['steam.cache_control']        = cache_control
    env['steam.cache_vary']           = cache_vary
    env['steam.cache_etag']           = key
    env['steam.cache_last_modified']  = site.last_modified_at.httpdate

    # retrieve the response from the cache.
    # This is useful if no CDN is being used.
    code, headers, _ = response = fetch_cached_response(key)

    unless CACHEABLE_RESPONSE_CODES.include?(code.to_i)
      env['steam.cache_control'] = headers['Cache-Control'] = NO_CACHE_CONTROL
      env['steam.cache_vary'] = headers['Vary'] = nil
    end

    # we don't want to render twice the page
    @next_response = response
  else
    env['steam.cache_control']  = NO_CACHE_CONTROL
  end
end