Consolidate contextualization of inputs via the context

This commit is contained in:
Thierry Joyal
2022-03-07 12:49:28 -05:00
parent 7357dcf185
commit 1bf77d7798
6 changed files with 85 additions and 26 deletions
+17 -8
View File
@@ -187,16 +187,11 @@ module Liquid
# path and find_index() is optimized in MRI to reduce object allocation
index = @scopes.find_index { |s| s.key?(key) }
variable = if index
if index
lookup_and_evaluate(@scopes[index], key, raise_on_not_found: raise_on_not_found)
else
try_variable_find_in_environments(key, raise_on_not_found: raise_on_not_found)
end
variable = variable.to_liquid
variable.context = self if variable.respond_to?(:context=)
variable
end
def lookup_and_evaluate(obj, key, raise_on_not_found: true)
@@ -207,9 +202,9 @@ module Liquid
value = obj[key]
if value.is_a?(Proc) && obj.respond_to?(:[]=)
obj[key] = value.arity == 0 ? value.call : value.call(self)
obj[key] = contextualize(value)
else
value
contextualize(value)
end
end
@@ -228,6 +223,20 @@ module Liquid
@disabled_tags.fetch(tag_name, 0) > 0
end
# Convert input objects into liquid aware representations
# Procs will be resolved
# Assigns the context (self) through context=
def contextualize(object)
if object.is_a?(Proc)
object = object.arity == 0 ? object.call : object.call(self)
end
object = object.to_liquid
object.context = self if object.respond_to?(:context=)
object
end
protected
attr_writer :base_scope_depth, :warnings, :errors, :strainer, :filters, :disabled_tags
+1 -2
View File
@@ -582,8 +582,7 @@ module Liquid
def each
@input.each do |e|
e = e.respond_to?(:to_liquid) ? e.to_liquid : e
e.context = @context if e.respond_to?(:context=)
e = @context.contextualize(e)
yield(e)
end
end
+3 -7
View File
@@ -49,15 +49,14 @@ module Liquid
((object.respond_to?(:key?) && object.key?(key)) ||
(object.respond_to?(:fetch) && key.is_a?(Integer)))
# if its a proc we will replace the entry with the proc
res = context.lookup_and_evaluate(object, key)
object = res.to_liquid
object = context.lookup_and_evaluate(object, key)
# Some special cases. If the part wasn't in square brackets and
# no key with the same name was found we interpret following calls
# as commands and call them on the current object
elsif @command_flags & (1 << i) != 0 && object.respond_to?(key)
object = object.send(key).to_liquid
object = object.send(key)
object = context.contextualize(object)
# 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
@@ -66,9 +65,6 @@ module Liquid
return nil unless context.strict_variables
raise Liquid::UndefinedVariable, "undefined variable #{key}"
end
# If we are dealing with a drop here we have to
object.context = context if object.respond_to?(:context=)
end
object