aitor (owner)

Fork Of

Revisions

gist: 142349 Download_button fork
public
Public Clone URL: git://gist.github.com/142349.git
Embed All Files: show embed
finder_sort.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# Mimic Mac OS X Finder's sort by name.
class Array
  def finder_sort
    sort { |a, b| a.to_finder_sort <=> b.to_finder_sort }
  end
end
 
class String
  def to_finder_sort
    result = self.dup
    order = %w[` ^ _ - , ; ! ? ' " ( ) [ ] { } @ * \\ & # % + < = > | ~ $] + [/[^0-9a-z\s]/i, /\d+/]
    order.reverse.each_with_index do |target, index|
      result.gsub!(target) { |m| m.rjust(100 + index) }
    end
    result.downcase
  end
end
 
require "test/unit"
 
class FinderSortTest < Test::Unit::TestCase
  def test_ignore_case
    assert_equal %w[rob Robo robot], %w[robot Robo rob].finder_sort
  end
  
  def test_sort_numeric
    assert_equal %w[19 21 119], %w[119 19 21].finder_sort
  end
  
  def test_sort_numeric_with_spaces
    assert_equal ["12 19", "12 119"], ["12 119", "12 19"].finder_sort
  end
  
  def test_punctuation
    given = %w[% ! " # $ ' ` { [ > a ( ) * + , ? & @ - 1 ; < = \\ ] ^ _ | } ~] + [" "]
    expected = [" "] + %w[` ^ _ - , ; ! ? ' " ( ) [ ] { } @ * \\ & # % + < = > | ~ $ 1 a]
    assert_equal expected.to_s, given.finder_sort.to_s
  end
  
  def test_unknown_punctuation
    assert_equal %w[` $ : 1 a], %w[: 1 a ` $].finder_sort
  end
end