1



I need to write a case using some ranges in order to write in a better way something like the following spaghetti code :

if $mem < 1024 { $retvalue = "128M" } elsif $mem < 7000 { $retvalue = "160M" } elsif $mem < 15000 { $retvalue = "192M" } elsif $mem < 31000 { $retvalue = "256M" } else { $retvalue = "512M" }

Is it possible to use a case statements by using the range fuction (on stdlib) or something better than that ?


BR
Giuseppe

2 Answers 2

0

For ranges of this magnitude, I would advise to refrain from creating ranges (i.e., arrays full of integer values for scanning).

Your approach is solid. If you really want a case statement, you could go for a piece of Ruby code and the inline_template function, but that has a performance penalty and does not add much in terms of maintainability.

1

Puppet's case statement can evaluate expressions and will run the first associated with the first matching case.

It doesn't quite support this:

case $mem {
  0..1023:      { $retvalue = "128M" }
  1024..6999:   { $retvalue = "160M" }
  7000...14999: { $retvalue = "192M" }
  15000..30999: { $retvalue = "256M" }
  default:      { $retvalue = "512M" }
}

However you can give it expressions and tell it to match the first one that's true.

So you can do this:

case true {
  $mem < 1024:  { $retvalue = "128M" }
  $mem < 7000:  { $retvalue = "160M" }
  $mem < 15000: { $retvalue = "192M" }
  $mem < 31000: { $retvalue = "256M" }
  default:      { $retvalue = "512M" }
}

Similarly you could use a selector to return the right value:

$retvalue = true ? {
  $mem < 1024  => "128M",
  $mem < 7000  => "160M",
  $mem < 15000 => "192M",
  $mem < 31000 => "256M",
  default      => "512M",
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .