Skip to content

Commit 001f213

Browse files
committed
(MODULES-5679) Add a new function ifelse to match ruby's tenary operator
1 parent 2339ea8 commit 001f213

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1171,6 +1171,15 @@ For example, `hash(['a',1,'b',2,'c',3])` returns {'a'=>1,'b'=>2,'c'=>3}.
11711171
11721172
*Type*: rvalue.
11731173
1174+
1175+
#### `ifelse`
1176+
1177+
Shorthand version for if-else: this maps to the ruby tenary operator.
1178+
1179+
For example, `ifelse(4 > 0, 'positive', 'negative')` returns `'positive'`.
1180+
1181+
*Type*: rvalue.
1182+
11741183
#### `intersection`
11751184
11761185
Returns an array an intersection of two.

lib/puppet/functions/ifelse.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Shorthand for bool ? true value : false value.
2+
#
3+
# @example
4+
# $number_sign = ifelse($i >= 0, "positive", "negative")
5+
#
6+
Puppet::Functions.create_function(:ifelse) do
7+
# @param bool Boolean condition
8+
# @param iftrue Value to return if condition is true.
9+
# @param iffalse Value to return if condition is false.
10+
# @return Value from `$iftrue` or `$iffalse` depending on the boolean condition.
11+
dispatch :ifelse do
12+
param 'Boolean', :bool
13+
param 'Any', :iftrue
14+
param 'Any', :iffalse
15+
end
16+
17+
def ifelse(bool, iftrue, iffalse)
18+
bool ? iftrue : iffalse
19+
end
20+
end

spec/functions/ifelse_spec.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
require 'spec_helper'
2+
3+
describe 'ifelse' do
4+
it { is_expected.not_to eq(nil) }
5+
it { is_expected.to run.with_params.and_raise_error(ArgumentError, %r{expects 3 arguments}i) }
6+
it { is_expected.to run.with_params('1').and_raise_error(ArgumentError, %r{expects 3 arguments}i) }
7+
8+
it { is_expected.to run.with_params('false', 'iftrue', 'iffalse').and_raise_error(ArgumentError, %r{parameter 'bool' expects a Boolean value}i) }
9+
10+
it { is_expected.to run.with_params(false, 'iftrue', 'iffalse').and_return('iffalse') }
11+
it { is_expected.to run.with_params(true, 'iftrue', 'iffalse').and_return('iftrue') }
12+
it { is_expected.to run.with_params(true, :undef, 'iffalse').and_return(:undef) }
13+
it { is_expected.to run.with_params(true, nil, 'iffalse').and_return(nil) }
14+
end

0 commit comments

Comments
 (0)