Skip to content

(MODULES-5679) Add a new function ifelse to match ruby's tenary operator #823

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 27, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
20 changes: 20 additions & 0 deletions lib/puppet/functions/ifelse.rb
Original file line number Diff line number Diff line change
@@ -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
14 changes: 14 additions & 0 deletions spec/functions/ifelse_spec.rb
Original file line number Diff line number Diff line change
@@ -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