From 3cef5d9e3323115c896e76f9e217cac061ab156f Mon Sep 17 00:00:00 2001 From: fatmcgav Date: Tue, 12 Feb 2013 15:07:18 +0000 Subject: (#19201) Add concat function to join two arrays Without this patch applied there is no easy way to append one array to another. This is a problem because it is often desirable to join two arrays without flattening the contents into a single, one dimensional array. This patch addresses the problem by adding a `concat()` function which takes two arguments. The arguments will be concatenated together and a new array returned to the caller. Reviewed-by: Jeff McCune --- README.markdown | 7 +++++ lib/puppet/parser/functions/concat.rb | 37 ++++++++++++++++++++++++ spec/unit/puppet/parser/functions/concat_spec.rb | 15 ++++++++++ 3 files changed, 59 insertions(+) create mode 100644 lib/puppet/parser/functions/concat.rb create mode 100644 spec/unit/puppet/parser/functions/concat_spec.rb diff --git a/README.markdown b/README.markdown index 922383c..c58d31f 100644 --- a/README.markdown +++ b/README.markdown @@ -96,6 +96,13 @@ separators then you should use the `chomp` function. Requires a string or array of strings as input. +- *Type*: rvalue + +concat +----- +Appends the contents of the second array onto the first array. + + - *Type*: rvalue defined_with_params diff --git a/lib/puppet/parser/functions/concat.rb b/lib/puppet/parser/functions/concat.rb new file mode 100644 index 0000000..c86aa00 --- /dev/null +++ b/lib/puppet/parser/functions/concat.rb @@ -0,0 +1,37 @@ +# +# concat.rb +# + +module Puppet::Parser::Functions + newfunction(:concat, :type => :rvalue, :doc => <<-EOS +Appends the contents of array 2 onto array 1. + +*Example:* + + concat(['1','2','3'],['4','5','6']) + +Would result in: + + ['1','2','3','4','5','6'] + EOS + ) do |arguments| + + # Check that 2 arguments have been given ... + raise(Puppet::ParseError, "concat(): Wrong number of arguments " + + "given (#{arguments.size} for 2)") if arguments.size != 2 + + a = arguments[0] + b = arguments[1] + + # Check that both args are arrays. + unless a.is_a?(Array) and b.is_a?(Array) + raise(Puppet::ParseError, 'concat(): Requires array to work with') + end + + result = a.concat(b) + + return result + end +end + +# vim: set ts=2 sw=2 et : diff --git a/spec/unit/puppet/parser/functions/concat_spec.rb b/spec/unit/puppet/parser/functions/concat_spec.rb new file mode 100644 index 0000000..123188b --- /dev/null +++ b/spec/unit/puppet/parser/functions/concat_spec.rb @@ -0,0 +1,15 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the concat function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_concat([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should be able to concat an array" do + result = scope.function_concat([['1','2','3'],['4','5','6']]) + result.should(eq(['1','2','3','4','5','6'])) + end +end -- cgit v1.2.3