mirror of
https://github.com/Shopify/liquid.git
synced 2026-10-03 00:55:11 -07:00
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.
This commit is contained in:
@@ -61,11 +61,15 @@ module Liquid
|
|||||||
# as commands and call them on the current object
|
# as commands and call them on the current object
|
||||||
elsif lookup_command?(i) && object.respond_to?(key)
|
elsif lookup_command?(i) && object.respond_to?(key)
|
||||||
object = object.send(key).to_liquid
|
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
|
# 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
|
# keywords either. The only thing we got left is to return nil or
|
||||||
# raise an exception if `strict_variables` option is set to true
|
# raise an exception if `strict_variables` option is set to true
|
||||||
else
|
|
||||||
return nil unless context.strict_variables
|
return nil unless context.strict_variables
|
||||||
raise Liquid::UndefinedVariable, "undefined variable #{key}"
|
raise Liquid::UndefinedVariable, "undefined variable #{key}"
|
||||||
end
|
end
|
||||||
|
|||||||
@@ -130,4 +130,8 @@ class VariableTest < Minitest::Test
|
|||||||
def test_raw_value_variable
|
def test_raw_value_variable
|
||||||
assert_template_result('bar', '{{ [key] }}', { 'key' => 'foo', 'foo' => 'bar' })
|
assert_template_result('bar', '{{ [key] }}', { 'key' => 'foo', 'foo' => 'bar' })
|
||||||
end
|
end
|
||||||
|
|
||||||
|
def test_hash_last
|
||||||
|
assert_template_result('last', '{{ hash.last }}', { 'hash' => { 'first' => 'first', 'last' => 'last' } })
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
|||||||
Reference in New Issue
Block a user