Skip to content

Commit c4620a9

Browse files
author
Dmitry Ilyin
committed
Improve parseyaml function
* Add default value support * Update tests
1 parent f820bb1 commit c4620a9

File tree

2 files changed

+12
-10
lines changed

2 files changed

+12
-10
lines changed

lib/puppet/parser/functions/parseyaml.rb

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,20 @@
33
#
44

55
module Puppet::Parser::Functions
6-
newfunction(:parseyaml, :type => :rvalue, :doc => <<-EOS
6+
newfunction(:parseyaml, :type => :rvalue, :arity => -2, :doc => <<-EOS
77
This function accepts YAML as a string and converts it into the correct
88
Puppet structure.
9+
10+
The optional second argument can be used to pass a default value that will
11+
be returned if the parsing of YAML string have failed.
912
EOS
1013
) do |arguments|
1114

12-
if (arguments.size != 1) then
13-
raise(Puppet::ParseError, "parseyaml(): Wrong number of arguments "+
14-
"given #{arguments.size} for 1")
15-
end
16-
1715
require 'yaml'
1816

19-
YAML::load(arguments[0])
20-
17+
data = YAML::load(arguments[0])
18+
data = arguments[1] unless data
19+
data
2120
end
2221
end
2322

spec/functions/parseyaml_spec.rb

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,12 @@
22

33
describe 'parseyaml' do
44
it { is_expected.not_to eq(nil) }
5-
it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError, /wrong number of arguments/i) }
6-
it { is_expected.to run.with_params('', '').and_raise_error(Puppet::ParseError, /wrong number of arguments/i) }
5+
it { is_expected.to run.with_params().and_raise_error(ArgumentError, /wrong number of arguments/i) }
76
it { is_expected.to run.with_params('["one", "two", "three"]').and_return(['one', 'two', 'three']) }
7+
it { is_expected.to run.with_params('', 'default_value').and_return('default_value') }
8+
it { is_expected.to run.with_params('', { 'a' => '1' }).and_return({ 'a' => '1' }) }
9+
it { is_expected.to run.with_params("---\na: '1'\n").and_return({ 'a' => '1' }) }
10+
it { is_expected.to run.with_params("---\na: '1'\n", 'default_value').and_return({ 'a' => '1' }) }
811
context 'when running on modern rubies', :unless => RUBY_VERSION == '1.8.7' do
912
it { is_expected.to run.with_params('["one"').and_raise_error(Psych::SyntaxError) }
1013
end

0 commit comments

Comments
 (0)