Class: Asynk::Response

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(status:, body: nil, error_message: nil) ⇒ Response

Returns a new instance of Response.



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

def initialize(status: , body: nil, error_message: nil)
  @status, @body, @error_message = status, body, error_message
end

Instance Attribute Details

#bodyObject (readonly)

Returns the value of attribute body.



4
5
6
# File 'lib/asynk/response.rb', line 4

def body
  @body
end

#error_messageObject (readonly)

Returns the value of attribute error_message.



4
5
6
# File 'lib/asynk/response.rb', line 4

def error_message
  @error_message
end

#statusObject (readonly)

Returns the value of attribute status.



4
5
6
# File 'lib/asynk/response.rb', line 4

def status
  @status
end

Class Method Details

.try_parse_json(str) ⇒ Object



49
50
51
52
53
54
55
# File 'lib/asynk/response.rb', line 49

def self.try_parse_json(str)
  begin
    JSON.parse(str)
  rescue JSON::ParserError => e
    return false
  end
end

.try_to_create_from_hash(payload) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/asynk/response.rb', line 39

def self.try_to_create_from_hash(payload)
  return nil if payload.nil?
  parsed_payload = try_parse_json(payload)
  return payload unless parsed_payload
  return payload unless parsed_payload.kind_of?(Hash)
  hiwa = parsed_payload.with_indifferent_access
  return payload unless (hiwa.has_key?(:status) && hiwa.has_key?(:body) && hiwa.has_key?(:error_message))
  new(status: hiwa[:status], body: hiwa[:body], error_message: hiwa[:error_message])
end

Instance Method Details

#[](key) ⇒ Object



23
24
25
# File 'lib/asynk/response.rb', line 23

def [](key)
  @body[key]
end

#errorsObject



21
# File 'lib/asynk/response.rb', line 21

def errors; @error_message; end

#fail?Boolean

Returns:

  • (Boolean)


11
# File 'lib/asynk/response.rb', line 11

def fail?; !success?; end

#success?Boolean

Returns:

  • (Boolean)


10
# File 'lib/asynk/response.rb', line 10

def success?; @status.to_s == 'ok'; end

#to_h(options = {}) ⇒ Object Also known as: to_s, as_json



13
14
15
# File 'lib/asynk/response.rb', line 13

def to_h(options = {})
  { status: @status, body: @body, error_message: @error_message }
end

#to_jsonObject



31
32
33
# File 'lib/asynk/response.rb', line 31

def to_json
  to_h.to_json
end