Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions lib/faraday/http_cache.rb
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ class HttpCache < Faraday::Middleware
# :instrumenter - An instrumentation object that should respond to 'instrument'.
# :instrument_name - The String name of the instrument being reported on (optional).
# :logger - A logger object.
# :max_entries - The maximum number of entries to store per cache key. This option is only
# used when using the +ByUrl+ cache strategy.
#
# Examples:
#
Expand Down
6 changes: 6 additions & 0 deletions lib/faraday/http_cache/strategies/by_url.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ module Strategies
# The original strategy by Faraday::HttpCache.
# Uses URL + HTTP method to generate cache keys.
class ByUrl < BaseStrategy
def initialize(options = {})
super
@max_entries = options[:max_entries]
end

# Store a response inside the cache.
#
# @param [Faraday::HttpCache::Request] request - instance of the executed HTTP request.
Expand All @@ -26,6 +31,7 @@ def write(request, response)
end

entries << entry
entries = entries.last(@max_entries) unless @max_entries.nil?

cache.write(key, entries)
rescue ::Encoding::UndefinedConversionError => e
Expand Down
23 changes: 23 additions & 0 deletions spec/strategies/by_url_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,29 @@
described_class.new(store: wrong)
}.to raise_error(ArgumentError)
end

context 'with max_entries set' do
let(:max_entries) { 2 }
let(:strategy) { described_class.new(store: cache, max_entries: max_entries) }
let(:response) { double(serializable_hash: { response_headers: { 'Vary' => 'X-Foo' } }) }

it 'limits the number of cached entries' do
requests = Array.new(max_entries + 1) do |i|
env = { method: :get, url: 'http://test/index', headers: { 'X-Foo' => i } }
double(env.merge(serializable_hash: env))
end

requests.each { |request| subject.write(request, response) }

expect(subject.cache.read(cache_key).count).to eq(max_entries)

expect(subject.read(requests.first)).to eq(nil)

requests.last(max_entries).each do |request|
expect(subject.read(request)).not_to be_nil
end
end
end
end

describe 'storing responses' do
Expand Down
Loading