Class: Stubify::IO

Inherits:
Object
  • Object
show all
Defined in:
lib/stubify/io.rb

Class Method Summary collapse

Class Method Details

.cached?(request, body) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
41
42
43
44
45
46
# File 'lib/stubify/io.rb', line 38

def self.cached?(request, body)
  # Do not load cache if path is whitelisted
  return false if Stubify.options.whitelisted.include?(request.path)

  # Otherwise check there is a cached payload
  path = IO.path_from_request(request)
  file_name = IO.file_name_from_request(request, body)
  return Pathname.new(File.join(path, file_name)).file?
end

.file_name_from_request(request, body) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/stubify/io.rb', line 52

def self.file_name_from_request(request, body)
  file_name = request.request_method.dup
  file_name << request.query_string.dup unless request.query_string.nil?
  unless body.nil?
    file_name << Digest::SHA256.hexdigest(body.to_s)
  end
  file_name = "#{Digest::SHA256.hexdigest(file_name)}.json"
  return file_name
end

.path_from_request(request) ⇒ Object



48
49
50
# File 'lib/stubify/io.rb', line 48

def self.path_from_request(request)
  return File.join(Stubify.options.directory, request.path)
end

.read_from_disk(request, body) ⇒ Object



31
32
33
34
35
36
# File 'lib/stubify/io.rb', line 31

def self.read_from_disk(request, body)
  path = IO.path_from_request(request)
  file_name = IO.file_name_from_request(request, body)
  file = File.read(File.join(path, file_name))
  return JSON.parse(file)
end

.write_on_disk(request, body, response) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/stubify/io.rb', line 10

def self.write_on_disk(request, body, response)
  path = IO.path_from_request(request)
  file_name = IO.file_name_from_request(request, body)

  data = {
    'status_code': response.code,
    'content_type': response.content_type,
    'body': response.body.to_s
  }

  # Do not persist if path is whitelisted
  return data if Stubify.options.whitelisted.include?(request.path)

  FileUtils.mkdir_p(path)
  File.open(File.join(path, file_name), "wb") do |file|
    file.puts(data.to_json)
  end

  return data
end