diff --git a/lib/liquid/tags/for.rb b/lib/liquid/tags/for.rb index b69aa78..f18fb71 100644 --- a/lib/liquid/tags/for.rb +++ b/lib/liquid/tags/for.rb @@ -124,14 +124,23 @@ module Liquid from = if @from == :continue offsets[@name].to_i else - context.evaluate(@from).to_i + from_value = context.evaluate(@from) + if from_value.nil? + 0 + else + Utils.to_integer(from_value) + end end collection = context.evaluate(@collection_name) collection = collection.to_a if collection.is_a?(Range) - limit = context.evaluate(@limit) - to = limit ? limit.to_i + from : nil + limit_value = context.evaluate(@limit) + to = if limit_value.nil? + nil + else + Utils.to_integer(limit_value) + from + end segment = Utils.slice_collection(collection, from, to) segment.reverse! if @reversed diff --git a/test/integration/tags/for_tag_test.rb b/test/integration/tags/for_tag_test.rb index cb7a822..9980e25 100644 --- a/test/integration/tags/for_tag_test.rb +++ b/test/integration/tags/for_tag_test.rb @@ -103,6 +103,34 @@ HERE assert_template_result('3456', '{%for i in array limit: 4 offset: 2 %}{{ i }}{%endfor%}', assigns) end + def test_limiting_with_invalid_limit + assigns = { 'array' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] } + template = <<-MKUP + {% for i in array limit: true offset: 1 %} + {{ i }} + {% endfor %} + MKUP + + exception = assert_raises(Liquid::ArgumentError) do + Template.parse(template).render!(assigns) + end + assert_equal("Liquid error: invalid integer", exception.message) + end + + def test_limiting_with_invalid_offset + assigns = { 'array' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] } + template = <<-MKUP + {% for i in array limit: 1 offset: true %} + {{ i }} + {% endfor %} + MKUP + + exception = assert_raises(Liquid::ArgumentError) do + Template.parse(template).render!(assigns) + end + assert_equal("Liquid error: invalid integer", exception.message) + end + def test_dynamic_variable_limiting assigns = { 'array' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] } assigns['limit'] = 2