Sha256: 13e5efccd8513ea9771eb5c5a88ab28dabde80b17ba02fe0604379f362784f4b

Contents?: true

Size: 1.13 KB

Versions: 26

Compression:

Stored size: 1.13 KB

Contents

# Returns a value for a sequence of given keys/indexes into a structure.
# This function is used to "dig into" a complex data structure by
# using a sequence of keys / indexes to access a value from which
# the next key/index is accessed recursively.
#
# The first encountered `undef` value or key stops the "dig" and `undef` is returned.
#
# An error is raised if an attempt is made to "dig" into
# something other than an `undef` (which immediately returns `undef`), an Array or a Hash. 
#
# @example Using `dig`
#
# ~~~ puppet
# $data = {a => { b => [{x => 10, y => 20}, {x => 100, y => 200}]}}
# notice $data.dig(a, b, 1, x)
# ~~~
#
# Would notice the value 100.
#
# @since 4.5.0
#
Puppet::Functions.create_function(:dig) do
  dispatch :dig do
    param 'Optional[Collection]', :data
    repeated_param 'Any', :arg
  end

  def dig(data, *args)
    walked_path = []
    args.reduce(data) do | d, k |
      return nil if d.nil? || k.nil?
      if !(d.is_a?(Array) || d.is_a?(Hash))
        raise ArgumentError, "The given data does not contain a Collection at #{walked_path}, got '#{d.class}'"
      end
      walked_path << k
      d[k]
    end
  end
end

Version data entries

26 entries across 26 versions & 2 rubygems

Version Path
puppet-retrospec-1.5.0 vendor/gems/puppet-4.5.2/lib/puppet/functions/dig.rb
puppet-retrospec-1.4.1 vendor/gems/puppet-4.5.2/lib/puppet/functions/dig.rb
puppet-retrospec-1.4.0 vendor/gems/puppet-4.5.2/lib/puppet/functions/dig.rb
puppet-retrospec-1.3.2 vendor/gems/puppet-4.5.2/lib/puppet/functions/dig.rb
puppet-retrospec-1.3.1 vendor/gems/puppet-4.5.2/lib/puppet/functions/dig.rb
puppet-retrospec-1.3.0 vendor/gems/puppet-4.5.2/lib/puppet/functions/dig.rb
puppet-retrospec-1.2.1 vendor/gems/puppet-4.5.2/lib/puppet/functions/dig.rb
puppet-retrospec-1.2.0 vendor/gems/puppet-4.5.2/lib/puppet/functions/dig.rb
puppet-retrospec-1.1.0 vendor/gems/puppet-4.5.2/lib/puppet/functions/dig.rb
puppet-4.5.3 lib/puppet/functions/dig.rb
puppet-4.5.3-x86-mingw32 lib/puppet/functions/dig.rb
puppet-4.5.3-x64-mingw32 lib/puppet/functions/dig.rb
puppet-4.5.3-universal-darwin lib/puppet/functions/dig.rb
puppet-retrospec-1.0.0 vendor/gems/puppet-4.5.2/lib/puppet/functions/dig.rb
puppet-4.5.2 lib/puppet/functions/dig.rb
puppet-4.5.2-x86-mingw32 lib/puppet/functions/dig.rb
puppet-4.5.2-x64-mingw32 lib/puppet/functions/dig.rb
puppet-4.5.2-universal-darwin lib/puppet/functions/dig.rb
puppet-4.5.1 lib/puppet/functions/dig.rb
puppet-4.5.1-x86-mingw32 lib/puppet/functions/dig.rb