Module: EasyPost::Util

Defined in:
lib/easypost/util.rb

Overview

Internal utilities helpful for this libraries operation.

Constant Summary collapse

BY_PREFIX =
{
  'ak' => EasyPost::ApiKey,
  'adr' => EasyPost::Address,
  'bank' => EasyPost::PaymentMethod,
  'batch' => EasyPost::Batch,
  'brd' => EasyPost::Brand,
  'ca' => EasyPost::CarrierAccount,
  'card' => EasyPost::PaymentMethod,
  'cstinfo' => EasyPost::CustomsInfo,
  'cstitem' => EasyPost::CustomsItem,
  'es' => EasyPost::EndShipper,
  'evt' => EasyPost::Event,
  'hook' => EasyPost::Webhook,
  'ins' => EasyPost::Insurance,
  'order' => EasyPost::Order,
  'pickup' => EasyPost::Pickup,
  'pickuprate' => EasyPost::PickupRate,
  'pl' => EasyPost::PostageLabel,
  'plrep' => EasyPost::Report,
  'prcl' => EasyPost::Parcel,
  'rate' => EasyPost::Rate,
  'refrep' => EasyPost::Report,
  'rfnd' => EasyPost::Refund,
  'sf' => EasyPost::ScanForm,
  'shp' => EasyPost::Shipment,
  'shpinvrep' => EasyPost::Report,
  'shprep' => EasyPost::Report,
  'trk' => EasyPost::Tracker,
  'trkrep' => EasyPost::Report,
  'user' => EasyPost::User,
}.freeze
BY_TYPE =
{
  'Address' => EasyPost::Address,
  'ApiKey' => EasyPost::ApiKey,
  'BankAccount' => EasyPost::PaymentMethod,
  'Batch' => EasyPost::Batch,
  'Brand' => EasyPost::Brand,
  'CarbonOffset' => EasyPost::CarbonOffset,
  'CarrierAccount' => EasyPost::CarrierAccount,
  'CreditCard' => EasyPost::PaymentMethod,
  'CustomsInfo' => EasyPost::CustomsInfo,
  'CustomsItem' => EasyPost::CustomsItem,
  'EndShipper' => EasyPost::EndShipper,
  'Event' => EasyPost::Event,
  'Insurance' => EasyPost::Insurance,
  'Order' => EasyPost::Order,
  'Parcel' => EasyPost::Parcel,
  'PaymentLogReport' => EasyPost::Report,
  'Pickup' => EasyPost::Pickup,
  'PickupRate' => EasyPost::PickupRate,
  'PostageLabel' => EasyPost::PostageLabel,
  'Rate' => EasyPost::Rate,
  'Referral' => EasyPost::Beta::Referral,
  'Refund' => EasyPost::Refund,
  'RefundReport' => EasyPost::Report,
  'Report' => EasyPost::Report,
  'ScanForm' => EasyPost::ScanForm,
  'Shipment' => EasyPost::Shipment,
  'ShipmentInvoiceReport' => EasyPost::Report,
  'ShipmentReport' => EasyPost::Report,
  'TaxIdentifier' => EasyPost::TaxIdentifier,
  'Tracker' => EasyPost::Tracker,
  'TrackerReport' => EasyPost::Report,
  'User' => EasyPost::User,
  'Webhook' => EasyPost::Webhook,
}.freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Attribute Details

#os_archObject

Returns the value of attribute os_arch.



5
6
7
# File 'lib/easypost/util.rb', line 5

def os_arch
  @os_arch
end

#os_nameObject

Returns the value of attribute os_name.



5
6
7
# File 'lib/easypost/util.rb', line 5

def os_name
  @os_name
end

#os_versionObject

Returns the value of attribute os_version.



5
6
7
# File 'lib/easypost/util.rb', line 5

def os_version
  @os_version
end

Class Method Details

.build_dict_key(keys) ⇒ Object

Build a dict key from a list of keys. Example: [code, number] -> code



115
116
117
118
119
120
121
122
123
# File 'lib/easypost/util.rb', line 115

def self.build_dict_key(keys)
  result = keys[0].to_s

  keys[1..-1].each do |key|
    result += "[#{key}]"
  end

  result
end

.convert_to_easypost_object(response, api_key, parent = nil, name = nil) ⇒ Object

Convert data to an EasyPost Object.



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/easypost/util.rb', line 148

