From 8d217f0012fef332642faf485ad187773a95bcc1 Mon Sep 17 00:00:00 2001 From: Steve Huff Date: Fri, 29 Mar 2013 15:06:36 -0400 Subject: (19864) num2bool match fix This is a bit more heavy-handed than I might like, but it does appear to do the right things: * accepts numeric input appropriately, truncating floats * matches string input against a regex, then coerces number-looking strings to int * makes a best effort to coerce anything else to a string, then subjects it to the same treatment * raises an error in the event of incorrect number of arguments or non-number-looking strings I've also included some additional unit tests. --- lib/puppet/parser/functions/num2bool.rb | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) (limited to 'lib/puppet') diff --git a/lib/puppet/parser/functions/num2bool.rb b/lib/puppet/parser/functions/num2bool.rb index 15dd560..cf98f80 100644 --- a/lib/puppet/parser/functions/num2bool.rb +++ b/lib/puppet/parser/functions/num2bool.rb @@ -13,13 +13,32 @@ become true. raise(Puppet::ParseError, "num2bool(): Wrong number of arguments " + "given (#{arguments.size} for 1)") if arguments.size != 1 - # we need to get an Integer out of this - begin - number = arguments[0].to_i - rescue NoMethodError - raise(Puppet::ParseError, 'num2bool(): Unable to parse number: ' + $!) + number = arguments[0] + + case number + when Numeric + # Yay, it's a number + when String + # Deal with strings later + else + begin + number = number.to_s + rescue NoMethodError + raise(Puppet::ParseError, 'num2bool(): Unable to parse argument: ' + $!) + end + end + + case number + when String + # Only accept strings that look somewhat like numbers + unless number =~ /^-?\d+/ + raise(Puppet::ParseError, "num2bool(): '#{number}' does not look like a number") + end end + # Truncate floats + number = number.to_i + # Return true for any positive number and false otherwise return number > 0 ? true : false end -- cgit v1.2.3