module Buff::Extensions::Hash::DottedPaths
Public Class Methods
included(base)
click to toggle source
# File lib/buff/extensions/hash/dotted_paths.rb, line 5 def included(base) base.send(:extend, ClassMethods) end
Public Instance Methods
berks_dig(path)
click to toggle source
Return the value of the nested hash key from the given dotted path
@example
nested_hash = { "deep" => { "nested" => { "hash" => :seed_value } } } nested_hash.berks_dig('deep.nested.hash') => :seed_value
@param [String] path
@return [Object, nil]
# File lib/buff/extensions/hash/dotted_paths.rb, line 87 def berks_dig(path) return nil unless path.present? parts = path.split('.', 2) match = self[parts[0].to_s].nil? ? self[parts[0].to_sym] : self[parts[0].to_s] if !parts[1] or match.nil? match else match.berks_dig(parts[1]) end end
dotted_paths(source = self, acc = Array.new, namespace = Array.new)
click to toggle source
Returns an array of dotted paths from the keys, values of this Hash
. Values which are nested Hashes will also recurred into and their paths will be added properly.
@param [Hash] source @param [Array] acc @param [Array] namespace
@return [Array<String>]
# File lib/buff/extensions/hash/dotted_paths.rb, line 107 def dotted_paths(source = self, acc = Array.new, namespace = Array.new) if source.is_a?(Hash) && !source.empty? source.each do |key, value| branch = namespace.dup branch << key dotted_paths(value, acc, branch) end else acc << namespace.join('.') end acc end