Method: HTTPX::Plugins::ResponseCache::FileStore#set

Defined in:
lib/httpx/plugins/response_cache/file_store.rb

#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