Skip to content

Conversation

@graygilmore
Copy link
Contributor

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.

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.
@graygilmore graygilmore requested a review from a team October 30, 2025 22:35
Copy link
Contributor

@aswamy aswamy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like a fair change. I didn't know searching a key like that even threw an error :|

@graygilmore
Copy link
Contributor Author

I didn't know searching a key like that even threw an error :|

It only throws an error if you've set strict_variables to true on the context.


def key?(key)
self[key] != nil
find_variable(key, raise_on_not_found: false) != nil
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an opinionated change. Instead of evaluating Expression.parse to look up the tree if we don't find a match we should assume that somebody is passing a simple lookup to key? and check for it directly.

Copy link
Contributor

@karreiro karreiro left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you, @graygilmore! This change looks fair me, specially considering find_variable implementation :)

@graygilmore graygilmore merged commit cbd8a0a into main Nov 4, 2025
23 checks passed
@graygilmore graygilmore deleted the gg-change-key-behavior branch November 4, 2025 21:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Unable to call "key?" and "[]=" on Liquid::Context when strict_variable is true

4 participants