mirror of
https://github.com/Shopify/liquid.git
synced 2026-09-15 08:50:45 -07:00
Fix "sort" filter on empty array to return empty array
When sorting an empty array with the "sort" filter, it returns nil instead of []. This confuses subsequent filters in the chain that expect an array. For example, when followed by the "map" filter, it produces an array containing one nil element: [nil]. I could special-case the nil return value, but that would be more cumbersome than making sure "sort" always returns an array. Add a case to the "sort" method to return [] if the array is empty, before performing any checks on ary.first that assume a non-empty array. There is still a danger of returning nil if the first item in the array is nil and it is non-empty, but I'm not sure how better to handle that case. Apply a similar fix to sort_natural, uniq, and compact filters.
This commit is contained in:
@@ -158,6 +158,14 @@ class StandardFiltersTest < Minitest::Test
|
||||
assert_equal [{ "a" => 1 }, { "a" => 2 }, { "a" => 3 }, { "a" => 4 }], @filters.sort([{ "a" => 4 }, { "a" => 3 }, { "a" => 1 }, { "a" => 2 }], "a")
|
||||
end
|
||||
|
||||
def test_sort_empty_array
|
||||
assert_equal [], @filters.sort([], "a")
|
||||
end
|
||||
|
||||
def test_sort_natural_empty_array
|
||||
assert_equal [], @filters.sort_natural([], "a")
|
||||
end
|
||||
|
||||
def test_legacy_sort_hash
|
||||
assert_equal [{ a: 1, b: 2 }], @filters.sort({ a: 1, b: 2 })
|
||||
end
|
||||
@@ -177,6 +185,14 @@ class StandardFiltersTest < Minitest::Test
|
||||
assert_equal [testdrop], @filters.uniq([testdrop, TestDrop.new], 'test')
|
||||
end
|
||||
|
||||
def test_uniq_empty_array
|
||||
assert_equal [], @filters.uniq([], "a")
|
||||
end
|
||||
|
||||
def test_compact_empty_array
|
||||
assert_equal [], @filters.compact([], "a")
|
||||
end
|
||||
|
||||
def test_reverse
|
||||
assert_equal [4, 3, 2, 1], @filters.reverse([1, 2, 3, 4])
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user