Browse Source

Sort types/categories by number when they start with a number

Thibaut Courouble 9 years ago
parent
commit
70b19c238a
2 changed files with 10 additions and 1 deletions
  1. 7 1
      lib/docs/core/models/type.rb
  2. 3 0
      test/lib/docs/core/models/type_test.rb

+ 7 - 1
lib/docs/core/models/type.rb

@@ -7,8 +7,14 @@ module Docs
       self.count ||= 0
     end
 
+    STARTS_WITH_INTEGER = /\A\d/
+
     def <=>(other)
-      name.to_s.casecmp(other.name.to_s)
+      if name && other && name =~ STARTS_WITH_INTEGER && other.name =~ STARTS_WITH_INTEGER
+        name.to_i <=> other.name.to_i
+      else
+        name.to_s.casecmp(other.name.to_s)
+      end
     end
 
     def slug

+ 3 - 0
test/lib/docs/core/models/type_test.rb

@@ -21,14 +21,17 @@ class DocsTypeTest < MiniTest::Spec
   describe "#<=>" do
     it "returns 1 when the other type's name is less" do
       assert_equal 1, Type.new('b') <=> Type.new('a')
+      assert_equal 1, Type.new('15 a') <=> Type.new('4 b')
     end
 
     it "returns -1 when the other type's name is greater" do
       assert_equal -1, Type.new('a') <=> Type.new('b')
+      assert_equal -1, Type.new('8 a') <=> Type.new('16 b')
     end
 
     it "returns 0 when the other type's name is equal" do
       assert_equal 0, Type.new('a') <=> Type.new('a')
+      assert_equal 0, Type.new('23 a') <=> Type.new('23 b')
     end
 
     it "is case-insensitive" do