From 23a51084f61c4ce16bef7311725ecbab33f1ac97 Mon Sep 17 00:00:00 2001 From: Richard Clark Date: Sun, 11 May 2014 16:03:06 +0100 Subject: [PATCH] to_yaml function added. * Makes use of ZAML.dump --- lib/puppet/parser/functions/to_yaml.rb | 21 +++++++++++++++++++ spec/functions/to_yaml_spec.rb | 28 ++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 lib/puppet/parser/functions/to_yaml.rb create mode 100644 spec/functions/to_yaml_spec.rb diff --git a/lib/puppet/parser/functions/to_yaml.rb b/lib/puppet/parser/functions/to_yaml.rb new file mode 100644 index 000000000..c7f82c7fd --- /dev/null +++ b/lib/puppet/parser/functions/to_yaml.rb @@ -0,0 +1,21 @@ +# +# to_yaml.rb +# + +module Puppet::Parser::Functions + newfunction(:to_yaml, :type => :rvalue, :doc => <<-EOS +This function accepts a puppet data structure (I.E hash/array/string or nested combination of these) and converts it into a yaml format string, so that YAML files can be written using the content param in the file provider. + EOS + ) do |arguments| + + if (arguments.size != 1) then + raise(Puppet::ParseError, "to_yaml(): Wrong number of arguments "+ + "given #{arguments.size} for 1") + end + + ZAML.dump(arguments[0]) + + end +end + +# vim: set ts=2 sw=2 et : diff --git a/spec/functions/to_yaml_spec.rb b/spec/functions/to_yaml_spec.rb new file mode 100644 index 000000000..bc5c8a6fd --- /dev/null +++ b/spec/functions/to_yaml_spec.rb @@ -0,0 +1,28 @@ +#! /usr/bin/env ruby -S rspec +require 'spec_helper' + +describe "the to_yaml function" do + let(:scope) { PuppetlabsSpec::PuppetInternals.scope } + + it "should exist" do + Puppet::Parser::Functions.function("to_yaml").should == "function_to_yaml" + end + + it "should raise a ParseError if there is less than 1 arguments" do + lambda { scope.function_to_yaml([]) }.should( raise_error(Puppet::ParseError)) + end + + it "should convert a data structure to YAML" do + yaml_data = { + 'string' => 'a string', + 'array' => ['aaa', 'bbb', 'ccc' ], + 'bool' => true, + 'hash' => { + 'string' => 'indeed it is', + 'another_string' => 'quite so' + }, + } + result = scope.function_to_yaml([yaml_data]) + result.should(eq("#{yaml_data.to_yaml}")) + end +end