mirror of
https://github.com/Shopify/liquid.git
synced 2026-09-12 23:40:45 -07:00
added array sorting and mapping on properties
This commit is contained in:
@@ -63,8 +63,26 @@ 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
|
||||||
|
|
||||||
|
# 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
|
end
|
||||||
|
|
||||||
# Replace occurrences of a string with another
|
# Replace occurrences of a string with another
|
||||||
|
|||||||
@@ -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
|
||||||
|
|||||||
Reference in New Issue
Block a user