Class: HTTP::Features::Caching

Inherits:
HTTP::Feature show all
Defined in:
lib/http/features/caching.rb,
lib/http/features/caching/entry.rb,
lib/http/features/caching/in_memory_store.rb

Overview

HTTP caching feature that stores and reuses responses according to RFC 7234. Only GET and HEAD responses are cached. Supports Cache-Control, Expires, ETag, and Last-Modified for freshness checks and conditional revalidation.

Examples:

Basic usage with in-memory cache

HTTP.use(:caching).get("https://example.com/")

With a shared store across requests

store = HTTP::Features::Caching::InMemoryStore.new
client = HTTP.use(caching: { store: store })
client.get("https://example.com/")

Defined Under Namespace

Classes: Entry, InMemoryStore

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from HTTP::Feature

#on_error, #on_request, #wrap_request

Constructor Details

#initialize(store: InMemoryStore.new) ⇒ Caching

Initializes the Caching feature

Examples:

Caching.new(store: InMemoryStore.new)

Parameters:

  • store (#lookup, #store) (defaults to: InMemoryStore.new)

    cache store instance



44
45
46
# File 'lib/http/features/caching.rb', line 44

def initialize(store: InMemoryStore.new)
  @store = store
end

Instance Attribute Details

#store#lookup, #store (readonly)

The cache store instance

Examples:

feature.store

Returns:

  • (#lookup, #store)

    the cache store



34
35
36
# File 'lib/http/features/caching.rb', line 34

def store
  @store
end

Instance Method Details

#around_request(request) { ... } ⇒ HTTP::Response

Wraps the HTTP exchange with caching logic

Checks the cache before making a request. Returns a cached response if fresh; otherwise adds conditional headers and revalidates. Stores cacheable responses for future use.

Examples:

feature.around_request(request) { |req| perform_exchange(req) }

Parameters:

Yields:

  • Executes the HTTP exchange

Yield Returns:

Returns:



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/http/features/caching.rb', line 62

def around_request(request)
  return yield(request) unless cacheable_request?(request)

  entry = store.lookup(request)

  return yield(request) unless entry

  return build_cached_response(entry, request) if entry.fresh?

  response = yield(add_conditional_headers(request, entry))

  return revalidate_entry(entry, response, request) if response.status.not_modified?

  response
end

#wrap_response(response) ⇒ HTTP::Response

Stores cacheable responses in the cache

Examples:

feature.wrap_response(response)

Parameters:

Returns:



86
87
88
89
90
91
# File 'lib/http/features/caching.rb', line 86

def wrap_response(response)
  return response unless cacheable_request?(response.request)
  return response unless cacheable_response?(response)

  store_and_freeze_response(response)
end