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



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
202
203
# File 'lib/apimatic-core/utilities/api_helper.rb', line 173

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.



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
128
129
# File 'lib/apimatic-core/utilities/api_helper.rb', line 97

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

.apply_primitive_type_parser(value) ⇒ Integer, ...

Applies a primitive type parser to deserialize a value.

Parameters:

  • value (String)

    The value to be parsed.

Returns:

  • (Integer, Float, Boolean, String)

    The deserialized value, which can be an Integer, Float, Boolean, or String.



251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/apimatic-core/utilities/api_helper.rb', line 251

def self.apply_primitive_type_parser(value)
  # Attempt to deserialize as Integer
  return value.to_i if value.match?(/^\d+$/)

  # Attempt to deserialize as Float
  return value.to_f if value.match?(/^\d+(\.\d+)?$/)

  # Attempt to deserialize as Boolean
  return true if value.downcase == 'true'
  return false if value.downcase == 'false'

  # Default: return the original string
  value
end

.apply_unboxing_function(obj, unboxing_function, is_array: false, is_dict: false, is_array_of_map: false, is_map_of_array: false, dimension_count: 1) ⇒ Object



498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/apimatic-core/utilities/api_helper.rb', line 498

def self.apply_unboxing_function(obj, unboxing_function, is_array: false, is_dict: false, is_array_of_map: false,
                                 is_map_of_array: false, dimension_count: 1)
  if is_dict
    if is_map_of_array
      # Handle case where the object is a map of arrays (Hash with array values)
      obj.transform_values do |v|
        apply_unboxing_function(v, unboxing_function, is_array: true, dimension_count: dimension_count)
      end
    else
      # Handle regular Hash (map) case
      obj.transform_values { |v| unboxing_function.call(v) }
    end
  elsif is_array
    if is_array_of_map
      # Handle case where the object is an array of maps (Array of Hashes)
      obj.map do |element|
        apply_unboxing_function(element, unboxing_function, is_dict: true, dimension_count: dimension_count)
      end
    elsif dimension_count > 1
      # Handle multi-dimensional array
      obj.map do |element|
        apply_unboxing_function(element, unboxing_function, is_array: true,
                                                            dimension_count: dimension_count - 1)
      end
    else
      # Handle regular Array case
      obj.map { |element| unboxing_function.call(element) }
    end
  else
    # Handle base case where the object is neither Array nor Hash
    unboxing_function.call(obj)
  end
end

.clean_hash(hash) ⇒ Object

Removes elements with empty values from a hash.

Parameters:

  • hash (Hash)

    The hash to clean.



331
332
333
# File 'lib/apimatic-core/utilities/api_helper.rb', line 331

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)


208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/apimatic-core/utilities/api_helper.rb', line 208

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



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'lib/apimatic-core/utilities/api_helper.rb', line 359

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



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

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



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

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



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

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

.deserializable_json?(json) ⇒ Boolean

Checks whether the content is deserializable JSON.

Parameters:

  • json (String)

    A JSON string.

Returns:

  • (Boolean)

    True if the content can be deserialized, false otherwise.



312
313
314
315
316
317
318
319
320
321
# File 'lib/apimatic-core/utilities/api_helper.rb', line 312

def self.deserializable_json?(json)
  return false if json.nil? || json.to_s.strip.empty?

  begin
    JSON.parse(json)
    true
  rescue JSON::ParserError
    false
  end
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



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

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)


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

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

.deserialize_union_type(union_type, response, should_symbolize = false, should_deserialize = false) ⇒ Object

Deserialize the response based on the provided union_type.

Parameters:

  • union_type (UnionType)

    The union type to validate and deserialize the response.

  • response (Object)

    The response object to be deserialized.

  • should_deserialize (Boolean) (defaults to: false)

    Flag indicating whether the response should be deserialized. Default is true.

Returns:

  • (Object)

    The deserialized response based on the union_type.



239
240
241
242
243
244
245
# File 'lib/apimatic-core/utilities/api_helper.rb', line 239

def self.deserialize_union_type(union_type, response, should_symbolize = false, should_deserialize = false)
  response = ApiHelper.json_deserialize(response, false, true) if should_deserialize

  union_type_result = union_type.validate(response)

  union_type_result.deserialize(response, should_symbolize: should_symbolize)
end

.dynamic_deserializer(response, should_symbolize) ⇒ Hash, ...

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

Parameters:

  • response

    The response received.

Returns:

  • (Hash, Array, nil)

    The deserialized response.



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

def self.dynamic_deserializer(response, should_symbolize)
  return unless deserializable_json?(response)

  json_deserialize(response, should_symbolize)
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



394
395
396
397
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
# File 'lib/apimatic-core/utilities/api_helper.rb', line 394

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

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

  # Create a form encoded hash for this object.
  if obj.nil?
    return retval
  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.



338
339
340
341
342
343
344
345
# File 'lib/apimatic-core/utilities/api_helper.rb', line 338

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_additional_properties(hash, unboxing_function, is_array: false, is_dict: false, is_array_of_map: false, is_map_of_array: false, dimension_count: 1) ⇒ Hash

Apply unboxing_function to additional properties from hash.

Parameters:

  • hash (Hash)

    The hash to extract additional properties from.

  • unboxing_function (Proc)

    The deserializer to apply to each item in the hash.

