Class: Rack::FunkyCache
- Inherits:
-
Object
- Object
- Rack::FunkyCache
- Defined in:
- lib/rack/funky-cache.rb
Instance Method Summary collapse
- #cache(env, response) ⇒ Object
- #call(env) ⇒ Object
- #env_excluded?(env) ⇒ Boolean
-
#initialize(app, settings = {}) ⇒ FunkyCache
constructor
A new instance of FunkyCache.
- #should_cache(env, response) ⇒ Object
Constructor Details
#initialize(app, settings = {}) ⇒ FunkyCache
Returns a new instance of FunkyCache.
8 9 10 11 12 13 |
# File 'lib/rack/funky-cache.rb', line 8 def initialize(app, settings={}) @app = app @settings = settings @root = settings[:root] || Dir.pwd @path = settings[:path] || "/public" @directory = settings[:directory] || ::File.join(@root, @path) end |
Instance Method Details
#cache(env, response) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/rack/funky-cache.rb', line 21 def cache(env, response) path = Rack::Utils.unescape(env["PATH_INFO"]) if path[-1, 1] == "/" path = ::File.join(path, "index.html") else path << '.html' end basename = ::File.basename(path) dirname = ::File.join(@directory, ::File.dirname(path)) cachefile = ::File.join(dirname, basename) FileUtils.mkdir_p(dirname) unless ::File.directory?(dirname) unless ::File.exists?(cachefile) ::File.open(cachefile, "w") do |file| response[2].each do |string| file.write(string) end end end end |
#call(env) ⇒ Object
15 16 17 18 19 |
# File 'lib/rack/funky-cache.rb', line 15 def call(env) response = @app.call(env) cache(env, response) if should_cache(env, response) response end |
#env_excluded?(env) ⇒ Boolean
53 54 55 |
# File 'lib/rack/funky-cache.rb', line 53 def env_excluded?(env) @settings[:exclude] && @settings[:exclude].call(env) end |
#should_cache(env, response) ⇒ Object
45 46 47 48 49 50 51 |
# File 'lib/rack/funky-cache.rb', line 45 def should_cache(env, response) unless env_excluded?(env) request = Rack::Request.new(env) request.get? && request.query_string.empty? && /text\/html/ =~ response[1]["Content-Type"] && 200 == response[0] end end |