I have two very similar methods in Grails, something like “calculate statistics by os” and “calculate statistics by browser” - it’s effective to prepare some things and run a similar query in the database, and then do something with the results. The only part where the methods differ is the request that they run in the middle of my method -
def summary = c.list { eq('browser', Browser.get(1)) // OR eq('os', OS.get(1)) between('date', dates.start, dates.end) }
It occurred to me that the ideal way to refactor would be to go to the first line of closure as a method parameter. how
doStats (Closure query) { ... def summary = c.list { query between('date', dates.start, dates.end) } }
I tried this, but the "request" is ignored. I tried query (), but then the query sentence is executed where defined, so this does not work either. I suppose I could just pass the whole closure as a parameter, but that seems wrong - the request may also get complicated in the future.
Anyone have any better ideas?
source share