Fix backward-compatibility issue with the 'sort' filter

This commit is contained in:
Guilherme Carreiro
2025-01-29 16:50:05 +01:00
parent 8dd9279265
commit 0ae38bac69
4 changed files with 125 additions and 3 deletions
+32 -2
View File
@@ -387,7 +387,23 @@ module Liquid
end
elsif ary.all? { |el| el.respond_to?(:[]) }
begin
ary.sort { |a, b| nil_safe_compare(fetch_property(a, property), fetch_property(b, property)) }
ary.sort do |a, b|
a = fetch_property(a, property)
b = fetch_property(b, property)
##
# We handle nested properties gracefully to avoid breaking backward
# compatibility.
#
# However, we raise errors for incompatible types when no nested
# properties are used to maintain strict type checking in simple
# cases.
if has_nested_property?(property)
type_safe_compare(a, b) { |a, b| nil_safe_compare(a, b) }
else
nil_safe_compare(a, b)
end
end
rescue TypeError
raise_property_error(property)
end
@@ -1005,7 +1021,7 @@ module Liquid
# ```
value = drop[property_or_keys]
return value if !value.nil? || !property_or_keys.is_a?(String)
return value if !value.nil? || !has_nested_property?(property_or_keys)
keys = property_or_keys.split('.')
keys.reduce(drop) do |drop, key|
@@ -1013,6 +1029,10 @@ module Liquid
end
end
def has_nested_property?(property)
property.is_a?(String) && property.include?('.')
end
def raise_property_error(property)
raise Liquid::ArgumentError, "cannot select the property '#{property}'"
end
@@ -1036,6 +1056,16 @@ module Liquid
end
end
def type_safe_compare(a, b)
klass_a = a.class
klass_b = b.class
# Converting classes to string to have a deterministic comparison.
return nil_safe_casecmp(klass_a, klass_b) if klass_a != klass_b
yield(a, b)
end
def nil_safe_casecmp(a, b)
if !a.nil? && !b.nil?
a.to_s.casecmp(b.to_s)
+1 -1
View File
@@ -2,5 +2,5 @@
# frozen_string_literal: true
module Liquid
VERSION = "5.7.1"
VERSION = "5.7.2"
end