Class: CoreLibrary::ApiHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/apimatic-core/utilities/api_helper.rb

Overview

API utility class involved in executing an API

Class Method Summary collapse

Class Method Details

.append_url_with_query_parameters(query_builder, parameters, array_serialization = ArraySerializationFormat::INDEXED) ⇒ Object

Appends the given set of parameters to the given query string.

Parameters:

  • query_builder (String)

    The query string builder to add the query parameters to.

  • parameters (Hash)

    The parameters to append.

  • array_serialization (String) (defaults to: ArraySerializationFormat::INDEXED)

    The serialization format



171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/apimatic-core/utilities/api_helper.rb', line 171

def self.append_url_with_query_parameters(query_builder, parameters,
                                          array_serialization = ArraySerializationFormat::INDEXED)
  # Perform parameter validation.
  unless query_builder.instance_of? String
    raise ArgumentError, 'Given value for parameter \"query_builder\"
      is invalid.'
  end

  # Return if there are no parameters to replace.
  return query_builder if parameters.nil?

  parameters = process_complex_types_parameters(parameters, array_serialization)

  parameters.each do |key, value|
    seperator = query_builder.include?('?') ? '&' : '?'
    unless value.nil?
      if value.instance_of? Array
        value.compact!
        serialize_array(
          key, value, formatting: array_serialization
        ).each do |element|
          seperator = query_builder.include?('?') ? '&' : '?'
          query_builder += "#{seperator}#{element[0]}=#{element[1]}"
        end
      else
        query_builder += "#{seperator}#{key}=#{CGI.escape(value.to_s)}"
      end
    end
  end
  query_builder
end

.append_url_with_template_parameters(query_builder, parameters) ⇒ Object

Replaces template parameters in the given url. parameters.

Parameters:

  • query_builder (String)

    The query string builder to replace the template

  • parameters (Hash)

    The parameters to replace in the url.



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/apimatic-core/utilities/api_helper.rb', line 95

def self.append_url_with_template_parameters(query_builder, parameters)
  # perform parameter validation
  unless query_builder.instance_of? String
    raise ArgumentError, 'Given value for parameter \"query_builder\" is
      invalid.'
  end

  # Return if there are no parameters to replace.
  return query_builder if parameters.nil?

  parameters.each do |key, val|
    if val.nil?
      replace_value = ''
    elsif val['value'].instance_of? Array
      if val['encode'] == true
        val['value'].map! { |element| CGI.escape(element.to_s) }
      else
        val['value'].map!(&:to_s)
      end
      replace_value = val['value'].join('/')
    else
      replace_value = if val['encode'] == true
                        CGI.escape(val['value'].to_s)
                      else
                        val['value'].to_s
                      end
    end

    # Find the template parameter and replace it with its value.
    query_builder = query_builder.gsub("{#{key}}", replace_value)
  end
  query_builder
end

.clean_hash(hash) ⇒ Object

Removes elements with empty values from a hash.

Parameters:

  • hash (Hash)

    The hash to clean.



253
254
255
# File 'lib/apimatic-core/utilities/api_helper.rb', line 253

def self.clean_hash(hash)
  hash.delete_if { |_key, value| value.to_s.strip.empty? }
end

.clean_url(url) ⇒ String

Validates and processes the given Url.

Parameters:

  • url (String)

    The given Url to process.

Returns:

  • (String)

    Pre-processed Url as string.

Raises:

  • (ArgumentError)


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/apimatic-core/utilities/api_helper.rb', line 206

