Module: MockServer::UtilityMethods

Included in:
AbstractClient, MockServerClient, Model::Expectation, MockServerCLI
Defined in:
lib/mockserver/utility_methods.rb

Overview

A module that has common utility methods used by this project

@author

Nayyara Samuel (mailto: [email protected])

Instance Method Summary collapse

Instance Method Details

#camelize(str) ⇒ String

Returns the string converted to camelcase with first letter in lower case.

Parameters:

  • str (Object)

    an object to camelize the string representation of

Returns:

  • (String)

    the string converted to camelcase with first letter in lower case



47
48
49
# File 'lib/mockserver/utility_methods.rb', line 47

def camelize(str)
  str.to_s.camelize(:lower)
end

#camelized_hash(obj) ⇒ Hash

Does the following filter/transform operations on a hash

  • exclude null or empty valued keys from the hash

  • camelize the keys of the hash

rubocop:disable Style/MethodLength rubocop:disable Style/CyclomaticComplexity

Parameters:

  • obj (Object)

    an object which will be used to create the hash. Must support :to_hash method

Returns:

  • (Hash)

    the transformed hash



17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/mockserver/utility_methods.rb', line 17

def camelized_hash(obj)
  obj = obj && obj.respond_to?(:to_hash) ? obj.to_hash : obj

  if obj.is_a?(Hash)
    obj.each_with_object({}) do |(k, v), acc|
      is_empty         = v.nil? || (v.respond_to?(:empty?) ? v.empty? : false)
      acc[camelize(k)] = camelized_hash(v) unless is_empty
    end
  elsif obj.respond_to?(:map)
    obj.map { |element| camelized_hash(element) }
  else
    obj
  end
end

#parse_string_to_json(response) ⇒ Hash

Parse string response into JSON

Parameters:

  • response (Response)

    from RestClient response

Returns:

  • (Hash)

    the parsed response or the object unmodified if parsing is not possible



54
55
56
57
58
# File 'lib/mockserver/utility_methods.rb', line 54

def parse_string_to_json(response)
  JSON.parse(response)
rescue JSON::ParserError
  response
end

#symbolize_keys(hash) ⇒ Hash

Converts keys to symbols

Parameters:

  • hash (Hash)

    a hash

Returns:

  • (Hash)

    a copy of the hash where keys are symbols



35
36
37
38
39
40
41
42
43
# File 'lib/mockserver/utility_methods.rb', line 35

def symbolize_keys(hash)
  if hash.is_a?(Hash)
    Hash[hash.map { |k, v| [k.to_s.underscore.to_sym, symbolize_keys(v)] }]
  elsif hash.respond_to?(:map)
    hash.map { |obj| symbolize_keys(obj) }
  else
    hash
  end
end