Module: Philiprehberger::HeaderKit::CacheControl
- Defined in:
- lib/philiprehberger/header_kit/cache_control.rb
Overview
Parses and builds Cache-Control header values.
Supports common directives: max-age, s-maxage, no-cache, no-store, public, private, must-revalidate, proxy-revalidate, no-transform, immutable.
Constant Summary collapse
- VALUE_DIRECTIVES =
%w[max-age s-maxage max-stale min-fresh stale-while-revalidate stale-if-error].freeze
Class Method Summary collapse
-
.build(directives) ⇒ String
Build a Cache-Control header string from a directive hash.
-
.parse(header) ⇒ Hash{Symbol => true, Integer, String}
Parse a Cache-Control header string into a directive hash.
Class Method Details
.build(directives) ⇒ String
Build a Cache-Control header string from a directive hash.
47 48 49 50 51 52 53 54 55 56 |
# File 'lib/philiprehberger/header_kit/cache_control.rb', line 47 def self.build(directives) return '' if directives.nil? || directives.empty? parts = directives.map do |key, value| directive = key.to_s.tr('_', '-') value == true ? directive : "#{directive}=#{value}" end parts.join(', ') end |
.parse(header) ⇒ Hash{Symbol => true, Integer, String}
Parse a Cache-Control header string into a directive hash.
Boolean directives become ‘true`. Value directives are converted to integers. Keys are symbolized with hyphens replaced by underscores.
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/philiprehberger/header_kit/cache_control.rb', line 19 def self.parse(header) return {} if header.nil? || header.strip.empty? directives = {} header.split(',').each do |part| part = part.strip next if part.empty? key, value = part.split('=', 2) key = key.strip.downcase sym = key.tr('-', '_').to_sym if value value = value.strip.delete('"') directives[sym] = VALUE_DIRECTIVES.include?(key) ? value.to_i : value else directives[sym] = true end end directives end |