Skip to content
Open
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
5 changes: 3 additions & 2 deletions lib/liquid/context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -221,8 +221,9 @@ def find_variable(key, raise_on_not_found: true)
# but only after the normal environment lookup doesn't find a value.
return @self_drop ||= SelfDrop.new(self) if fallback_to_self_drop && variable.nil?

# update variable's context before invoking #to_liquid
variable.context = self if variable.respond_to?(:context=)
# Only Liquid::Drop owns this context contract; application objects may
# define an unrelated context= method.
variable.context = self if variable.is_a?(Liquid::Drop) && variable.respond_to?(:context=)

liquid_variable = variable.to_liquid

Expand Down
16 changes: 16 additions & 0 deletions test/integration/context_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,16 @@ def initialize(category)
end
end

class ReadonlyContextModel
def context=(_context)
raise "context is a read-only model attribute"
end

def to_liquid
{ "name" => "record" }
end
end

class CounterDrop < Liquid::Drop
def count
@count ||= 0
Expand Down Expand Up @@ -479,6 +489,12 @@ def test_to_liquid_and_context_at_first_level
assert_equal(@context, @context['category'].context)
end

def test_does_not_assign_context_to_non_drop_variables
model = ReadonlyContextModel.new

assert_equal("record", Template.parse("{{ item.name }}").render("item" => model))
end

def test_interrupt_avoids_object_allocations
@context.interrupt? # ruby 3.0.0 allocates on the first call
assert_no_object_allocations do
Expand Down
Loading