Joseph
Joseph

Reputation: 1461

Grails filter controller in package

The project I'm working on currently uses filters for various pieces. The filters themselves work great. The problem I'm running into is that when specifying which controllers the filter should be executed on, I end up with a very large list. Functionally this works fine but it ends up being ugly and somewhat unwieldy.

def filters =
{
        filterSomething(controller:'one|two|three|...|xyz', action:'*')
        {
            //before filter here, not important.
        }
    }

Is there a way to specify that the filter is only applicable for controllers in a given package or list of packages?

If there is nothing out of the box, I was thinking about tying something into the bootstrap and setting my lists that way.

Upvotes: 3

Views: 606

Answers (1)

Alidad
Alidad

Reputation: 5538

You could have a filter on all controllers and then check their package and then decide what you want to do. There are better and more elegant way coding this, but just to give you an idea.

 class MyFilters {
def grailsApplication


def filters = {
    all(controller:'*', action:'*') {
        before = {
            if (checkController(['com.package.name'],controllerName)){
            }
        }
    }
}


def searchInList(list,packageName){
    for (keyword in list) {
        if (packageName.contains(keyword)) return true
    }
    return false
}

Boolean checkController(def includePackageList,cname) {
    def dlist = grailsApplication.getArtefacts("Controller")
    def filteredList= dlist.findAll{ searchInList(includePackageList,it.getPackageName()) }
    return filteredList.contains(cname)
}
}

Upvotes: 2

Related Questions