Class: Pal::SafeHashParse

Inherits:
Object
  • Object
show all
Defined in:
lib/pal/common/safe_hash_parse.rb

Overview

The most lazy way to find things in hashes and JSON. Provides default and optional params Provides safe navigation with hash key dot notation (‘this.is.a.key’)

Class Method Summary collapse

Class Method Details

.all_values(hash) ⇒ Object

Parameters:

  • hash (Hash)


82
83
84
# File 'lib/pal/common/safe_hash_parse.rb', line 82

def all_values(hash)
  hash.flat_map { |_k, v| (v.is_a?(Hash) ? all_values(v) : [v]) }
end

.all_values_from_json(json) ⇒ Object

Parameters:

  • json (String)


77
78
79
# File 'lib/pal/common/safe_hash_parse.rb', line 77

def all_values_from_json(json)
  all_values(JSON.parse(json))
end

.extract_from_hash(hash, search_key, optional = false, default = nil) ⇒ Object?

rubocop:disable Metrics/AbcSize rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/PerceivedComplexity

Parameters:

  • hash (Hash)
  • search_key (Object)
  • optional (Boolean) (defaults to: false)
  • default (Object, nil) (defaults to: nil)

Returns:

  • (Object, nil)


38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/pal/common/safe_hash_parse.rb', line 38

def extract_from_hash(hash, search_key, optional=false, default=nil)
  keys = format_key(search_key)
  last_level = hash
  searched = nil

  keys.each_with_index do |key, index|
    break unless last_level.is_a?(Hash) && last_level.key?(key.to_s)

    if index + 1 == keys.length
      searched = last_level[key.to_s] || last_level[key.to_sym]
    else
      last_level = last_level[key.to_s] || last_level[key.to_sym]
    end
  end

  return searched if searched
  return nil unless optional

  default
end

.extract_from_json(json_str, key, optional = false, default = nil) ⇒ Array

Parameters:

  • json_str (String)
  • key (Object)
  • optional (Boolean) (defaults to: false)
  • default (Object) (defaults to: nil)

Returns:

  • (Array)


18
19
20
21
22
23
24
25
26
27
28
# File 'lib/pal/common/safe_hash_parse.rb', line 18

def extract_from_json(json_str, key, optional=false, default=nil)
  val = JsonPath.new(key.to_s).on(json_str)
  return val if val && !val.empty?
  return [] unless optional

  [default]
rescue JSON::ParserError, MultiJson::ParseError, ArgumentError => e
  raise e unless optional

  [default]
end

.format_key(key) ⇒ Array

Parameters:

  • key (Object)

Returns:

  • (Array)

Raises:

  • (ArgumentError)


64
65
66
67
68
69
70
71
72
73
74
# File 'lib/pal/common/safe_hash_parse.rb', line 64

def format_key(key)
  return [key.downcase] if key.is_a?(Symbol)

  if key.is_a?(String)
    return [key.downcase.to_sym] unless key.include?(".")

    return key.to_s.split(".").map { |s| s.downcase.to_sym }
  end

  raise ArgumentError, "Key [#{key}] must be either a String or Symbol"
end