Class: Whoosh::Response

Inherits:
Object
  • Object
show all
Defined in:
lib/whoosh/response.rb

Constant Summary collapse

JSON_HEADERS =
{ "content-type" => "application/json" }.freeze
MIME_TYPES =
{ ".html" => "text/html", ".json" => "application/json", ".css" => "text/css",
".js" => "application/javascript", ".png" => "image/png", ".jpg" => "image/jpeg",
".svg" => "image/svg+xml", ".pdf" => "application/pdf", ".txt" => "text/plain" }.freeze

Class Method Summary collapse

Class Method Details

.download(data, filename:, content_type: "application/octet-stream") ⇒ Object



15
16
17
# File 'lib/whoosh/response.rb', line 15

def self.download(data, filename:, content_type: "application/octet-stream")
  [200, { "content-type" => content_type, "content-disposition" => "attachment; filename=\"#{filename}\"" }, [data]]
end

.error(error, production: false) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/whoosh/response.rb', line 41

def self.error(error, production: false)
  headers = { "content-type" => "application/json" }

  if error.is_a?(Errors::RateLimitExceeded)
    headers["retry-after"] = error.retry_after.to_s
  end

  body = if error.is_a?(Errors::HttpError)
    error.to_h
  else
    hash = { error: "internal_error" }
    hash[:message] = error.message unless production
    hash
  end

  [error.is_a?(Errors::HttpError) ? error.status : 500, headers, [Serialization::Json.encode(body)]]
end

.file(path, content_type: nil) ⇒ Object



19
20
21
22
23
24
# File 'lib/whoosh/response.rb', line 19

def self.file(path, content_type: nil)
  raise Errors::NotFoundError unless File.exist?(path)
  ct = content_type || guess_content_type(path)
  body = File.binread(path)
  [200, { "content-type" => ct, "content-length" => body.bytesize.to_s }, [body]]
end

.guess_content_type(path) ⇒ Object



26
27
28
29
# File 'lib/whoosh/response.rb', line 26

def self.guess_content_type(path)
  ext = File.extname(path).downcase
  MIME_TYPES[ext] || "application/octet-stream"
end

.json(data, status: 200, headers: {}) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'lib/whoosh/response.rb', line 31

def self.json(data, status: 200, headers: {})
  body = Serialization::Json.encode(data)
  response_headers = if headers.empty?
    { "content-type" => "application/json", "content-length" => body.bytesize.to_s }
  else
    { "content-type" => "application/json", "content-length" => body.bytesize.to_s }.merge(headers)
  end
  [status, response_headers, [body]]
end

.not_foundObject



59
60
61
# File 'lib/whoosh/response.rb', line 59

def self.not_found
  error(Errors::NotFoundError.new)
end

.redirect(url, status: 302) ⇒ Object



11
12
13
# File 'lib/whoosh/response.rb', line 11

def self.redirect(url, status: 302)
  [status, { "location" => url }, []]
end