From 870a272cee6889934d60c4bfd7a814bcf47011f1 Mon Sep 17 00:00:00 2001 From: Dmitry Ilyin Date: Tue, 26 Apr 2016 21:51:43 +0300 Subject: Add the default value to the "loadyaml" function This value will be returned if the is no file to load or a file could not be parsed. It's similar to the "parseyaml" function's default value. Add the "loadjson" function too --- lib/puppet/parser/functions/loadjson.rb | 34 +++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 lib/puppet/parser/functions/loadjson.rb (limited to 'lib/puppet/parser/functions/loadjson.rb') diff --git a/lib/puppet/parser/functions/loadjson.rb b/lib/puppet/parser/functions/loadjson.rb new file mode 100644 index 0000000..3a3372b --- /dev/null +++ b/lib/puppet/parser/functions/loadjson.rb @@ -0,0 +1,34 @@ +module Puppet::Parser::Functions + newfunction(:loadjson, :type => :rvalue, :arity => -2, :doc => <<-'ENDHEREDOC') do |args| +Load a JSON file containing an array, string, or hash, and return the data +in the corresponding native data type. +The second parameter is the default value. It will be returned if the file +was not found or could not be parsed. + +For example: + + $myhash = loadjson('/etc/puppet/data/myhash.json') + $myhash = loadjson('no-file.json', {'default' => 'value'}) + ENDHEREDOC + + raise ArgumentError, 'Wrong number of arguments. 1 or 2 arguments should be provided.' unless args.length >= 1 + + if File.exists?(args[0]) + begin + content = File.read(args[0]) + PSON::load(content) || args[1] + rescue Exception => e + if args[1] + args[1] + else + raise e + end + end + else + warning("Can't load '#{args[0]}' File does not exist!") + args[1] + end + + end + +end -- cgit v1.2.3