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.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/rack/contrib/static_cache.rb', line 46

def initialize(app, options={})
  @app = app
  @urls = options[:urls]
  @no_cache = {}
  @urls.collect! do |url|
    if url  =~ /\*$/
      url.sub!(/\*$/, '')
      @no_cache[url] = 1
    end
    url
  end
  root = options[:root] || Dir.pwd
  @file_server = Rack::File.new(root)
  @cache_duration = options[:duration] || 1
  @versioning_enabled = true
  @versioning_enabled = options[:versioning] unless options[:versioning].nil?
  @duration_in_seconds = self.duration_in_seconds
  @duration_in_words    = self.duration_in_words
end

Instance Method Details

#call(env) ⇒ Object



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/rack/contrib/static_cache.rb', line 66

def call(env)
  path = env["PATH_INFO"]
  url = @urls.detect{ |u| path.index(u) == 0 }
  unless url.nil?
    path.sub!(/-[\d.]+([.][a-zA-Z][\w]+)?$/, '\1') if @versioning_enabled
    status, headers, body = @file_server.call(env)
    if @no_cache[url].nil?
      headers['Cache-Control'] ="max-age=#{@duration_in_seconds}, public"
      headers['Expires'] = @duration_in_words
      headers.delete 'Etag'
      headers.delete 'Pragma'
      headers.delete 'Last-Modified'
    end
    [status, headers, body]
  else
    @app.call(env)
  end
end

#duration_in_secondsObject



89
90
91
# File 'lib/rack/contrib/static_cache.rb', line 89

def duration_in_seconds
  60 * 60 * 24 * 365 * @cache_duration
end

#duration_in_wordsObject



85
86
87
# File 'lib/rack/contrib/static_cache.rb', line 85

def duration_in_words
  (Time.now + self.duration_in_seconds).strftime '%a, %d %b %Y %H:%M:%S GMT'
end