Skip to content

Commit 3ac3241

Browse files
committed
Add clamp function
Clamp keeps value within the range. Employ of soft() makes the whole thing is independant of order.
1 parent 61333cf commit 3ac3241

3 files changed

Lines changed: 84 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
#
2+
# clamp.rb
3+
#
4+
5+
module Puppet::Parser::Functions
6+
newfunction(:clamp, :type => :rvalue, :doc => <<-EOS
7+
Clamps value to a range.
8+
EOS
9+
) do |args|
10+
11+
raise(Puppet::ParseError, "clamp(): Wrong number of arguments " +
12+
"need at least one") if args.size < 1
13+
14+
result = []
15+
16+
args.each do |x|
17+
if x.is_a?(Array)
18+
result += x
19+
else
20+
result << x
21+
end
22+
end
23+
24+
raise(Puppet::ParseError, "clamp(): Wrong number/type of arguments " +
25+
"need three to clamp") if result.size != 3
26+
27+
result.map{ |n| n.to_i }.sort[1]
28+
end
29+
end
30+
31+
# vim: set ts=2 sw=2 et :

spec/acceptance/clamp_spec.rb

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#! /usr/bin/env ruby -S rspec
2+
require 'spec_helper_acceptance'
3+
4+
describe 'clamp function', :unless => UNSUPPORTED_PLATFORMS.include?(fact('operatingsystem')) do
5+
describe 'success' do
6+
it 'clamps list of values' do
7+
pp = <<-EOS
8+
$x = 17
9+
$y = 225
10+
$z = 155
11+
$o = clamp($x, $y, $z)
12+
if $o == $z {
13+
notify { 'output correct': }
14+
}
15+
EOS
16+
17+
apply_manifest(pp, :catch_failures => true) do |r|
18+
expect(r.stdout).to match(/Notice: output correct/)
19+
end
20+
end
21+
it 'clamps array of values' do
22+
pp = <<-EOS
23+
$a = [7, 19, 66]
24+
$b = 19
25+
$o = clamp($a)
26+
if $o == $b {
27+
notify { 'output correct': }
28+
}
29+
EOS
30+
31+
apply_manifest(pp, :catch_failures => true) do |r|
32+
expect(r.stdout).to match(/Notice: output correct/)
33+
end
34+
end
35+
end
36+
describe 'failure' do
37+
it 'handles improper argument counts'
38+
it 'handles no arguments'
39+
end
40+
end

spec/functions/clamp_spec.rb

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
require 'spec_helper'
2+
3+
describe 'clamp' do
4+
it { is_expected.not_to eq(nil) }
5+
it { is_expected.to run.with_params().and_raise_error(Puppet::ParseError) }
6+
it { is_expected.to run.with_params("string1").and_raise_error(Puppet::ParseError) }
7+
it { is_expected.to run.with_params([]).and_raise_error(Puppet::ParseError) }
8+
it { is_expected.to run.with_params([4,3,99]).and_return(4) }
9+
it { is_expected.to run.with_params(444,3,99).and_return(99) }
10+
it { is_expected.to run.with_params([4,873],73).and_return(73) }
11+
it { is_expected.to run.with_params([4],8,99).and_return(8) }
12+
it { is_expected.to run.with_params([4],[31], 9911).and_return(31) }
13+
end

0 commit comments

Comments
 (0)