Class: Fleck::Consumer::Response

Inherits:
Object
  • Object
show all
Includes:
Loggable
Defined in:
lib/fleck/consumer/response.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Loggable

#logger

Constructor Details

#initialize(request_id) ⇒ Response

Returns a new instance of Response.



8
9
10
11
12
13
14
15
16
# File 'lib/fleck/consumer/response.rb', line 8

def initialize(request_id)
  @id = request_id
  logger.progname += " #{@id}"

  @status  = 200
  @errors  = []
  @headers = {}
  @body    = nil
end

Instance Attribute Details

#bodyObject

Returns the value of attribute body.



6
7
8
# File 'lib/fleck/consumer/response.rb', line 6

def body
  @body
end

#errorsObject

Returns the value of attribute errors.



6
7
8
# File 'lib/fleck/consumer/response.rb', line 6

def errors
  @errors
end

#headersObject

Returns the value of attribute headers.



6
7
8
# File 'lib/fleck/consumer/response.rb', line 6

def headers
  @headers
end

#idObject

Returns the value of attribute id.



6
7
8
# File 'lib/fleck/consumer/response.rb', line 6

def id
  @id
end

#statusObject

Returns the value of attribute status.



6
7
8
# File 'lib/fleck/consumer/response.rb', line 6

def status
  @status
end

Instance Method Details

#not_found(msg = nil) ⇒ Object



18
19
20
21
22
# File 'lib/fleck/consumer/response.rb', line 18

def not_found(msg = nil)
  @status = 404
  @errors << 'Resource Not Found'
  @errors << msg if msg
end

#render_error(status, msg = []) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/fleck/consumer/response.rb', line 24

def render_error(status, msg = [])
  @status = status.to_i
  if msg.is_a?(Array)
    @errors += msg
  else
    @errors << msg
  end
end

#to_jsonObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/fleck/consumer/response.rb', line 33

def to_json
  return Oj.dump({
    "status"  => @status,
    "errors"  => @errors,
    "headers" => @headers,
    "body"    => @body
  }, mode: :compat)
rescue => e
  logger.error e.inspect + "\n" + e.backtrace.join("\n")
  return Oj.dump({
    "status" => 500,
    "errors" => ['Internal Server Error', 'Failed to dump the response to JSON']
  }, mode: :compat)
end

#to_sObject



48
49
50
# File 'lib/fleck/consumer/response.rb', line 48

def to_s
  return "#<#{self.class} #{self.to_json}>"
end