Class: HTTPX::Plugins::ResponseCache::FileStore
- Inherits:
-
Object
- Object
- HTTPX::Plugins::ResponseCache::FileStore
- Defined in:
- lib/httpx/plugins/response_cache/file_store.rb
Overview
Implementation of a file system based cache store.
It stores cached responses in a file under a directory pointed by the dir
variable (defaults to the default temp directory from the OS), in a custom format (similar but different from HTTP/1.1 request/response framing).
Constant Summary collapse
- CRLF =
HTTPX::Connection::HTTP1::CRLF
Instance Attribute Summary collapse
-
#dir ⇒ Object
readonly
Returns the value of attribute dir.
Instance Method Summary collapse
- #clear ⇒ Object
- #get(request) ⇒ Object
-
#initialize(dir = Dir.tmpdir) ⇒ FileStore
constructor
A new instance of FileStore.
- #set(request, response) ⇒ Object
Constructor Details
#initialize(dir = Dir.tmpdir) ⇒ FileStore
Returns a new instance of FileStore.
17 18 19 20 21 |
# File 'lib/httpx/plugins/response_cache/file_store.rb', line 17 def initialize(dir = Dir.tmpdir) @dir = Pathname.new(dir).join("httpx-response-cache") FileUtils.mkdir_p(@dir) end |
Instance Attribute Details
#dir ⇒ Object (readonly)
Returns the value of attribute dir.
15 16 17 |
# File 'lib/httpx/plugins/response_cache/file_store.rb', line 15 def dir @dir end |
Instance Method Details
#clear ⇒ Object
23 24 25 |
# File 'lib/httpx/plugins/response_cache/file_store.rb', line 23 def clear FileUtils.rm_rf(@dir) end |
#get(request) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 |
# File 'lib/httpx/plugins/response_cache/file_store.rb', line 27 def get(request) path = file_path(request) return unless File.exist?(path) File.open(path, mode: File::RDONLY | File::BINARY) do |f| f.flock(File::Constants::LOCK_SH) read_from_file(request, f) end end |
#set(request, response) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/httpx/plugins/response_cache/file_store.rb', line 39 def set(request, response) path = file_path(request) file_exists = File.exist?(path) mode = file_exists ? File::RDWR : File::CREAT | File::Constants::WRONLY File.open(path, mode: mode | File::BINARY) do |f| f.flock(File::Constants::LOCK_EX) if file_exists cached_response = read_from_file(request, f) if cached_response next if cached_response == request.cached_response cached_response.close f.truncate(0) f.rewind end end # cache the request headers f << request.verb << CRLF f << request.uri << CRLF request.headers.each do |field, value| f << field << ":" << value << CRLF end f << CRLF # cache the response f << response.status << CRLF f << response.version << CRLF response.headers.each do |field, value| f << field << ":" << value << CRLF end f << CRLF response.body.rewind ::IO.copy_stream(response.body, f) end end |