Class: Rack::StaticCache

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/contrib/static_cache.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ StaticCache

Returns a new instance of StaticCache.



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/rack/contrib/static_cache.rb', line 58

def initialize(app, options={})
  @app = app
  @urls = options[:urls]
  @no_cache = {}
  @urls.collect! do |url|
    if url  =~ /\*$/
      url_prefix = url.sub(/\*$/, '')
      @no_cache[url_prefix] = 1
      url_prefix
    else
      url
    end
  end
  root = options[:root] || Dir.pwd
  @file_server = Rack::Files.new(root)
  @cache_duration = options[:duration] || 1
  @versioning_enabled = options.fetch(:versioning, true)
  if @versioning_enabled
    @version_regex = options.fetch(:version_regex, /-[\d.]+([.][a-zA-Z][\w]+)?$/)
  end
  @duration_in_seconds = self.duration_in_seconds
end

Instance Method Details

#call(env) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/rack/contrib/static_cache.rb', line 81

def call(env)
  path = env["PATH_INFO"]
  url = @urls.detect{ |u| path.index(u) == 0 }
  if url.nil?
    @app.call(env)
  else
    if @versioning_enabled
      path.sub!(@version_regex, '\1')
    end

    status, headers, body = @file_server.call(env)
    headers = HEADERS_KLASS.new.merge(headers)

    if @no_cache[url].nil?
      headers['Cache-Control'] ="max-age=#{@duration_in_seconds}, public"
      headers['Expires'] = duration_in_words
    end
    headers['Date'] = Time.now.httpdate
    [status, headers, body]
  end
end

#duration_in_secondsObject



107
108
109
# File 'lib/rack/contrib/static_cache.rb', line 107

def duration_in_seconds
  (60 * 60 * 24 * 365 * @cache_duration).to_i
end

#duration_in_wordsObject



103
104
105
# File 'lib/rack/contrib/static_cache.rb', line 103

def duration_in_words
  (Time.now.utc + self.duration_in_seconds).httpdate
end