Compare commits

...
1 Commits
Author SHA1 Message Date
Sam Doiron cc6cd64065 Special case Hash#last in variable lookup
Ruby's defines Hash#first via Enumerable but not Hash#last.
This is a confusing behaviour, and it bubbles up to Liquid.

Solution: add a special case for command-lookups of Hash#last to return
hash.values.last.
2022-11-01 14:40:36 -03:00
2 changed files with 9 additions and 1 deletions
+5 -1
View File
@@ -61,11 +61,15 @@ module Liquid
# as commands and call them on the current object
elsif lookup_command?(i) && object.respond_to?(key)
object = object.send(key).to_liquid
elsif lookup_command?(i) && object.is_a?(Hash) && key == 'last'
# Ruby defines Hash#first via Enumerable but not Hash#last.
# This is unexpected, so we explicitly handle that case here.
object = object.values.last.to_liquid
else
# No key was present with the desired value and it wasn't one of the directly supported
# keywords either. The only thing we got left is to return nil or
# raise an exception if `strict_variables` option is set to true
else
return nil unless context.strict_variables
raise Liquid::UndefinedVariable, "undefined variable #{key}"
end
+4
View File
@@ -130,4 +130,8 @@ class VariableTest < Minitest::Test
def test_raw_value_variable
assert_template_result('bar', '{{ [key] }}', { 'key' => 'foo', 'foo' => 'bar' })
end
def test_hash_last
assert_template_result('last', '{{ hash.last }}', { 'hash' => { 'first' => 'first', 'last' => 'last' } })
end
end