Class: Faraday::CacheAdvanced

Inherits:
Middleware
  • Object
show all
Defined in:
lib/faraday/cache-advanced/cache-advanced.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, cache = nil, opts = {}) ⇒ CacheAdvanced

Returns a new instance of CacheAdvanced.



8
9
10
11
12
13
14
15
# File 'lib/faraday/cache-advanced/cache-advanced.rb', line 8

def initialize(app, cache = nil, opts = {})
  @app = app
  if(storename = opts.delete(:store))
    @store = lookup_store(storename)
  else
    @store = cache || yield
  end
end

Instance Attribute Details

#storeObject

Returns the value of attribute store.



4
5
6
# File 'lib/faraday/cache-advanced/cache-advanced.rb', line 4

def store
  @store
end

Instance Method Details

#cache_key(env) ⇒ Object



34
35
36
37
38
# File 'lib/faraday/cache-advanced/cache-advanced.rb', line 34

def cache_key(env)
  body = Hash(env[:body])
  body_string = body.keys.sort.map {|key| "#{key}=#{body[key]}"}.join("&")
  "#{env[:url]}/#{body_string}"
end

#call(env) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/faraday/cache-advanced/cache-advanced.rb', line 17

def call(env)
  key = cache_key(env)
  response = store.read(key)

  if(response.nil? || env[:request_headers].delete(:must_revalidate))
    response = @app.call(env)
    store.write(key, response) if response.success?
  end

  env[:response] = response
  env.update response.env unless env[:response_headers]
  response.env[:method] = env[:method]
  response.env[:url] = env[:url]

  response
end

#lookup_store(name, opts) ⇒ Object



40
41
42
# File 'lib/faraday/cache-advanced/cache-advanced.rb', line 40

def lookup_store(name, opts)
  ActiveSupport::Cache.lookup_store(name.to_sym, opts)
end