Skip to content

Commit 8eb4a64

Browse files
authored
Merge pull request #823 from vrtdev/feature/new_function_ifelse
(MODULES-5679) Add a new function ifelse to match ruby's tenary operator
2 parents b691910 + 001f213 commit 8eb4a64

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
@@ -1179,6 +1179,15 @@ For example, `hash(['a',1,'b',2,'c',3])` returns {'a'=>1,'b'=>2,'c'=>3}.
11791179
11801180
*Type*: rvalue.
11811181
1182+
1183+
#### `ifelse`
1184+
1185+
Shorthand version for if-else: this maps to the ruby tenary operator.
1186+
1187+
For example, `ifelse(4 > 0, 'positive', 'negative')` returns `'positive'`.
1188+
1189+
*Type*: rvalue.
1190+
11821191
#### `intersection`
11831192
11841193
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)