From 9973f3399e6531ac381e798039f41f33d65aa508 Mon Sep 17 00:00:00 2001 From: Gray Gilmore Date: Thu, 30 Oct 2025 15:26:27 -0700 Subject: [PATCH] Don't raise if no variable found when using context.key? Previously if you set `strict_variables` to `true` on the context using `key?('key_name')` would raise a `Liquid::UndefinedVariable` error. Raising this error makes sense if you're trying to access the variable directly with something like `context['key_name']` but by using `key?` you're safely checking if it exists first. You should be able to enable `strict_variables` and use `key?` in combination with each other to ensure code safety. --- lib/liquid/context.rb | 2 +- test/integration/context_test.rb | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/lib/liquid/context.rb b/lib/liquid/context.rb index 1ef272d4..433b6d00 100644 --- a/lib/liquid/context.rb +++ b/lib/liquid/context.rb @@ -184,7 +184,7 @@ module Liquid end def key?(key) - self[key] != nil + find_variable(key, raise_on_not_found: false) != nil end def evaluate(object) diff --git a/test/integration/context_test.rb b/test/integration/context_test.rb index f59147e2..d230734f 100644 --- a/test/integration/context_test.rb +++ b/test/integration/context_test.rb @@ -639,6 +639,21 @@ class ContextTest < Minitest::Test end end + def test_key_lookup_will_raise_for_missing_keys_when_strict_variables_is_enabled + context = Context.new + context.strict_variables = true + assert_raises(Liquid::UndefinedVariable) do + context['unknown'] + end + end + + def test_has_key_will_not_raise_for_missing_keys_when_strict_variables_is_enabled + context = Context.new + context.strict_variables = true + refute(context.key?('unknown')) + assert_empty(context.errors) + end + def test_context_always_uses_static_registers registers = { my_register: :my_value,