module Olelo::HttpHelper

Public Instance Methods

cache_control(options) click to toggle source

Cache control for page

# File lib/olelo/helper.rb, line 226
def cache_control(options)
  return if !Config['production']

  if options[:no_cache]
    response.headers.delete('ETag')
    response.headers.delete('Last-Modified')
    response.headers.delete('Cache-Control')
    return
  end

  last_modified = options.delete(:last_modified)
  modified_since = env['HTTP_IF_MODIFIED_SINCE']
  last_modified = last_modified.try(:to_time) || last_modified
  last_modified = last_modified.try(:httpdate) || last_modified

  if User.logged_in?
    # Always private mode if user is logged in
    options[:private] = true

    # Special etag for authenticated user
    options[:etag] = "#{User.current.name}-#{options[:etag]}" if options[:etag]
  end

  if options[:etag]
    value = '"%s"' % options.delete(:etag)
    response['ETag'] = value.to_s
    response['Last-Modified'] = last_modified if last_modified
    if etags = env['HTTP_IF_NONE_MATCH']
      etags = etags.split(/\s*,\s*/)
      # Etag is matching and modification date matches (HTTP Spec §14.26)
      halt :not_modified if (etags.include?(value) || etags.include?('*')) && (!last_modified || last_modified == modified_since)
    end
  elsif last_modified
    # If-Modified-Since is only processed if no etag supplied.
    # If the etag match failed the If-Modified-Since has to be ignored (HTTP Spec §14.26)
    response['Last-Modified'] = last_modified
    halt :not_modified if last_modified == modified_since
  end

  options[:public] = !options[:private]
  options[:max_age] ||= 0
  options[:must_revalidate] ||= true if !options.include?(:must_revalidate)

  response['Cache-Control'] = options.map do |k, v|
    if v == true
      k.to_s.tr('_', '-')
    elsif v
      v = 31536000 if v.to_s == 'static'
      "#{k.to_s.tr('_', '-')}=#{v}"
    end
  end.compact.join(', ')
end