1 # TODO(Krzysztof Wilczynski): We need to add support for regular expression ...
2 # TODO(Krzysztof Wilczynski): Support for strings and hashes too ...
6 module Puppet::Parser::Functions
7 newfunction(:member, :type => :rvalue, :doc => <<-DOC
8 This function determines if a variable is a member of an array.
9 The variable can be a string, fixnum, or array.
13 member(['a','b'], 'b')
17 member(['a', 'b', 'c'], ['a', 'b'])
21 member(['a','b'], 'c')
25 member(['a', 'b', 'c'], ['d', 'b'])
29 Note: Since Puppet 4.0.0 the same can be performed in the Puppet language. For single values
30 the operator `in` can be used:
32 'a' in ['a', 'b'] # true
34 And for arrays by using operator `-` to compute a diff:
36 ['d', 'b'] - ['a', 'b', 'c'] == [] # false because 'd' is not subtracted
37 ['a', 'b'] - ['a', 'b', 'c'] == [] # true because both 'a' and 'b' are subtracted
39 Also note that since Puppet 5.2.0 the general form of testing content of an array or hash is to use the built-in
40 `any` and `all` functions.
44 raise(Puppet::ParseError, "member(): Wrong number of arguments given (#{arguments.size} for 2)") if arguments.size < 2
48 unless array.is_a?(Array)
49 raise(Puppet::ParseError, 'member(): Requires array to work with')
52 unless arguments[1].is_a?(String) || arguments[1].is_a?(Integer) || arguments[1].is_a?(Array)
53 raise(Puppet::ParseError, 'member(): Item to search for must be a string, fixnum, or array')
56 item = if arguments[1].is_a?(String) || arguments[1].is_a?(Integer)
62 raise(Puppet::ParseError, 'member(): You must provide item to search for within array given') if item.respond_to?('empty?') && item.empty?
64 result = (item - array).empty?
70 # vim: set ts=2 sw=2 et :