Module: HashExtensions::InstanceMethods
- Defined in:
- lib/eventhub/hash_extensions.rb
Overview
InstanceMethods module
Instance Method Summary collapse
-
#all_keys_with_path(parent = nil) ⇒ Object
get all keys with path, { ‘a’ => ‘v1’, ‘b’ => { ‘c’ => ‘v2’}}.all_keys_with_path => [‘a’,‘b.c’].
-
#get(arg) ⇒ Object
get value from provided key path e.g.
-
#set(arg, value, overwrite = true) ⇒ Object
set value from provided key path, e.h.
Instance Method Details
#all_keys_with_path(parent = nil) ⇒ Object
get all keys with path, { ‘a’ => ‘v1’, ‘b’ => { ‘c’ => ‘v2’}}.all_keys_with_path => [‘a’,‘b.c’]
30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/eventhub/hash_extensions.rb', line 30 def all_keys_with_path(parent = nil) a = [] each do |k, v| if v.is_a?(Hash) a << v.all_keys_with_path([parent, k].compact.join('.')) else a << [parent, k].compact.join('.').to_s end end a.flatten end |
#get(arg) ⇒ Object
get value from provided key path e.g. hash.get(%w(event_hub plate.queue1 retry_s)) “a” => { “b” => { “c” => { “value”}}}
12 13 14 15 |
# File 'lib/eventhub/hash_extensions.rb', line 12 def get(arg) path = arg.is_a?(String) ? arg.split('.') : arg path.inject(self, :[]) end |
#set(arg, value, overwrite = true) ⇒ Object
set value from provided key path, e.h. hash.set(‘a.b.c’,‘new value’) if overwrite is false, value will be set if it was nil previously
19 20 21 22 23 24 25 26 |
# File 'lib/eventhub/hash_extensions.rb', line 19 def set(arg, value, overwrite = true) *key_path, last = arg.is_a?(String) ? arg.split('.') : arg if overwrite key_path.inject(self) { |h, key| h.key?(key) ? h[key] : h[key] = {} } [last] = value else key_path.inject(self) { |h, key| h.key?(key) ? h[key] : h[key] = {} } [last] ||= value end end |