Class: Usps::Imis::Data

Inherits:
Hash
  • Object
show all
Defined in:
lib/usps/imis/data.rb

Overview

Convenience wrapper for accessing specific properties within an API data response

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.from_json(json) ⇒ Object

Load raw API response JSON to access properties



15
# File 'lib/usps/imis/data.rb', line 15

def self.from_json(json) = self[JSON.parse(json)]

Instance Method Details

#[](property_name) ⇒ Object

Access an individual property value by name



34
35
36
37
38
39
40
# File 'lib/usps/imis/data.rb', line 34

def [](property_name)
  property = raw['Properties']['$values'].find { it['Name'] == property_name }
  return if property.nil?

  value = property['Value']
  value.nil? || value.is_a?(String) ? value : value['$value']
end

#[]=Object

Raises:



53
54
55
# File 'lib/usps/imis/data.rb', line 53

def []=(...)
  raise Errors::ApiError, '`Data` does not support setting values. If you need to modify it, call `.raw` on it.'
end

#entityObject

The Business Object or Panel name



21
# File 'lib/usps/imis/data.rb', line 21

def entity = raw['EntityTypeName']

#imis_idObject Also known as: id

Access the iMIS ID property



25
# File 'lib/usps/imis/data.rb', line 25

def imis_id = self['ID'].to_i

#inspectObject



57
58
59
60
61
# File 'lib/usps/imis/data.rb', line 57

def inspect
  stringio = StringIO.new
  PP.pp(self, stringio)
  stringio.string.delete("\n")
end

#ordinalObject

Access the Ordinal identifier property (if present)



30
# File 'lib/usps/imis/data.rb', line 30

def ordinal = self['Ordinal']&.to_i

#pretty_print(pp) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
# File 'lib/usps/imis/data.rb', line 63

def pretty_print(pp)
  data = { entity:, imis_id:, ordinal: }.compact

  pp.group(1, "#<#{self.class}", '>') do
    data.each do |key, value|
      pp.breakable
      pp.text "#{key}="
      pp.pp value
    end
  end
end

#properties(include_ids: false) ⇒ Object

Hash of all property names to values



46
47
48
49
50
51
# File 'lib/usps/imis/data.rb', line 46

def properties(include_ids: false)
  raw['Properties']['$values']
    .map { it['Name'] }
    .select { include_ids || !%w[ID Ordinal].include?(it) }
    .index_with { self[it] }
end