diff --git a/lib/liquid/context.rb b/lib/liquid/context.rb index 30492578e..f42a2eb57 100644 --- a/lib/liquid/context.rb +++ b/lib/liquid/context.rb @@ -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 diff --git a/test/integration/context_test.rb b/test/integration/context_test.rb index 8fa83ddb5..8a6dff923 100644 --- a/test/integration/context_test.rb +++ b/test/integration/context_test.rb @@ -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 @@ -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