Merge pull request #239 from Shopify/sort_filter_on_enumerables

Sort filter on Enumerables
This commit is contained in:
Florian Weingarten
2013-08-14 13:59:44 -07:00
2 changed files with 28 additions and 13 deletions

View File

@@ -81,7 +81,7 @@ module Liquid
# Sort elements of the array
# provide optional property with which to sort an array of hashes or drops
def sort(input, property = nil)
ary = [input].flatten
ary = flatten_if_necessary(input)
if property.nil?
ary.sort
elsif ary.first.respond_to?('[]') and !ary.first[property].nil?
@@ -99,17 +99,8 @@ module Liquid
# map/collect on a given property
def map(input, property)
ary = if input.is_a?(Array)
input.flatten
elsif input.kind_of?(Enumerable)
input
else
[input].flatten
end
ary.map do |e|
flatten_if_necessary(input).map do |e|
e = e.call if e.is_a?(Proc)
e = e.to_liquid if e.respond_to?(:to_liquid)
if property == "to_liquid"
e
@@ -256,6 +247,17 @@ module Liquid
private
def flatten_if_necessary(input)
ary = if input.is_a?(Array)
input.flatten
elsif input.kind_of?(Enumerable)
input
else
[input].flatten
end
ary.map{ |e| e.respond_to?(:to_liquid) ? e.to_liquid : e }
end
def to_number(obj)
case obj
when Float

View File

@@ -15,6 +15,10 @@ class TestThing
"woot: #{@foo}"
end
def [](whatever)
to_s
end
def to_liquid
@foo += 1
self
@@ -31,7 +35,7 @@ class TestEnumerable < Liquid::Drop
include Enumerable
def each(&block)
[ { "foo" => 1 }, { "foo" => 2 }, { "foo" => 3 } ].each(&block)
[ { "foo" => 1, "bar" => 2 }, { "foo" => 2, "bar" => 1 }, { "foo" => 3, "bar" => 3 } ].each(&block)
end
end
@@ -133,7 +137,12 @@ class StandardFiltersTest < Test::Unit::TestCase
def test_map_calls_to_liquid
t = TestThing.new
assert_equal "woot: 1", Liquid::Template.parse('{{ foo }}').render("foo" => t)
assert_equal "woot: 1", Liquid::Template.parse('{{ foo | map: "whatever" }}').render("foo" => [t])
end
def test_sort_calls_to_liquid
t = TestThing.new
assert_equal "woot: 1", Liquid::Template.parse('{{ foo | sort: "whatever" }}').render("foo" => [t])
end
def test_map_over_proc
@@ -147,6 +156,10 @@ class StandardFiltersTest < Test::Unit::TestCase
assert_equal "123", Liquid::Template.parse('{{ foo | map: "foo" }}').render!("foo" => TestEnumerable.new)
end
def test_sort_works_on_enumerables
assert_equal "213", Liquid::Template.parse('{{ foo | sort: "bar" | map: "foo" }}').render!("foo" => TestEnumerable.new)
end
def test_date
assert_equal 'May', @filters.date(Time.parse("2006-05-05 10:00:00"), "%B")
assert_equal 'June', @filters.date(Time.parse("2006-06-05 10:00:00"), "%B")