Class: NetHTTP::Core::Utilities

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

Class Method Summary collapse

Class Method Details

.camel_2_snake(key, type = nil) ⇒ Object

CamelCase to snake_case


88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/core/utilities.rb', line 88

def self.camel_2_snake(key, type = nil)
  key_class = key.class.to_s.downcase
  new_key = key.to_s
               .tr('::', '/')
               .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
               .gsub(/([a-z\d])([A-Z])/, '\1_\2')
               .tr('-', '_')
               .downcase

  # return the newly formatted key without modifying the type
  if type.nil?
    case key_class
    when 'string'
      return new_key.to_s
    when 'symbol'
      return new_key.to_sym
    end
  end

  # return the newly formatted key in type format requested
  return new_key.to_s if type.to_s.downcase == 'string'
  return new_key.to_sym if type.to_s.downcase == 'symbol'

  nil
end

.construct_uri(uri = {}) ⇒ Object


13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
# File 'lib/core/utilities.rb', line 13

def self.construct_uri(uri = {})
  return nil if uri.empty?
  return nil if uri[:host].to_s.empty?
  return nil if uri[:scheme].to_s.empty? && uri[:port].to_s.empty?

  scheme = uri[:scheme]
  if scheme.to_s.empty?
    case uri[:port]
    when 80, '80'
      scheme = 'http'
    else
      scheme = 'https'
    end
  end

  port = uri[:port]
  if port.to_s.empty?
    case uri[:scheme]
    when 'https'
      port = 443
    when 'http'
      port = 80
    end
  end

  if uri[:user].to_s.empty? || uri[:password].to_s.empty?
    user_pass = nil
  else
    user_pass = "#{uri[:user]}:#{uri[:password]}@"
  end

  scheme = "#{scheme}://"
  host = uri[:host]
  port = ":#{port}"
  path = uri[:path]
  query = parse_query(uri[:query])

  scheme = nil if scheme.to_s.empty?
  port = nil if port.to_s.empty?
  path = nil if uri[:path].to_s.empty?
  query = nil if uri[:query].to_s.empty?

  URI("#{scheme}#{user_pass}#{host}#{port}#{path}#{query}").to_s
end

.convert_hash_keys(opts = {}) ⇒ Object

convert hash / array / nested object keys to either snake_case or CamelCase format -> 'snake' or 'camel' type -> 'string' or 'symbol'


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
# File 'lib/core/utilities.rb', line 140

def self.convert_hash_keys(opts = {})
  return opts[:object] if opts[:format].nil? && opts[:type].nil?

  case opts[:object]
  when Hash
    new_hash = {}
    opts[:object].each do |key, value|
      value = convert_hash_keys(
        object: value,
        format: opts[:format],
        type: opts[:type]
      )
      case opts[:format].downcase
      when 'snake'
        new_key = camel_2_snake(key, opts[:type])
      when 'camel'
        new_key = snake_2_camel(key, opts[:type])
      end
      new_hash[new_key] = value
    end
    return new_hash
  when Array
    return opts[:object].map { |value| convert_hash_keys(object: value, format: opts[:format], type: opts[:type]) }
  end

  opts[:object]
end

.empty_or_blank?(obj) ⇒ Boolean

helper method to deal with objects that will otherwise fail in scrub_obj() above

Returns:

  • (Boolean)

186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/core/utilities.rb', line 186

def self.empty_or_blank?(obj)
  return true if obj.nil?
  return false if obj.is_a?(TrueClass)
  return false if obj.is_a?(FalseClass)

  begin
    return true if obj.empty?
  rescue NoMethodError => err
  end

  begin
    return true if obj.blank?
  rescue NoMethodError => err
  end

  false
end

.format_xml_doc(xml_doc) ⇒ Object


253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/core/utilities.rb', line 253

