added array sorting and mapping on properties

This commit is contained in:
James MacAulay
2008-10-28 10:36:05 -04:00
parent 3d8efe04a7
commit 36860eab57
2 changed files with 27 additions and 2 deletions
+20 -2
View File
@@ -63,9 +63,27 @@ module Liquid
end end
# Sort elements of the array # Sort elements of the array
def sort(input) # provide optional property with which to sort an array of hashes or drops
[input].flatten.sort def sort(input, property = nil)
ary = [input].flatten
if property.nil?
ary.sort
elsif ary.first.respond_to?('[]') and !ary.first[property].nil?
ary.sort {|a,b| a[property] <=> b[property] }
elsif ary.first.respond_to?(property)
ary.sort {|a,b| a.send(property) <=> b.send(property) }
end
end end
# map/collect on a given property
def map(input, property)
ary = [input].flatten
if ary.first.respond_to?('[]') and !ary.first[property].nil?
ary.map {|e| e[property] }
elsif ary.first.respond_to?(property)
ary.map {|e| e.send(property) }
end
end
# Replace occurrences of a string with another # Replace occurrences of a string with another
def replace(input, string, replacement = '') def replace(input, string, replacement = '')
+7
View File
@@ -67,6 +67,13 @@ class StandardFiltersTest < Test::Unit::TestCase
def test_sort def test_sort
assert_equal [1,2,3,4], @filters.sort([4,3,2,1]) assert_equal [1,2,3,4], @filters.sort([4,3,2,1])
assert_equal [{"a" => 1}, {"a" => 2}, {"a" => 3}, {"a" => 4}], @filters.sort([{"a" => 4}, {"a" => 3}, {"a" => 1}, {"a" => 2}], "a")
end
def test_map
assert_equal [1,2,3,4], @filters.map([{"a" => 1}, {"a" => 2}, {"a" => 3}, {"a" => 4}], 'a')
assert_template_result 'abc', "{{ ary | map:'foo' | map:'bar' }}",
'ary' => [{'foo' => {'bar' => 'a'}}, {'foo' => {'bar' => 'b'}}, {'foo' => {'bar' => 'c'}}]
end end
def test_date def test_date