Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Always stringify sum filter property #1935

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/liquid/standardfilters.rb
Original file line number Diff line number Diff line change
Expand Up @@ -952,11 +952,13 @@ def default(input, default_value = '', options = {})
# @liquid_syntax array | sum
# @liquid_return [number]
def sum(input, property = nil)
property = Liquid::Utils.to_s(property)

ary = InputIterator.new(input, context)
return 0 if ary.empty?

values_for_sum = ary.map do |item|
if property.nil?
if property.empty?
item
elsif item.respond_to?(:[])
item[property]
Expand Down
11 changes: 11 additions & 0 deletions test/integration/standard_filter_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1281,6 +1281,17 @@ def test_sum_with_floats_and_indexable_map_values
assert_template_result("0", "{{ input | sum: 'subtotal' }}", { "input" => input })
end

def test_sum_with_non_string_property
input = [{ "true" => 1 }, { "1.0" => 0.2, "1" => -0.3 }, { "1..5" => 0.4 }]

assert_equal(1, @filters.sum(input, true))
assert_equal(0.2, @filters.sum(input, 1.0))
assert_equal(-0.3, @filters.sum(input, 1))
assert_equal(0.4, @filters.sum(input, (1..5)))
assert_equal(0, @filters.sum(input, nil))
assert_equal(0, @filters.sum(input, ""))
end

private

def with_timezone(tz)
Expand Down
Loading