Module: Roda::RodaPlugins::Caching::ResponseMethods

Defined in:
lib/roda/plugins/caching.rb

Constant Summary collapse

UNDERSCORE =
'_'.freeze
DASH =
'-'.freeze
COMMA =
', '.freeze
CACHE_CONTROL =
'Cache-Control'.freeze
EXPIRES =
'Expires'.freeze
CONTENT_TYPE =
'Content-Type'.freeze
CONTENT_LENGTH =
'Content-Length'.freeze

Instance Method Summary collapse

Instance Method Details

#cache_control(opts) ⇒ Object

Specify response freshness policy for using the Cache-Control header. Options can can any non-value directives (:public, :private, :no_cache, :no_store, :must_revalidate, :proxy_revalidate), with true as the value. Options can also contain value directives (:max_age, :s_maxage).

response.cache_control :public=>true, :max_age => 60
# => Cache-Control: public, max-age=60

See RFC 2616 / 14.9 for more on standard cache control directives: tools.ietf.org/html/rfc2616#section-14.9.1



187
188
189
190
191
192
193
194
195
196
# File 'lib/roda/plugins/caching.rb', line 187

def cache_control(opts)
  values = []
  opts.each do |k, v|
    next unless v
    k = k.to_s.tr(UNDERSCORE, DASH)
    values << (v == true ? k : "#{k}=#{v}")
  end

  self[CACHE_CONTROL] = values.join(COMMA) unless values.empty?
end

#expires(max_age, opts = OPTS) ⇒ Object

Set Cache-Control header with the max_age given. max_age should be an integer number of seconds that the current request should be cached for. Also sets the Expires header, useful if you have HTTP 1.0 clients (Cache-Control is an HTTP 1.1 header).



202
203
204
205
# File 'lib/roda/plugins/caching.rb', line 202

def expires(max_age, opts=OPTS)
  cache_control(Hash[opts].merge!(:max_age=>max_age))
  self[EXPIRES] = (Time.now + max_age).httpdate
end

#finishObject

Remove Content-Type and Content-Length for 304 responses.



208
209
210
211
212
213
214
215
216
# File 'lib/roda/plugins/caching.rb', line 208

def finish
  a = super
  if a[0] == 304
    h = a[1]
    h.delete(CONTENT_TYPE)
    h.delete(CONTENT_LENGTH)
  end
  a
end