Skip to content

Commit c9f906f

Browse files
committed
(MODULES-1329) Allow member function to look for array
Currently, the member function allows one to only find if a variable is part of an array. Sometimes it is useful to find if an array is part of a bigger array for validation purpose.
1 parent 85d7edd commit c9f906f

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

lib/puppet/parser/functions/member.rb

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,25 @@
88
module Puppet::Parser::Functions
99
newfunction(:member, :type => :rvalue, :doc => <<-EOS
1010
This function determines if a variable is a member of an array.
11+
The variable can either be a string or an array.
1112
1213
*Examples:*
1314
1415
member(['a','b'], 'b')
1516
1617
Would return: true
1718
19+
member(['a', 'b', 'c'], ['a', 'b'])
20+
21+
would return: true
22+
1823
member(['a','b'], 'c')
1924
2025
Would return: false
26+
27+
member(['a', 'b', 'c'], ['d', 'b'])
28+
29+
would return: false
2130
EOS
2231
) do |arguments|
2332

@@ -30,13 +39,17 @@ module Puppet::Parser::Functions
3039
raise(Puppet::ParseError, 'member(): Requires array to work with')
3140
end
3241

33-
item = arguments[1]
42+
if arguments[1].is_a? String
43+
item = Array(arguments[1])
44+
else
45+
item = arguments[1]
46+
end
3447

3548

3649
raise(Puppet::ParseError, 'member(): You must provide item ' +
3750
'to search for within array given') if item.respond_to?('empty?') && item.empty?
3851

39-
result = array.include?(item)
52+
result = (item - array).empty?
4053

4154
return result
4255
end

spec/functions/member_spec.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,4 +21,14 @@
2121
result = scope.function_member([["a","b","c"], "d"])
2222
expect(result).to(eq(false))
2323
end
24+
25+
it "should return true if a member array is in an array" do
26+
result = scope.function_member([["a","b","c"], ["a", "b"]])
27+
expect(result).to(eq(true))
28+
end
29+
30+
it "should return false if a member array is not in an array" do
31+
result = scope.function_member([["a","b","c"], ["d", "e"]])
32+
expect(result).to(eq(false))
33+
end
2434
end

0 commit comments

Comments
 (0)