def self.format_xml_doc(xml_doc)
  case xml_doc
  when String
    formatted_xml_doc = Nokogiri::XML(xml_doc) { |c| c.options = Nokogiri::XML::ParseOptions::STRICT }
    formatted_xml_doc = formatted_xml_doc.remove_namespaces!.to_s
  when Nokogiri::XML::Document
    formatted_xml_doc = xml_doc.remove_namespaces!.to_s
  else
    raise "Unrecognized 'xml_doc' class => '#{xml_doc.class}'"
  end

  formatted_xml_doc
end

.json_2_hash(json_doc, type = 'symbol', logger = nil) ⇒ Object

Convert JSON doc to a Ruby Hash.


205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/core/utilities.rb', line 205

def self.json_2_hash(json_doc, type = 'symbol', logger = nil)
  msg = "Invalid 'type' => #{type}.  Use either 'string' or 'symbol' (default)."
  unless ['string', 'symbol'].include?(type.downcase)
    if logger.nil? || logger.to_s.empty?
      puts msg
    else
      logger.debug(msg)
    end
    raise msg
  end

  json_doc = JSON.parse(json_doc) if json_doc.class == String

  begin
    convert_hash_keys(
      object: json_doc,
      format: 'snake',
      type: type.downcase
    )
  rescue RuntimeError => error
    raise error
  end
end

.parse_query(query) ⇒ Object


58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/core/utilities.rb', line 58

def self.parse_query(query)
  # todo: may need to update this as URI.escape is considered obsolete
  case query
  when String
    query = query[1..-1] if query.start_with?('?')
    URI.escape("?#{query}")
  when Hash
    query = query.map { |k, v| "#{k}=#{v}" }
    query = query.join('&')
    URI.escape("?#{query}")
  else
    nil
  end
end

.parse_uri(uri) ⇒ Object


73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/core/utilities.rb', line 73

