Class: Wfirma::Result

Inherits:
Object
  • Object
show all
Defined in:
lib/wfirma/result.rb

Overview

Wraps a parsed wFirma API response. wFirma answers HTTP 200 even for failures - the real outcome lives in status.code, and validation errors are nested inside the returned objects.

Responses are shaped .., e.g. invoices.0.invoice or contractors.0.contractor.

collection/entity are positional on purpose: Result.new("status" => …) with a brace-less hash would otherwise be parsed as keyword arguments.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw, collection = "invoices", entity = "invoice") ⇒ Result

Returns a new instance of Result.



14
15
16
17
18
# File 'lib/wfirma/result.rb', line 14

def initialize(raw, collection = "invoices", entity = "invoice")
  @raw = raw || {}
  @collection = collection
  @entity = entity
end

Instance Attribute Details

#rawObject (readonly)

Returns the value of attribute raw.



12
13
14
# File 'lib/wfirma/result.rb', line 12

def raw
  @raw
end

Instance Method Details

#errorsObject



56
57
58
# File 'lib/wfirma/result.rb', line 56

def errors
  @errors ||= field_errors.empty? ? Array(message_error) : field_errors
end

#messageObject

Top-level failure text. Actions that answer without a record body (invoices/send) report the reason here rather than as field errors.



52
53
54
# File 'lib/wfirma/result.rb', line 52

def message
  dig_hash(raw, "status", "message")
end

#recordObject Also known as: invoice

The object wFirma returned, from ...



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/wfirma/result.rb', line 29

def record
  entries = raw[@collection]
  return nil unless entries.is_a?(Hash)

  entries.each do |key, value|
    next unless key.to_s.match?(/\A\d+\z/) && value.is_a?(Hash)

    found = value[@entity]
    return found if found.is_a?(Hash)
  end
  nil
end

#record_idObject Also known as: invoice_id



42
43
44
45
# File 'lib/wfirma/result.rb', line 42

def record_id
  id = record && record["id"]
  id&.to_i
end

#status_codeObject



24
25
26
# File 'lib/wfirma/result.rb', line 24

def status_code
  dig_hash(raw, "status", "code")
end

#success?Boolean

Returns:

  • (Boolean)


20
21
22
# File 'lib/wfirma/result.rb', line 20

def success?
  status_code == "OK"
end