Tuesday, October 20, 2009

How to get actions of a controller

I'm doing something about security in my project using grails jsecurity plugin. To make this function user-friendly, I want to implement an ui that admin can assign a slected controller or its actions to an user or a role. It's not a big deal to list all controllers within a grails app: you can use "grailsApplication.controllerClasses". So, the next step is how to get actions of a controller.
Google is a good teacher when you meet trouble. But I can google nothing. It seems that there is not any thread about my question. So, I checked grails api and found two things:
1. GrailsControllerClass does not provide a method to list all actions.
2. But GrailsControllerClass has a method to list all its possible URIs: getURIs().
Since an URI is a combination of controller and action in grails, finally, I solved my problem using that method. Here is my solution:

def actions= []
grailsApplication.getArtefact(ControllerArtefactHandler.TYPE, your controller name).URIs.each{
def parts= it.split('/')
if(parts.size()>2){
actions << parts[2]
}
}
return (actions as Set)

By the way, Grails JSecurity Plugin is awesome! It reallys makes my life easier!

No comments: