Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new MapELResolver with type coercion to support accessing enum keys #688

Merged
merged 4 commits into from
Jun 17, 2021

Conversation

liamrharwood
Copy link
Contributor

related to #271

This PR adds the new TypeConvertingMapELResolver in order to allow accessing map entries when their key does not have equality with its string representation.

This is most often seen with enums. For instance, imagine a Java map with key type MyEnum:

public enum MyEnum { FOO, BAR; } 

Outputting the map via {{ map }} could produce the following:

{FOO=value1, BAR=value2}

However, {{ map.FOO }} would not resolve to anything as the string "FOO" does not have equality with MyEnum.FOO.

To fix this, I've used the CollectionMembershipOperator and TruthyTypeConverter to determine if a key is valid and convert it to the correct class. This means that this should work for all types that have this issue, not just enums (for instance, numeric types).

After this PR, {{ map.FOO }} will output value1, which is the expected result.

try {
return super.coerceToEnum(value, type);
} catch (ELException e) {
if (value instanceof String) {
Copy link
Contributor Author

@liamrharwood liamrharwood Jun 17, 2021

Choose a reason for hiding this comment

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

@mattcoley Since jinjava actually uses the toString representation when printing enums, Enum.valueOf in the regular coerceToEnum will not always match. For that reason, I added extra logic here to check the toString values of the enums as well.
You can see an example in the itGetsDictValuesWithEnumKeysUsingToString test case below.

@liamrharwood liamrharwood requested a review from mattcoley June 17, 2021 14:26
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.

3 participants