def self.clean_url(url)
  # Perform parameter validation.
  raise ArgumentError, 'Invalid Url.' unless url.instance_of? String

  # Ensure that the urls are absolute.
  matches = url.match(%r{^(https?://[^/]+)})
  raise ArgumentError, 'Invalid Url format.' if matches.nil?

  # Get the http protocol match.
  protocol = matches[1]

  # Check if parameters exist.
  index = url.index('?')

  # Remove redundant forward slashes.
  query = url[protocol.length...(!index.nil? ? index : url.length)]
  query.gsub!(%r{//+}, '/')

  # Get the parameters.
  parameters = !index.nil? ? url[url.index('?')...url.length] : ''

  # Return processed url.
  protocol + query + parameters
end

.custom_merge(a, b) ⇒ Object



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/apimatic-core/utilities/api_helper.rb', line 281

def self.custom_merge(a, b)
  x = {}
  a.each do |key, value_a|
    b.each do |k, value_b|
      next unless key == k

      x[k] = []
      if value_a.instance_of? Array
        value_a.each do |v|
          x[k].push(v)
        end
      else
        x[k].push(value_a)
      end
      if value_b.instance_of? Array
        value_b.each do |v|
          x[k].push(v)
        end
      else
        x[k].push(value_b)
      end
      a.delete(k)
      b.delete(k)
    end
  end
  x.merge!(a)
  x.merge!(b)
  x
end

.custom_type_deserializer(response, deserialize_into, is_array, should_symbolize) ⇒ Object

Deserializes response to a known custom model type.

Parameters:

  • response

    The response received.

  • deserialize_into

    The custom model type to deserialize into.

  • is_array

    Is the response provided an array or not



84
85
86
87
88
89
# File 'lib/apimatic-core/utilities/api_helper.rb', line 84

def self.custom_type_deserializer(response, deserialize_into, is_array, should_symbolize)
  decoded = json_deserialize(response, should_symbolize)
  return deserialize_into.call(decoded) unless is_array

  decoded.map { |element| deserialize_into.call(element) }
end

.data_typesObject

Array of supported data types



551
552
553
554
555
# File 'lib/apimatic-core/utilities/api_helper.rb', line 551

def self.data_types
  [String, Float, Integer,
   TrueClass, FalseClass, Date,
   DateTime, Array, Hash, Object]
end

.date_deserializer(response, is_array, should_symbolize) ⇒ Object

Deserializes date.

Parameters:

  • response

    The response received.

  • is_array

    Is the response provided an array or not



64
65
66
67
68
69
70
# File 'lib/apimatic-core/utilities/api_helper.rb', line 64

def self.date_deserializer(response, is_array, should_symbolize)
  if is_array
    decoded = json_deserialize(response, should_symbolize)
    return decoded.map { |element| Date.iso8601(element) }
  end
  Date.iso8601(response)
end

.deserialize(template, value, sdk_module, should_symbolize) ⇒ Object

Deserialize the value against the template (group of types).

Parameters:

  • value (String)

    The value to be deserialized.

  • template (String)

    The type-combination group for which the value will be mapped (oneOf(Integer, String)).



389
390
391
392
# File 'lib/apimatic-core/utilities/api_helper.rb', line 389

def self.deserialize(template, value, sdk_module, should_symbolize)
  decoded = json_deserialize(value, should_symbolize)
  map_types(decoded, template, sdk_module: sdk_module)
end

.deserialize_datetime(response, datetime_format, is_array, should_symbolize) ⇒ Object

Deserializes datetime.

Parameters:

  • response

    The response received.

  • datetime_format

    Current format of datetime.

  • is_array

    Is the response provided an array or not



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/apimatic-core/utilities/api_helper.rb', line 42

def self.deserialize_datetime(response, datetime_format, is_array, should_symbolize)
  decoded = json_deserialize(response, should_symbolize) if is_array

  case datetime_format
  when DateTimeFormat::HTTP_DATE_TIME
    return DateTimeHelper.from_rfc1123(response) unless is_array

    decoded.map { |element| DateTimeHelper.from_rfc1123(element) }
  when DateTimeFormat::RFC3339_DATE_TIME
    return DateTimeHelper.from_rfc3339(response) unless is_array

    decoded.map { |element| DateTimeHelper.from_rfc3339(element) }
  when DateTimeFormat::UNIX_DATE_TIME
    return DateTimeHelper.from_unix(response) unless is_array

    decoded.map { |element| DateTimeHelper.from_unix(element) }
  end
end

.deserialize_primitive_types(response, type, is_array, should_symbolize) ⇒ Object

Deserializes primitive types like Boolean, String etc.

Parameters:

  • response

    The response received.

  • type

    Type to be deserialized.

  • is_array

    Is the response provided an array or not

Raises:

  • (ArgumentError)


31
32
33
34
35
36
# File 'lib/apimatic-core/utilities/api_helper.rb', line 31

def self.deserialize_primitive_types(response, type, is_array, should_symbolize)
  return json_deserialize(response, should_symbolize) if is_array
  raise ArgumentError, 'callable has not been not provided for deserializer.' if type.nil?

  type.call(response)
end

.dynamic_deserializer(response, should_symbolize) ⇒ Object

Deserializer to use when the type of response is not known beforehand.

Parameters:

  • response

    The response received.



74
75
76
77
78
# File 'lib/apimatic-core/utilities/api_helper.rb', line 74

def self.dynamic_deserializer(response, should_symbolize)
  decoded = json_deserialize(response, should_symbolize) unless response.nil? ||
                                                                response.to_s.strip.empty?
  decoded
end

.form_encode(obj, instance_name, formatting: ArraySerializationFormat::INDEXED) ⇒ Hash

Form encodes an object. of a hash.

Parameters:

  • obj (Dynamic)

    An object to form encode.

  • instance_name (String)

    The name of the object.

Returns:

  • (Hash)

    A form encoded representation of the object in the form



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/apimatic-core/utilities/api_helper.rb', line 316

def self.form_encode(obj, instance_name, formatting: ArraySerializationFormat::INDEXED)
  retval = {}

  # If this is a structure, resolve it's field names.
  obj = obj.to_hash if obj.is_a? BaseModel

  # Create a form encoded hash for this object.
  if obj.nil?
    nil
  elsif obj.instance_of? Array
    if formatting == ArraySerializationFormat::INDEXED
      obj.each_with_index do |value, index|
        retval.merge!(form_encode(value, "#{instance_name}[#{index}]"))
      end
    elsif serializable_types.map { |x| obj[0].is_a? x }.any?
      obj.each do |value|
        abc = if formatting == ArraySerializationFormat::UN_INDEXED
                form_encode(value, "#{instance_name}[]",
                            formatting: formatting)
              else
                form_encode(value, instance_name,
                            formatting: formatting)
              end
        retval = custom_merge(retval, abc)
      end
    else
      obj.each_with_index do |value, index|
        retval.merge!(form_encode(value, "#{instance_name}[#{index}]",
                                  formatting: formatting))
      end
    end
  elsif obj.instance_of? Hash
    obj.each do |key, value|
      retval.merge!(form_encode(value, "#{instance_name}[#{key}]",
                                formatting: formatting))
    end
  elsif obj.instance_of? File
    retval[instance_name] = UploadIO.new(
      obj, 'application/octet-stream', File.basename(obj.path)
    )
  else
    retval[instance_name] = obj
  end
  retval
end

.form_encode_parameters(form_parameters, array_serialization) ⇒ Hash

Form encodes a hash of parameters.

Parameters:

  • form_parameters (Hash)

    The hash of parameters to encode.

Returns:

  • (Hash)

    A hash with the same parameters form encoded.



260
261
262
263
264
265
266
267
# File 'lib/apimatic-core/utilities/api_helper.rb', line 260

def self.form_encode_parameters(form_parameters, array_serialization)
  encoded = {}
  form_parameters.each do |key, value|
    encoded.merge!(form_encode(value, key, formatting:
      array_serialization))
  end
  encoded
end

.get_content_type(value) ⇒ Object

Get content-type depending on the value

Parameters:

  • value (Object)

    The value for which the content-type is resolved.



536
537
538
539
540
541
542
# File 'lib/apimatic-core/utilities/api_helper.rb', line 536

def self.get_content_type(value)
  if serializable_types.map { |x| value.is_a? x }.any?
    'text/plain; charset=utf-8'
  else
    'application/json; charset=utf-8'
  end
end

.json_deserialize(json, should_symbolize = false) ⇒ Object

Parses JSON string. rubocop:disable Style/OptionalBooleanParameter

Parameters:

  • json (String)

    A JSON string.



234
235
236
237
238
239
240
241
242
# File 'lib/apimatic-core/utilities/api_helper.rb', line 234

def self.json_deserialize(json, should_symbolize = false)
  return if json.nil?

  begin
    JSON.parse(json, symbolize_names: should_symbolize)
  rescue StandardError
    raise TypeError, 'Server responded with invalid JSON.'
  end
end

.json_serialize(obj) ⇒ Object

Parses JSON string.

Parameters:

  • obj (object)

    The object to serialize.



247
248
249
# File 'lib/apimatic-core/utilities/api_helper.rb', line 247

def self.json_serialize(obj)
  serializable_types.map { |x| obj.is_a? x }.any? ? obj.to_s : obj.to_json
end

.map_array_type(value, type, group_name, matches) ⇒ Object

Validates and processes the value against the [Array] type.

Parameters:

  • value (String)

    The value to be mapped against the type.

  • type (String)

    The possible type of the value.

  • group_name (String)

    The parameter indicates the group (oneOf|anyOf).

  • matches (Integer)

    The parameter indicates the number of matches of value against types.



468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/apimatic-core/utilities/api_helper.rb', line 468

def self.map_array_type(value, type, group_name, matches)
  if value.instance_of? Array
    decoded = []
    value.each do |val|
      type = type.chomp('[]').to_s
      val = map_types(val, type, group_name: group_name)
      decoded.append(val) unless type.empty?
    rescue ValidationException
      next
    end
    matches += 1 if decoded.length == value.length
    value = decoded unless decoded.empty?
  end
  [value, matches]
end

.map_complex_type(value, type, matches, sdk_module) ⇒ Object

Validates and processes the value against the complex types.

Parameters:

  • value (String)

    The value to be mapped against the type.

  • type (String)

    The possible type of the value.

  • matches (Integer)

    The parameter indicates the number of matches of value against types.



504
505
506
507
508
509
510
511
512
513
514
# File 'lib/apimatic-core/utilities/api_helper.rb', line 504

def self.map_complex_type(value, type, matches, sdk_module)
  # TODO: Add a nil check on sdk_module?
  obj = sdk_module.const_get(type)
  value = if obj.respond_to? 'from_hash'
            obj.send('from_hash', value)
          else
            obj.constants.find { |k| obj.const_get(k) == value }
          end
  matches += 1 unless value.nil?
  [value, matches]
end

.map_data_type(value, element, matches) ⇒ Object

Validates and processes the value against the data types.

Parameters:

  • value (String)

    The value to be mapped against the type.

  • element (String)

    The possible type of the value.

  • matches (Integer)

    The parameter indicates the number of matches of value against types.



520
521
522
523
524
525
# File 'lib/apimatic-core/utilities/api_helper.rb', line 520

def self.map_data_type(value, element, matches)
  element = element.split('|').map { |x| Object.const_get x }
  matches += 1 if element.all? { |x| data_types.include?(x) } &&
                  element.any? { |x| (value.instance_of? x) || (value.class.ancestors.include? x) }
  [value, matches]
end

.map_hash_type(value, type, group_name, matches) ⇒ Object

Validates and processes the value against the [Hash] type.

Parameters:

  • value (String)

    The value to be mapped against the type.

  • type (String)

    The possible type of the value.

  • group_name (String)

    The parameter indicates the group (oneOf|anyOf).

  • matches (Integer)

    The parameter indicates the number of matches of value against types.



447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
# File 'lib/apimatic-core/utilities/api_helper.rb', line 447

def self.map_hash_type(value, type, group_name, matches)
  if value.instance_of? Hash
    decoded = {}
    value.each do |key, val|
      type = type.chomp('{}').to_s
      val = map_types(val, type, group_name: group_name)
      decoded[key] = val unless type.empty?
    rescue ValidationException
      next
    end
    matches += 1 if decoded.length == value.length
    value = decoded unless decoded.empty?
  end
  [value, matches]
end

.map_response(obj, keys) ⇒ Object

Retrieves a field from a Hash/Array based on an Array of keys/indexes

Parameters:

  • obj (Hash, Array)

    The hash to extract data from

  • keys (Array<String, Integer>)

    The keys/indexes to use

Returns:

  • (Object)

    The extracted value



366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/apimatic-core/utilities/api_helper.rb', line 366

def self.map_response(obj, keys)
  val = obj
  begin
    keys.each do |key|
      val = if val.is_a? Array
              if key.to_i.to_s == key
                val[key.to_i]
              else
                val = nil
              end
            else
              val.fetch(key.to_sym)
            end
    end
  rescue NoMethodError, TypeError, IndexError
    val = nil
  end
  val
end

.map_type(value, type, _group_name, matches, sdk_module) ⇒ Object

Validates and processes the value against the type.

Parameters:

  • value (String)

    The value to be mapped against the type.

  • type (String)

    The possible type of the value.

  • _group_name (String)

    The parameter indicates the group (oneOf|anyOf).

  • matches (Integer)

    The parameter indicates the number of matches of value against types.



489
490
491
492
493
494
495
496
497
498
# File 'lib/apimatic-core/utilities/api_helper.rb', line 489

def self.map_type(value, type, _group_name, matches, sdk_module)
  if sdk_module.constants.select do |c|
    sdk_module.const_get(c).to_s == "#{sdk_module}::#{type}"
  end.empty?
    value, matches = map_data_type(value, type, matches)
  else
    value, matches = map_complex_type(value, type, matches, sdk_module)
  end
  [value, matches]
end

.map_types(value, template, group_name: nil, sdk_module: nil) ⇒ Object

Validates and processes the value against the template(group of types).

Parameters:

  • value (String)

    The value to be mapped against the template.

  • template (String)

    The parameter indicates the group of types (oneOf(Integer, String)).

  • group_name (String) (defaults to: nil)

    The parameter indicates the group (oneOf|anyOf).

Raises:



398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# File 'lib/apimatic-core/utilities/api_helper.rb', line 398

def self.map_types(value, template, group_name: nil, sdk_module: nil)
  result_value = nil
  matches = 0
  types = []
  group_name = template.partition('(').first if group_name.nil? && template.match?(/anyOf|oneOf/)

  return if value.nil?

  if template.end_with?('{}') || template.end_with?('[]')
    types = template.split(group_name, 2).last.gsub(/\s+/, '').split
  else
    template = template.split(group_name, 2).last.delete_prefix('(').delete_suffix(')')
    types = template.scan(/(anyOf|oneOf)[(]([^[)]]*)[)]/).flatten.combination(2).map { |a, b| "#{a}(#{b})" }
    types.each { |t| template = template.gsub(", #{t}", '') }
    types = template.gsub(/\s+/, '').split(',').push(*types)
  end
  types.each do |element|
    if element.match?(/^(oneOf|anyOf)[(].*$/)
      begin
        result_value = map_types(value, element, matches)
        matches += 1
      rescue ValidationException
        next
      end
    elsif element.end_with?('{}')
      result_value, matches = map_hash_type(value, element, group_name, matches)
    elsif element.end_with?('[]')
      result_value, matches = map_array_type(value, element, group_name, matches)
    else
      begin
        result_value, matches = map_type(value, element, group_name, matches, sdk_module)
      rescue StandardError
        next
      end
    end
    break if group_name == 'anyOf' && matches == 1
  end
  raise ValidationException, "The value #{value} provided doesn't validate against the schema #{template}" unless
    matches == 1

  value = result_value unless result_value.nil?
  value
end

.process_complex_types_parameters(query_parameters, array_serialization) ⇒ Hash

Process complex types in query_params.

Parameters:

  • query_parameters (Hash)

    The hash of query parameters.

Returns:

  • (Hash)

    array_serialization A hash with the processed query parameters.



272
273
274
275
276
277
278
279
# File 'lib/apimatic-core/utilities/api_helper.rb', line 272

def self.process_complex_types_parameters(query_parameters, array_serialization)
  processed_params = {}
  query_parameters.each do |key, value|
    processed_params.merge!(ApiHelper.form_encode(value, key, formatting:
      array_serialization))
  end
  processed_params
end

.resolve_template_placeholders(placeholders, values, template) ⇒ Object

Updates all placeholders in the given message template with provided value. @@return [String] The resolved template value.

Parameters:

  • placeholders (List)

    The placeholders that need to be searched and replaced in the given template value.

  • values (Hash|String)

    The value which refers to the actual values to replace with.

  • template (String)

    The template string containing placeholders.



584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
# File 'lib/apimatic-core/utilities/api_helper.rb', line 584

def self.resolve_template_placeholders(placeholders, values, template)
  values = values.map { |key, value| [key.to_s, value.to_s] }.to_h if values.is_a? Hash

  placeholders.each do |placeholder|
    extracted_value = ''
    if values.is_a? Hash
      # pick the last chunk then strip the last character (i.e. `}`) of the string value
      key = if placeholder.include? '.'
              placeholder.split('.')[-1].delete_suffix('}')
            else
              placeholder.delete_prefix('{').delete_suffix('}')
            end
      extracted_value = values[key] unless values[key].nil?
    else
      extracted_value = values unless values.nil?
    end
    template.gsub!(placeholder, extracted_value.to_s)
  end

  template
end

.resolve_template_placeholders_using_json_pointer(placeholders, value, template) ⇒ Object

Updates all placeholders in the given message template with provided value. @@return [String] The resolved template value.

Parameters:

  • placeholders (String)

    The placeholders that need to be searched and replaced in the given template value.

  • value (String)

    The dictionary containing the actual values to replace with.

  • template (String)

    The template string containing placeholders.



562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
# File 'lib/apimatic-core/utilities/api_helper.rb', line 562

def self.resolve_template_placeholders_using_json_pointer(placeholders, value, template)
  placeholders.each do |placeholder|
    extracted_value = ''
    if placeholder.include? '#'
      # pick the 2nd chunk then remove the last character (i.e. `}`) of the string value
      node_pointer = placeholder.split('#')[1].delete_suffix('}')
      value_pointer = JsonPointer.new(value, node_pointer, symbolize_keys: true)
      extracted_value = json_serialize(value_pointer.value) if value_pointer.exists?
    elsif !value.nil?
      extracted_value = json_serialize(value)
    end
    template.gsub!(placeholder, extracted_value)
  end

  template
end

.serializable_typesObject

Array of serializable types



545
546
547
548
# File 'lib/apimatic-core/utilities/api_helper.rb', line 545

def self.serializable_types
  [String, Numeric, TrueClass,
   FalseClass, Date, DateTime]
end

.serialize_array(key, array, formatting: 'indexed') ⇒ Object

Serializes an array parameter (creates key value pairs).

Parameters:

  • key (String)

    The name of the parameter.

  • array (Array)

    The value of the parameter.

  • formatting (String) (defaults to: 'indexed')

    The format of the serialization.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/apimatic-core/utilities/api_helper.rb', line 11

def self.serialize_array(key, array, formatting: 'indexed')
  tuples = []

  tuples += case formatting
            when 'csv'
              [[key, array.map { |element| CGI.escape(element.to_s) }.join(',')]]
            when 'psv'
              [[key, array.map { |element| CGI.escape(element.to_s) }.join('|')]]
            when 'tsv'
              [[key, array.map { |element| CGI.escape(element.to_s) }.join("\t")]]
            else
              array.map { |element| [key, element] }
            end
  tuples
end

.update_user_agent_value_with_parameters(user_agent, parameters) ⇒ Object

Replaces the template parameters in the given user-agent string. parameters.

Parameters:

  • user_agent (String)

    The user_agent value to be replaced with the given

  • parameters (Hash)

    The parameters to replace in the user_agent.



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/apimatic-core/utilities/api_helper.rb', line 133

def self.update_user_agent_value_with_parameters(user_agent, parameters)
  # perform parameter validation
  unless user_agent.instance_of? String
    raise ArgumentError, 'Given value for \"user_agent\" is
      invalid.'
  end

  # Return if there are no parameters to replace.
  return user_agent if parameters.nil?

  parameters.each do |key, val|
    if val.nil?
      replace_value = ''
    elsif val['value'].instance_of? Array
      if val['encode'] == true
        val['value'].map! { |element| ERB::Util.url_encode(element.to_s) }
      else
        val['value'].map!(&:to_s)
      end
      replace_value = val['value'].join('/')
    else
      replace_value = if val['encode'] == true
                        ERB::Util.url_encode(val['value'].to_s)
                      else
                        val['value'].to_s
                      end
    end

    # Find the template parameter and replace it with its value.
    user_agent = user_agent.gsub(key.to_s, replace_value)
  end
  user_agent
end

.validate_types(value, template, sdk_module, should_symbolize) ⇒ Object

Validates the value against the template(group of types).

Parameters:

  • value (String)

    The value to be mapped against the type.

  • template (String)

    The parameter indicates the group of types (oneOf(Integer, String)).



530
531
532
# File 'lib/apimatic-core/utilities/api_helper.rb', line 530

def self.validate_types(value, template, sdk_module, should_symbolize)
  map_types(json_deserialize(value.to_json, should_symbolize), template, sdk_module: sdk_module)
end