1

I'm working on some dynamic filtering, and have this:

class Filterable {
    def statusId
    def secondaryFilterable
}
...
def filter = new Filter(validIds: [1], fieldName: 'statusId')
...
class Filter {

    def validIds = [] as Set
    def fieldName
    private boolean containsFieldValue(input) {
        def fieldValue = input."${fieldName}"
        return fieldValue in validIds
    }
}

Which works just fine for one property. However, now I need to filter by the secondary filterable - something like

def filter = new Filter(validIds: [1], fieldName: 'secondaryFilterable.statusId')

Which throws a groovy.lang.MissingPropertyException. Any advice?

Marcelo
  • 4,580
  • 7
  • 29
  • 46

1 Answers1

2

Quoted properties assume a dot is part of the property name.

A simple solution would be:

...
def fieldValue = fieldName.split(/\./).inject(input){ parent, property -> parent?."$property" }
...

This will recursively look up the field value using dot notation for child properties.

I put up a working example here on the Groovy web console.

OverZealous
  • 39,252
  • 15
  • 98
  • 100
  • Note: this example doesn't check for validity of the property — if the property doesn't exist, it may throw an error. (Try `'foo.bar.badValue'` in the example link.) If necessary, this can be prevented by adding a check using [`hasProperty`](http://groovy.codehaus.org/Evaluating+the+MetaClass+runtime). – OverZealous Jul 13 '12 at 10:22