diff --git a/lib/liquid/standardfilters.rb b/lib/liquid/standardfilters.rb index c87cd7c..8722687 100644 --- a/lib/liquid/standardfilters.rb +++ b/lib/liquid/standardfilters.rb @@ -125,7 +125,15 @@ module Liquid elsif ary.empty? # The next two cases assume a non-empty array. [] elsif ary.first.respond_to?(:[]) && !ary.first[property].nil? - ary.sort { |a, b| a[property] <=> b[property] } + ary.sort do |a, b| + a = a[property] + b = b[property] + if a && b + a <=> b + else + a ? -1 : 1 + end + end end end diff --git a/test/integration/standard_filter_test.rb b/test/integration/standard_filter_test.rb index c852ac6..b330d1d 100644 --- a/test/integration/standard_filter_test.rb +++ b/test/integration/standard_filter_test.rb @@ -178,6 +178,24 @@ 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_when_property_is_sometimes_missing_puts_nils_last + input = [ + { "price" => 4, "handle" => "alpha" }, + { "handle" => "beta" }, + { "price" => 1, "handle" => "gamma" }, + { "handle" => "delta" }, + { "price" => 2, "handle" => "epsilon" } + ] + expectation = [ + { "price" => 1, "handle" => "gamma" }, + { "price" => 2, "handle" => "epsilon" }, + { "price" => 4, "handle" => "alpha" }, + { "handle" => "delta" }, + { "handle" => "beta" } + ] + assert_equal expectation, @filters.sort(input, "price") + end + def test_sort_empty_array assert_equal [], @filters.sort([], "a") end