public
Rubygem
Description: Liquid markup language. Save, customer facing template language for flexible web apps.
Homepage: http://www.liquidmarkup.org
Clone URL: git://github.com/tobi/liquid.git
Click here to lend your support to: liquid and make a donation at www.pledgie.com !
added array sorting and mapping on properties
jamesmacaulay (author)
Tue Oct 28 07:36:05 -0700 2008
commit  36860eab570f448a7bc11875665f0642ed0e462d
tree    2dadd028ab800c8008c9cc8d11526d8d65c9c502
parent  3d8efe04a743d6fb4c3bc8d198f630f9896b853e
...
63
64
65
66
67
 
 
 
 
 
 
 
 
 
 
68
 
 
 
 
 
 
 
 
 
 
69
70
71
...
63
64
65
 
 
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
0
@@ -63,9 +63,27 @@ module Liquid
0
     end
0
 
0
     # Sort elements of the array
0
-    def sort(input)
0
-      [input].flatten.sort
0
+    # provide optional property with which to sort an array of hashes or drops
0
+    def sort(input, property = nil)
0
+      ary = [input].flatten
0
+      if property.nil?
0
+        ary.sort
0
+      elsif ary.first.respond_to?('[]') and !ary.first[property].nil?
0
+        ary.sort {|a,b| a[property] <=> b[property] }
0
+      elsif ary.first.respond_to?(property)
0
+        ary.sort {|a,b| a.send(property) <=> b.send(property) }
0
+      end
0
     end               
0
+    
0
+    # map/collect on a given property
0
+    def map(input, property)
0
+      ary = [input].flatten
0
+      if ary.first.respond_to?('[]') and !ary.first[property].nil?
0
+        ary.map {|e| e[property] }
0
+      elsif ary.first.respond_to?(property)
0
+        ary.map {|e| e.send(property) }
0
+      end
0
+    end
0
             
0
     # Replace occurrences of a string with another
0
     def replace(input, string, replacement = '')
...
67
68
69
 
 
 
 
 
 
 
70
71
72
...
67
68
69
70
71
72
73
74
75
76
77
78
79
0
@@ -67,6 +67,13 @@ class StandardFiltersTest < Test::Unit::TestCase
0
   
0
   def test_sort
0
     assert_equal [1,2,3,4], @filters.sort([4,3,2,1])    
0
+    assert_equal [{"a" => 1}, {"a" => 2}, {"a" => 3}, {"a" => 4}], @filters.sort([{"a" => 4}, {"a" => 3}, {"a" => 1}, {"a" => 2}], "a")
0
+  end
0
+  
0
+  def test_map
0
+    assert_equal [1,2,3,4], @filters.map([{"a" => 1}, {"a" => 2}, {"a" => 3}, {"a" => 4}], 'a')
0
+    assert_template_result 'abc', "{{ ary | map:'foo' | map:'bar' }}",
0
+      'ary' => [{'foo' => {'bar' => 'a'}}, {'foo' => {'bar' => 'b'}}, {'foo' => {'bar' => 'c'}}]
0
   end
0
   
0
   def test_date

Comments