Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/speedflow/core_ext/hash.rb

Overview

Hash core extension

Direct Known Subclasses

Speedflow::Configuration

Instance Method Summary collapse

Instance Method Details

#hash_values_from_keys_schema(keys, hash) ⇒ Object

Public: Get hash value from keys schema

keys - String of keys. hash - Hash to parse.

Examples

hash_values_from_keys_schema('foo.bar', {foo: {bar: 'qux'}})
# => 'qux'

Returns String value.



71
72
73
74
75
76
77
78
# File 'lib/speedflow/core_ext/hash.rb', line 71

def hash_values_from_keys_schema(keys, hash)
  value = {}
  keys.split('.').each do |key, _|
    value = value.stringify_keys[key] unless value.nil?
    value = hash.stringify_keys[key] if value.nil?
  end
  value
end

#replace_values(pattern, hash = nil, &block) ⇒ Object

Public: Replace values from pattern.

pattern - Used to define the pattern to match. hash - Default hash. block - Used to work outside

TODO Re-enable Rubocop […] rubocop:disable MethodLength, PerceivedComplexity, CyclomaticComplexity

Returns Hash.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/speedflow/core_ext/hash.rb', line 13

def replace_values(pattern, hash = nil, &block)
  hash = self if hash.nil?
  hash.each do |hash_key, hash_value|
    if hash_value.is_a?(String) && hash_value =~ pattern
      hash[hash_key] = yield(hash_value)
    elsif hash_value.is_a?(Hash)
      replace_values(pattern, hash_value, &block)
    elsif hash_value.is_a?(Array)
      hash_value.flatten.each_with_index do |array_v, array_i|
        replace_values(pattern, array_v, &block) if array_v.is_a?(Hash)
        hash_value[array_i] = yield(array_v) if array_v.is_a?(String)
      end
    end
  end
  hash
end

#replace_values_from_env(hash = nil) ⇒ Object

Public: Change Hash values with environment values.

Replace ENV_VAR by ENV.

hash - Hash to change (default is current Hash).

Returns Hash.



38
39
40
41
42
43
# File 'lib/speedflow/core_ext/hash.rb', line 38

def replace_values_from_env(hash = nil)
  pattern = /\{([A-Z0-9_]+)\}/
  replace_values(pattern, hash) do |value|
    value.gsub(pattern) { |m| ENV[m.gsub(pattern, '\1')] }
  end
end

#replace_values_from_previous(prev_values, hash = nil) ⇒ Object

Public: Replace values from previous values.

prev_values - Hash of values. hash - Default hash.

Returns Hash.



51
52
53
54
55
56
57
58
# File 'lib/speedflow/core_ext/hash.rb', line 51

def replace_values_from_previous(prev_values, hash = nil)
  pattern = /\{previous\.((?!\.)(?!.*\.\.)[A-Za-z0-9_\.]+(?<!\.))\}/
  replace_values(pattern, hash) do |value|
    value.gsub(pattern) do |m|
      hash_values_from_keys_schema(m.gsub(pattern, '\1'), prev_values)
    end
  end
end