Class: MundiApi::APIHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/mundi_api/api_helper.rb

Overview

API utility class

Class Method Summary collapse

Class Method Details

.append_url_with_query_parameters(query_builder, parameters, array_serialization: 'indexed') ⇒ Object

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

Parameters:

  • The (String)

    query string builder to add the query parameters to.

  • The (Hash)

    parameters to append.

  • The (String)

    format of array parameter serialization.



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/mundi_api/api_helper.rb', line 65

def self.append_url_with_query_parameters(query_builder, parameters,
                                          array_serialization: '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.each do |key, value|
    seperator = query_builder.include?('?') ? '&' : '?'
    unless value.nil?
      if value.instance_of? Array
        value.compact!
        query_builder += if array_serialization == 'csv'
                           "#{seperator}#{key}=#{value.map do |element|
                             CGI.escape(element.to_s)
                           end.join(',')}"
                         elsif array_serialization == 'psv'
                           "#{seperator}#{key}=#{value.map do |element|
                             CGI.escape(element.to_s)
                           end.join('|')}"
                         elsif array_serialization == 'tsv'
                           "#{seperator}#{key}=#{value.map do |element|
                             CGI.escape(element.to_s)
                           end.join('\t')}"
                         else
                           "#{seperator}#{APIHelper.serialize_array(
                             key, value, formatting: array_serialization
                           ).map { |k, v| "#{k}=#{CGI.escape(v.to_s)}" }
                           .join('&')}"
                         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:

  • The (String)

    query string builder to replace the template

  • The (Hash)

    parameters to replace in the url.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/mundi_api/api_helper.rb', line 32

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?

  # Iterate and append parameters.

  parameters.each do |key, value|
    replace_value = ''

    if value.nil?
      replace_value = ''
    elsif value.instance_of? Array
      value.map! { |element| CGI.escape(element.to_s) }
      replace_value = value.join('/')
    else
      replace_value = CGI.escape(value.to_s)
    end

    # Find the template parameter and replace it with its value.

    query_builder = query_builder.gsub('{' + key.to_s + '}', replace_value)
  end
  query_builder
end

.clean_hash(hash) ⇒ Object

Removes elements with empty values from a hash.

Parameters:

  • The (Hash)

    hash to clean.



145
146
147
# File 'lib/mundi_api/api_helper.rb', line 145

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:

  • The (String)

    given Url to process.

Returns:

  • (String)

    Pre-processed Url as string.

Raises:

  • (ArgumentError)


110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/mundi_api/api_helper.rb', line 110

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

.form_encode(obj, instance_name) ⇒ Hash

Form encodes an object. of a hash.

Parameters:

  • An (Dynamic)

    object to form encode.

  • The (String)

    name of the object.

Returns:

  • (Hash)

    A form encoded representation of the object in the form



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/mundi_api/api_helper.rb', line 165

def self.form_encode(obj, instance_name)
  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
    obj.each_with_index do |value, index|
      retval.merge!(APIHelper.form_encode(value, instance_name + '[' +
        index.to_s + ']'))
    end
  elsif obj.instance_of? Hash
    obj.each do |key, value|
      retval.merge!(APIHelper.form_encode(value, instance_name + '[' +
        key + ']'))
    end
  else
    retval[instance_name] = obj
  end
  retval
end

.form_encode_parameters(form_parameters) ⇒ Hash

Form encodes a hash of parameters.

Parameters:

  • The (Hash)

    hash of parameters to encode.

Returns:

  • (Hash)

    A hash with the same parameters form encoded.



152
153
154
155
156
157
158
# File 'lib/mundi_api/api_helper.rb', line 152

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

.json_deserialize(json) ⇒ Object

Parses JSON string.

Parameters:



137
138
139
140
141
# File 'lib/mundi_api/api_helper.rb', line 137

def self.json_deserialize(json)
  return JSON.parse(json)
rescue StandardError
  raise TypeError, 'Server responded with invalid JSON.'
end

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

Serializes an array parameter (creates key value pairs).

Parameters:

  • The (String)

    name of the parameter.

  • The (Array)

    value of the parameter.

  • The (String)

    format of the serialization.



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

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

  if formatting == 'unindexed'
    tuples += array.map { |element| ["#{key}[]", element] }
  elsif formatting == 'indexed'
    tuples += array.map.with_index do |element, index|
      ["#{key}[#{index}]", element]
    end
  elsif formatting == 'plain'
    tuples += array.map { |element| [key, element] }
  else
    raise ArgumentError, 'Invalid format provided.'
  end
  tuples
end