]> gitweb.fluxo.info Git - puppet-stdlib.git/commitdiff
Allow comparisons of Numeric and number as String
authorErik Dalén <dalen@spotify.com>
Wed, 20 Mar 2013 15:36:20 +0000 (16:36 +0100)
committerAdrien Thebo <git@somethingsinistral.net>
Wed, 27 Mar 2013 21:03:31 +0000 (14:03 -0700)
Puppet passes numbers as String to functions, but it makes more sense to
compare them as Numeric.
But sometimes Puppet passes them as the wrong type, see:
https://projects.puppetlabs.com/issues/19812

lib/puppet/parser/functions/max.rb
lib/puppet/parser/functions/min.rb
spec/unit/puppet/parser/functions/max_spec.rb
spec/unit/puppet/parser/functions/min_spec.rb

index 10b6f7432d67dbd0f8a7f14306c3c51d8c3567ad..60fb94ac041ce6a06455e438986eb204be585e9f 100644 (file)
@@ -8,6 +8,14 @@ module Puppet::Parser::Functions
     raise(Puppet::ParseError, "max(): Wrong number of arguments " +
           "need at least one") if args.size == 0
 
-    return args.max
+    # Sometimes we get numbers as numerics and sometimes as strings.
+    # We try to compare them as numbers when possible
+    return args.max do |a,b|
+      if a.to_s =~ /\A-?\d+(.\d+)?\z/ and b.to_s =~ /\A-?\d+(.\d+)?\z/ then
+        a.to_f <=> b.to_f
+      else
+        a.to_s <=> b.to_s
+      end
+    end
   end
 end
index abf1b6217f31a07f9fd53ea01687be272443e00a..6bd6ebf20cf364c1aa0595165b9e2f0db9aa24e7 100644 (file)
@@ -8,6 +8,14 @@ module Puppet::Parser::Functions
     raise(Puppet::ParseError, "min(): Wrong number of arguments " +
           "need at least one") if args.size == 0
 
-    return args.min
+    # Sometimes we get numbers as numerics and sometimes as strings.
+    # We try to compare them as numbers when possible
+    return args.min do |a,b|
+      if a.to_s =~ /\A^-?\d+(.\d+)?\z/ and b.to_s =~ /\A-?\d+(.\d+)?\z/ then
+        a.to_f <=> b.to_f
+      else
+        a.to_s <=> b.to_s
+      end
+    end
   end
 end
index 604927e49b820c5bebb016961f2429ce0b7ce0b1..ff6f2b361c3a8e6e8d780fff8509e053bbb071dc 100755 (executable)
@@ -20,4 +20,8 @@ describe "the max function" do
   it "should be able to compare numbers" do
     scope.function_max([6,8,4]).should(eq(8))
   end
+
+  it "should be able to compare a number with a stringified number" do
+    scope.function_max([1,"2"]).should(eq("2"))
+  end
 end
index 781422cd55e625538bfaa80ad6229e449ca411f4..71d593ef091584bffbc9ccaf3f5ae963d5731cb3 100755 (executable)
@@ -20,4 +20,8 @@ describe "the min function" do
   it "should be able to compare numbers" do
     scope.function_min([6,8,4]).should(eq(4))
   end
+
+  it "should be able to compare a number with a stringified number" do
+    scope.function_min([1,"2"]).should(eq(1))
+  end
 end