Returns:

  • (Hash)

    A hash containing the additional properties and their values.



469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
# File 'lib/apimatic-core/utilities/api_helper.rb', line 469

def self.get_additional_properties(hash, unboxing_function, is_array: false, is_dict: false, is_array_of_map: false,
                                   is_map_of_array: false, dimension_count: 1)
  additional_properties = {}

  # Iterate over each key-value pair in the input hash
  hash.each do |key, value|
    # Prepare arguments for apply_unboxing_function
    args = {
      is_array: is_array,
      is_dict: is_dict,
      is_array_of_map: is_array_of_map,
      is_map_of_array: is_map_of_array,
      dimension_count: dimension_count
    }

    # If the value is a complex structure (Hash or Array), apply apply_unboxing_function
    additional_properties[key] = if is_array || is_dict
                                   apply_unboxing_function(value, unboxing_function, **args)
                                 else
                                   # Apply the unboxing function directly for simple values
                                   unboxing_function.call(value)
                                 end
  rescue StandardError
    # Ignore the exception and continue processing
  end

  additional_properties
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.



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

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

.get_query_parameters(url) ⇒ Object

Parses query parameters from a given URL. Returns a Hash with decoded keys and values. If a key has multiple values, they are returned as an array.

Example:

ApiHelper.get_query_parameters("https://example.com?a=1&b=2&b=3")
=> {"a"=>"1", "b"=>["2", "3"]}


611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
# File 'lib/apimatic-core/utilities/api_helper.rb', line 611

def self.get_query_parameters(url)
  return {} if url.nil? || url.strip.empty?

  begin
    uri = URI.parse(url)
    query = uri.query
    return {} if query.nil? || query.strip.empty?

    parsed = CGI.parse(query)

    # Convert arrays to string or handle empty ones as ""
    parsed.transform_values! do |v|
      if v.empty?
        ''
      elsif v.size == 1
        v.first
      else
        v
      end
    end
  rescue URI::InvalidURIError => e
    warn "Invalid URL provided: #{e.message}"
    {}
  rescue StandardError => e
    warn "Unexpected error while parsing URL: #{e.message}"
    {}
  end
end

.json_deserialize(json, should_symbolize = false, allow_primitive_type_parsing = false) ⇒ Hash, ...

Parses a JSON string.

Parameters:

  • json (String)

    A JSON string.

  • should_symbolize (Boolean) (defaults to: false)

    Determines whether the keys should be symbolized. If set to true, the keys will be converted to symbols. Defaults to false.

  • allow_primitive_type_parsing (Boolean) (defaults to: false)

    Determines whether to allow parsing of primitive types. If set to true, the method will attempt to parse primitive types like numbers and booleans. Defaults to false.

Returns:

  • (Hash, Array, nil)

    The parsed JSON object, or nil if the input string is nil.

Raises:

  • (TypeError)

    if the server responds with invalid JSON and primitive type parsing is not allowed.



297
298
299
300
301
302
303
304
305
306
307
# File 'lib/apimatic-core/utilities/api_helper.rb', line 297

def self.json_deserialize(json, should_symbolize = false, allow_primitive_type_parsing = false)
  return if json.nil? || json.to_s.strip.empty?

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

    ApiHelper.apply_primitive_type_parser(json)
  end
end

.json_serialize(obj) ⇒ Object

Parses JSON string.

Parameters:

  • obj (object)

    The object to serialize.



325
326
327
# File 'lib/apimatic-core/utilities/api_helper.rb', line 325

def self.json_serialize(obj)
  serializable_types.map { |x| obj.is_a? x }.any? ? obj.to_s : obj.to_json
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



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

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

.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.



350
351
352
353
354
355
356
357
# File 'lib/apimatic-core/utilities/api_helper.rb', line 350

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.



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

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.



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

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



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

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.



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

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.



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
166
167
# File 'lib/apimatic-core/utilities/api_helper.rb', line 135

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

.valid_type?(value, type_callable, is_model_hash: false, is_inner_model_hash: false) ⇒ Boolean

Checks if a value or all values in a nested structure satisfy a given type condition.

Parameters:

  • value (Object)

    The value or nested structure to be checked.

  • type_callable (Proc)

    A callable object that defines the type condition.

  • is_model_hash (Boolean) (defaults to: false)

    A flag to identify the provided value is a model value hash.

  • is_inner_model_hash (Boolean) (defaults to: false)

    A flag to identify the provided value is a hash of model value hash.

Returns:

  • (Boolean)

    Returns true if the value or all values in the structure satisfy the type condition, false otherwise.



273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/apimatic-core/utilities/api_helper.rb', line 273

def self.valid_type?(value, type_callable, is_model_hash: false, is_inner_model_hash: false)
  if value.is_a?(Array)
    value.all? do |item|
      valid_type?(item, type_callable,
                  is_model_hash: is_model_hash,
                  is_inner_model_hash: is_inner_model_hash)
    end
  elsif value.is_a?(Hash) && (!is_model_hash || is_inner_model_hash)
    value.values.all? do |item|
      valid_type?(item, type_callable, is_model_hash: is_model_hash)
    end
  else
    !value.nil? && type_callable.call(value)
  end
end