def self.parse_uri(uri)
  return if uri.nil?
  return if uri.to_s.empty?

  scheme = uri.to_s.scan(%r{([a-z][a-z0-9+\-.]*)://}).flatten[0].to_s
  return URI(uri) if scheme.downcase == 'http'
  return URI(uri) if scheme.downcase == 'https'

  port = uri.to_s.scan(%r{:([0-9]+)}).flatten[0].to_s
  return URI("http://#{uri.to_s.gsub("#{scheme}://", '')}") if port == '80'

  URI("https://#{uri.to_s.gsub("#{scheme}://", '')}")
end

.scrub_obj(obj) ⇒ Object

Recursive function to remove nil and empty values (including [] and {} from Array or Hash nested objects.


169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/core/utilities.rb', line 169

def self.scrub_obj(obj)
  case obj
  when Array
    return obj.map { |item| scrub_obj(item) }
  when Hash
    new_hash = {}
    obj.compact.each do |key, value|
      new_hash[key] = scrub_obj(value) unless empty_or_blank?(value)
    end

    return new_hash
  end

  obj
end

.snake_2_camel(key, type = nil) ⇒ Object

snake_case to CamelCase


115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/core/utilities.rb', line 115

def self.snake_2_camel(key, type = nil)
  key_class = key.class.to_s.downcase
  new_key = key.to_s.split('_')
  new_key = new_key[0].downcase + new_key[1..-1].map(&:capitalize).join('')

  # return the newly formatted key without modifying the type
  if type.nil?
    case key_class
    when 'string'
      return new_key.to_s
    when 'symbol'
      return new_key.to_sym
    end
  end

  # return the newly formatted key in type format requested
  return new_key.to_s if type.to_s.downcase == 'string'
  return new_key.to_sym if type.to_s.downcase == 'symbol'

  nil
end

.valid_html?(html_doc, logger = nil) ⇒ Boolean

Returns:

  • (Boolean)

340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/core/utilities.rb', line 340

def self.valid_html?(html_doc, logger = nil)
  begin
    return false if html_doc.nil?
    return false if html_doc.empty?
    return false unless html_doc.include?('<html>')
    return false unless html_doc.include?('</html>')
    return false unless html_doc.include?('<body>')
    return false unless html_doc.include?('</body>')
    return false unless Nokogiri::HTML(html_doc).errors.empty?
    return false unless Nokogiri::XML(html_doc).errors.empty?

    begin
      # parse_errors = Nokogiri::HTML.parse(html_doc).validate
      parse_errors = Nokogiri::XML(html_doc).errors { |c| c.options = Nokogiri::XML::ParseOptions::STRICT }
      Nokogiri::XML(html_doc) { |c| c.options = Nokogiri::XML::ParseOptions::STRICT }
    rescue Nokogiri::XML::SyntaxError
      if logger.nil? || logger.to_s.empty?
        puts 'WARNING - HTML syntax / parsing errors detected:'
        puts parse_errors
      else
        logger.debug('WARNING - HTML syntax / parsing errors detected:')
        logger.debug(parse_errors)
      end
      return true
    end
  rescue RuntimeError => error
    raise error
  end

  true
end

.valid_json?(json_doc, logger = nil) ⇒ Boolean

Returns:

  • (Boolean)

297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/core/utilities.rb', line 297

def self.valid_json?(json_doc, logger = nil)
  begin
    return false if json_doc.nil?
    return false if json_doc.empty?

    JSON.parse(json_doc)
  rescue JSON::ParserError => error
    if logger.nil? || logger.to_s.empty?
      puts 'WARNING - JSON syntax / parsing errors detected:'
      puts error
    else
      logger.debug('WARNING - JSON syntax / parsing errors detected:')
      logger.debug(error)
    end
    return false
  end

  true
end

.valid_xml?(xml_doc, logger = nil) ⇒ Boolean

Returns:

  • (Boolean)

317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'lib/core/utilities.rb', line 317

def self.valid_xml?(xml_doc, logger = nil)
  begin
    return false if xml_doc.nil?
    return false if xml_doc.empty?

    begin
      parse_errors = Nokogiri::XML(xml_doc).errors { |c| c.options = Nokogiri::XML::ParseOptions::STRICT }
      Nokogiri::XML(xml_doc) { |c| c.options = Nokogiri::XML::ParseOptions::STRICT }
    rescue Nokogiri::XML::SyntaxError
      if logger.nil? || logger.to_s.empty?
        puts 'WARNING - XML syntax / parsing errors detected:'
        puts parse_errors
      else
        logger.debug('WARNING - XML parsing / syntax errors detected:')
        logger.debug(parse_errors)
      end
      return false
    end
  end

  true
end

.xml_2_hash(xml_doc, type = 'symbol', logger = nil) ⇒ Object

Convert XML doc to a Ruby Hash.


230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
# File 'lib/core/utilities.rb', line 230

def self.xml_2_hash(xml_doc, type = 'symbol', logger = nil)
  msg = "Invalid 'type' => #{type}.  Use either 'string' or 'symbol' (default)."
  unless ['string', 'symbol'].include?(type.downcase)
    if logger.nil? || logger.to_s.empty?
      puts msg
    else
      logger.debug(msg)
    end
    raise msg
  end

  xml_doc = Hash.from_xml(format_xml_doc(xml_doc))
  begin
    convert_hash_keys(
      object: xml_doc,
      format: 'snake',
      type: type.downcase
    )
  rescue RuntimeError => error
    raise error
  end
end

.yaml_2_hash(yaml_doc, type = 'symbol', logger = nil) ⇒ Object

Convert YAML doc to a Ruby Hash.


268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/core/utilities.rb', line 268

def self.yaml_2_hash(yaml_doc, type = 'symbol', logger = nil)
  msg = "Invalid 'type' => #{type}.  Use either 'string' or 'symbol' (default)."
  unless ['string', 'symbol'].include?(type.downcase)
    if logger.nil? || logger.to_s.empty?
      puts msg
    else
      logger.debug(msg)
    end
    raise msg
  end

  case yaml
  when Hash
    yaml_doc = yaml_doc.to_hash
  when String
    yaml_doc = YAML.safe_load(yaml_doc).to_hash
  end

  begin
    convert_hash_keys(
      object: yaml_doc,
      format: 'snake',
      type: type.downcase
    )
  rescue RuntimeError => error
    raise error
  end
end