puppetlabs-stdlib/lib/puppet/parser/functions/delete_values.rb
Leonardo Rodrigues de Mello 51d96088c1 (#20681) fix behaviour of delete_values
The issue #20681 describe the error of delete() function
removing the elements from the origin array/hash/string.

This issue affected other delete functions. Because
ruby delete and delete_if functions make destructive
changes to the origin array/hash.

The delete_undef_values removed elements from the
origin hash and this is not the desired behaviour.

To solve this, we should dup or clone the hash
before using the delete or delete_if ruby functions.

This fix the problem and add unit tests, so we could
enforce this behaviour and prevent regressions.
2013-09-17 12:05:23 -03:00

26 lines
728 B
Ruby

module Puppet::Parser::Functions
newfunction(:delete_values, :type => :rvalue, :doc => <<-EOS
Deletes all instances of a given value from a hash.
*Examples:*
delete_values({'a'=>'A','b'=>'B','c'=>'C','B'=>'D'}, 'B')
Would return: {'a'=>'A','c'=>'C','B'=>'D'}
EOS
) do |arguments|
raise(Puppet::ParseError,
"delete_values(): Wrong number of arguments given " +
"(#{arguments.size} of 2)") if arguments.size != 2
hash, item = arguments
if not hash.is_a?(Hash)
raise(TypeError, "delete_values(): First argument must be a Hash. " + \
"Given an argument of class #{hash.class}.")
end
hash.dup.delete_if { |key, val| item == val }
end
end