class HTTPX::Plugins::ResponseCache::FileStore

  1. lib/httpx/plugins/response_cache/file_store.rb
Superclass: Object

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).

Methods

Public Class

  1. new

Public Instance

  1. clear
  2. dir
  3. get
  4. set

Constants

CRLF = HTTPX::Connection::HTTP1::CRLF  

Attributes

dir [R]

Public Class methods

new(dir = Dir.tmpdir)
[show source]
   # File lib/httpx/plugins/response_cache/file_store.rb
17 def initialize(dir = Dir.tmpdir)
18   @dir = Pathname.new(dir).join("httpx-response-cache")
19 
20   FileUtils.mkdir_p(@dir)
21 end

Public Instance methods

clear()
[show source]
   # File lib/httpx/plugins/response_cache/file_store.rb
23 def clear
24   FileUtils.rm_rf(@dir)
25 end
get(request)
[show source]
   # File lib/httpx/plugins/response_cache/file_store.rb
27 def get(request)
28   path = file_path(request)
29 
30   return unless File.exist?(path)
31 
32   File.open(path, mode: File::RDONLY | File::BINARY) do |f|
33     f.flock(File::Constants::LOCK_SH)
34 
35     read_from_file(request, f)
36   end
37 end
set(request, response)
[show source]
   # File lib/httpx/plugins/response_cache/file_store.rb
39 def set(request, response)
40   path = file_path(request)
41 
42   file_exists = File.exist?(path)
43 
44   mode = file_exists ? File::RDWR : File::CREAT | File::Constants::WRONLY
45 
46   File.open(path, mode: mode | File::BINARY) do |f|
47     f.flock(File::Constants::LOCK_EX)
48 
49     if file_exists
50       cached_response = read_from_file(request, f)
51 
52       if cached_response
53         next if cached_response == request.cached_response
54 
55         cached_response.close
56 
57         f.truncate(0)
58 
59         f.rewind
60       end
61     end
62     # cache the request headers
63     f << request.verb << CRLF
64     f << request.uri << CRLF
65 
66     request.headers.each do |field, value|
67       f << field << ":" << value << CRLF
68     end
69 
70     f << CRLF
71 
72     # cache the response
73     f << response.status << CRLF
74     f << response.version << CRLF
75 
76     response.headers.each do |field, value|
77       f << field << ":" << value << CRLF
78     end
79 
80     f << CRLF
81 
82     response.body.rewind
83 
84     ::IO.copy_stream(response.body, f)
85   end
86 end