diff --git a/lib/liquid/standardfilters.rb b/lib/liquid/standardfilters.rb index 8aad420f..254ac72a 100644 --- a/lib/liquid/standardfilters.rb +++ b/lib/liquid/standardfilters.rb @@ -63,9 +63,27 @@ module Liquid end # Sort elements of the array - def sort(input) - [input].flatten.sort + # provide optional property with which to sort an array of hashes or drops + 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 # Replace occurrences of a string with another def replace(input, string, replacement = '') diff --git a/test/standard_filter_test.rb b/test/standard_filter_test.rb index 2765fc45..54b776f3 100644 --- a/test/standard_filter_test.rb +++ b/test/standard_filter_test.rb @@ -67,6 +67,13 @@ class StandardFiltersTest < Test::Unit::TestCase def test_sort 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 def test_date