Search code examples
grailsgroovycontrollergrails-ormgsp

Grails grailApplication.controllerClasses sort controller by package


I have the following code that grabs all controllers, sorts it, and outputs in li tags:

<g:each var="c" in="${grailsApplication.controllerClasses.sort { it.fullName } }">
        <li<%= c.logicalPropertyName == controllerName ? ' class="active"' : '' %>>
                <g:link controller="${c.logicalPropertyName}">${c.naturalName}</g:link>
        </li>
</g:each>

I have a need to filter out controllers by package i.e. grab controller from a certain package.

For example:

com.app.module.mars.controller.HelloController
com.app.module.venus.controller.PrintController

As you can see I'm packaging controllers by modules, so mars will have its own set of controllers and venus will have its own. Then in the UI I want to use the above code (with some filter) which will show modules as main-menus and their controllers as dropdowns.

How can I apply such a filter? Or if you could guide me in the right direction would be great. Thanks.


Solution

  • You can use GrailsClassUtils.isClassBelowPackage() which takes a class and a list of packages as the arguments. So this should do the trick:

    GrailsClassUtils.isClassBelowPackage(c.class, ['com.app.module.mars'])
    

    Edit: grailsApplication.controllerClasses probably gives you a list of GrailsClass objects, so you'd want to use c.clazz instead of c.class like

    grailsApplication.controllerClasses.each { c ->
        GrailsClassUtils.isClassBelowPackage(c.clazz, ['com.app.module.mars'])
    }