Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>One way to create a helper method is to create it outside of the <code>filters</code> closure, and pass the instance in. It doesn't work to pass in <code>this</code> because that's not the closure but the <code>UserFilters</code> instance. Instead pass in the closure's <code>delegate</code> which is where the <code>render</code> and <code>redirect</code> methods are added, where the attributes like <code>params</code> and <code>controllerName</code> are:</p> <pre><code>class UserFilters { def filters = { // ... other filters ... adminAllCheck(controller: 'administration', action: '*') { before = { doAdminCheck(delegate) } } userListCheck(controller: 'user', action: 'list') { before = { doAdminCheck(delegate) } } } private boolean doAdminCheck(filters) { if (!filters.session.isAdmin) { if (accountService.isAdmin()) { filters.session.isAdmin = true } else { filters.flash.message = 'Non admin' filters.redirect(controller: 'home', action: 'index') return false } } true } } </code></pre> <p>You can also use the <code>|</code> character in the <code>controller</code> and <code>action</code> arguments to do common work across controllers. It wouldn't work here directly since you use <code>*</code> for the admin controller and only apply to the <code>list</code> action in the user controller, but you can do an explicit controller/action name check for that:</p> <pre><code>adminCheck(controller: 'administration|user', action: '*') { if (controllerName == 'user' &amp;&amp; actionName != 'list') { return true } // common logic here } </code></pre> <p>You could also move the logic to a service and dependency-inject that back in. It's usually not a good idea to mix tiers like that and have HTTP logic in a service, but that would keep the logic in one place. You could use the same trick with the delegate, or just pass in the session/request/response/etc. as needed.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload