diff --git a/README.md b/README.md index 2b6a64bd9..5696a8ab1 100644 --- a/README.md +++ b/README.md @@ -1171,6 +1171,15 @@ For example, `hash(['a',1,'b',2,'c',3])` returns {'a'=>1,'b'=>2,'c'=>3}. *Type*: rvalue. + +#### `ifelse` + +Shorthand version for if-else: this maps to the ruby tenary operator. + +For example, `ifelse(4 > 0, 'positive', 'negative')` returns `'positive'`. + +*Type*: rvalue. + #### `intersection` Returns an array an intersection of two. diff --git a/lib/puppet/functions/ifelse.rb b/lib/puppet/functions/ifelse.rb new file mode 100644 index 000000000..a264c52d6 --- /dev/null +++ b/lib/puppet/functions/ifelse.rb @@ -0,0 +1,20 @@ +# Shorthand for bool ? true value : false value. +# +# @example +# $number_sign = ifelse($i >= 0, "positive", "negative") +# +Puppet::Functions.create_function(:ifelse) do + # @param bool Boolean condition + # @param iftrue Value to return if condition is true. + # @param iffalse Value to return if condition is false. + # @return Value from `$iftrue` or `$iffalse` depending on the boolean condition. + dispatch :ifelse do + param 'Boolean', :bool + param 'Any', :iftrue + param 'Any', :iffalse + end + + def ifelse(bool, iftrue, iffalse) + bool ? iftrue : iffalse + end +end diff --git a/spec/functions/ifelse_spec.rb b/spec/functions/ifelse_spec.rb new file mode 100644 index 000000000..283fb3913 --- /dev/null +++ b/spec/functions/ifelse_spec.rb @@ -0,0 +1,14 @@ +require 'spec_helper' + +describe 'ifelse' do + it { is_expected.not_to eq(nil) } + it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{expects 3 arguments}i) } + it { is_expected.to run.with_params('1').and_raise_error(ArgumentError, %r{expects 3 arguments}i) } + + it { is_expected.to run.with_params('false', 'iftrue', 'iffalse').and_raise_error(ArgumentError, %r{parameter 'bool' expects a Boolean value}i) } + + it { is_expected.to run.with_params(false, 'iftrue', 'iffalse').and_return('iffalse') } + it { is_expected.to run.with_params(true, 'iftrue', 'iffalse').and_return('iftrue') } + it { is_expected.to run.with_params(true, :undef, 'iffalse').and_return(:undef) } + it { is_expected.to run.with_params(true, nil, 'iffalse').and_return(nil) } +end