Sha256: c8ea6da8c338658af338b08be617362a222f3f43cb055e37c78bfa75e0060ad3

Contents?: true

Size: 1.42 KB

Versions: 1

Compression:

Stored size: 1.42 KB

Contents

# encoding: UTF-8
require 'active_support/inflector'
require 'json'

#
# A module that has common utility methods used by this project
# @author:: Nayyara Samuel (mailto: nayyara.samuel@opower.com)
#
module MockServer::UtilityMethods
  # Does the following filter/transform operations on a hash
  # - exclude null or empty valued keys from the hash
  # - camelize the keys of the hash
  # @param hash [Object] an object which will be used to create the hash. Must support :to_hash method
  # @return [Hash] the transformed hash
  def prepare_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)] = prepare_hash(v) unless is_empty
      end
    elsif obj.respond_to?(:map)
      obj.map { |element| prepare_hash(element) }
    else
      obj
    end
  end

  # @param [Object] an object to camelize the string representation of
  # @return [String] the string converted to camelcase with first letter in lower case
  def camelize(str)
    str.to_s.camelize(:lower)
  end

  # Parse string response into JSON
  # @param response [Response] from RestClient response
  # @return [Hash] the parsed response or the object unmodified if parsing is not possible
  def parse_response(response)
    JSON.parse(response)
  rescue JSON::ParserError
    response
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
mockserver-client-0.0.1 lib/mockserver/utility_methods.rb