def self.convert_to_easypost_object(response, api_key, parent = nil, name = nil)
  case response
  when Array
    response.map { |i| convert_to_easypost_object(i, api_key, parent) }
  when Hash
    # Determine class based on the "object" key in the JSON response
    cls_name = response[:object] || response['object']
    if cls_name
      # Use the "object" key value to look up the class
      cls = BY_TYPE[cls_name]
    else
      # Fallback to determining class based on the "id" prefix in the JSON response
      id = response[:id] || response['id']
      if id.nil? || id.index('_').nil?
        # ID not present or prefix not present (ID malformed)
        cls = EasyPost::EasyPostObject
      else
        # Parse the prefix from the ID and use it to look up the class
        cls_prefix = id[0..id.index('_')][0..-2]
        cls = BY_PREFIX[cls_prefix]
      end
    end
    # Fallback to using the generic class if other determination methods fail (or class lookup produced no results)
    cls ||= EasyPost::EasyPostObject
    cls.construct_from(response, api_key, parent, name)
  else
    # response is neither a Hash nor Array (used mostly when dealing with final values like strings, booleans, etc.)
    response
  end
end

.form_encode_params(hash, parent_keys = [], parent_dict = {}) ⇒ Object

Form-encode a multi-layer dictionary to a one-layer dictionary.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/easypost/util.rb', line 97

def self.form_encode_params(hash, parent_keys = [], parent_dict = {})
  result = parent_dict or {}
  keys = parent_keys or []

  hash.each do |key, value|
    if value.instance_of?(Hash)
      keys << key
      result = form_encode_params(value, keys, result)
    else
      dict_key = build_dict_key(keys + [key])
      result[dict_key] = value
    end
  end
  result
end

.get_lowest_object_rate(easypost_object, carriers = [], services = [], rates_key = 'rates') ⇒ Object

Gets the lowest rate of an EasyPost object such as a Shipment, Order, or Pickup. You can exclude by having ‘’!‘` as the first element of your optional filter lists

Raises:



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/easypost/util.rb', line 181

def self.get_lowest_object_rate(easypost_object, carriers = [], services = [], rates_key = 'rates')
  lowest_rate = nil

  carriers = EasyPost::Util.normalize_string_list(carriers)
  negative_carriers = []
  carriers_copy = carriers.clone
  carriers_copy.each do |carrier|
    if carrier[0, 1] == '!'
      negative_carriers << carrier[1..-1]
      carriers.delete(carrier)
    end
  end

  services = EasyPost::Util.normalize_string_list(services)
  negative_services = []
  services_copy = services.clone
  services_copy.each do |service|
    if service[0, 1] == '!'
      negative_services << service[1..-1]
      services.delete(service)
    end
  end

  easypost_object[rates_key].each do |rate|
    rate_carrier = rate.carrier.downcase
    if carriers.size.positive? && !carriers.include?(rate_carrier)
      next
    end
    if negative_carriers.size.positive? && negative_carriers.include?(rate_carrier)
      next
    end

    rate_service = rate.service.downcase
    if services.size.positive? && !services.include?(rate_service)
      next
    end
    if negative_services.size.positive? && negative_services.include?(rate_service)
      next
    end

    if lowest_rate.nil? || rate.rate.to_f < lowest_rate.rate.to_f
      lowest_rate = rate
    end
  end

  raise EasyPost::Error.new('No rates found.') if lowest_rate.nil?

  lowest_rate
end

.normalize_string_list(lst) ⇒ Object

Normalizes a list of strings.



142
143
144
145
# File 'lib/easypost/util.rb', line 142

def self.normalize_string_list(lst)
  lst = lst.is_a?(String) ? lst.split(',') : Array(lst)
  lst.map(&:to_s).map(&:downcase).map(&:strip)
end

.objects_to_ids(obj) ⇒ Object

Converts an object to an object ID.



126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/easypost/util.rb', line 126

def self.objects_to_ids(obj)
  case obj
  when EasyPost::Resource
    { id: obj.id }
  when Hash
    result = {}
    obj.each { |k, v| result[k] = objects_to_ids(v) unless v.nil? }
    result
  when Array
    obj.map { |v| objects_to_ids(v) }
  else
    obj
  end
end

.os_archObject



92
93
94
# File 'lib/easypost/util.rb', line 92

def self.os_arch
  Gem::Platform.local.cpu
end

.os_nameObject



75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/easypost/util.rb', line 75

def self.os_name
  case RUBY_PLATFORM
  when /linux/i
    'Linux'
  when /darwin/i
    'Darwin'
  when /cygwin|mswin|mingw|bccwin|wince|emx/i
    'Windows'
  else
    'Unknown'
  end
end

.os_versionObject



88
89
90
# File 'lib/easypost/util.rb', line 88

def self.os_version
  Gem::Platform.local.version
end