zk_html/diary/2010-07-25-20:18:21.html

124 lines
7.0 KiB
HTML
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!doctype html>
<html>
<head>
<title>Zk | 2010-07-25 20:18:21</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Gentium+Plus&family=Lato&family=Ubuntu+Monodisplay=swap" />
<link rel="stylesheet" type="text/css" href="/style.css?2024-05-04" />
<meta name="viewport" content="width=device-width" />
<meta charset="utf-8" />
</head>
<body>
<main>
<header>
<h1>Zk | 2010-07-25 20:18:21</h1>
</header>
<article class="content">
<p><span class="tag">blog</span> <span class="tag">fossil</span> <span class="tag">diary</span></p>
<p>Working on a rather large project in grails, I&rsquo;ve come to realize two things: there is some absolutely amazing software frameworks out there, and some people who write documentation appear to be 3-year-old kids who speak English as a second language.  The embarrassing part about that is that, since the project is open-source, I could contribute to the documentation very easily, fixing problems that I see and adding where I see fit.  However, the problem is so large and daunting (and the project I&rsquo;m working on way more interesting), so instead, I wind up just living with it and searching El Goog over and over again for the same things.</p>
<p>I&rsquo;m going to try to change this as best I can, and I&rsquo;m going to start by collecting a few nifty tips and tricks I&rsquo;ve pulled out of thin air here, and hopefully pull them all together into one place soon enough.</p>
<!--more-->
<h2>Permissions</h2>
<p>The current project is using the grails Acegi plugin to manage users and security.  The plugin was recently deprecated, but it appears to have been done so before the replacement was completed, so I&rsquo;m using it for the time being.  The idea of roles is pretty standard, but I wanted some finer-grained control over permissions to specific views, especially pertaining to objects that have lists of users associated with them.  After fiddling around with specifics in the controllers, I abstracted it into a service that I can use everywhere:</p>
<pre lang="enc__groovy">grails-app/services/package/PermissionsService.groovy
class PermissionsService {
static transactional = true
def authenticateService
def groups = [
userCanRead: { group -&gt;
if (group.exclusive) {
if (authenticateService.principal().domainClass in group.members
|| authenticateService.principal().domainClass.id == group.admin.id
|| authenticateService.ifAnyGranted("ROLE_ADMIN")) {
return true
}
} else {
return true
}
},
// ...
]
}</pre>
<p>As you can see, the service contains a list of permissions - closures that do a few tests and return true or false - organized into lists in order to separate them into logical groups (in this case, the groups list pertains to the groups domain class, controller, and views). Each closure expects one argument - the object to test the permissions of. This comes in handy for the corresponding TagLib:</p>
<pre lang="enc__groovy">grails-app/taglib/package/PermissionsTagLib.groovy
class PermissionsTagLib {
static namespace = "my"
def permissionsService
def withPermission = { attrs, body -&gt;
if (permissionsService."${attrs['class']}"."${attrs['permission']}"(attrs['arg'])) {
out &lt;&lt; body()
}
}
}</pre>
<p>The tag-lib allows us to write logical tags that will only output data if the user passes the test, i.e:</p>
<pre lang="enc__html">In a view...
&lt;my:withPermission class="groups" permission="userCanPost" arg="${group}"&gt;
Post new topic
&lt;/my:withPermission&gt;</pre>
<p>After all, it is nice to ask permission&hellip;</p>
<h2>Comma-separated tags</h2>
<p>Just a little snippet, but I&rsquo;m using comma-separated tags for tagging some domains, and I wasn&rsquo;t really keen on some of the solutions I saw out there, so I scribbled out a &lsquo;one-liner&rsquo; for tagging stuff:</p>
<pre lang="enc__groovy">grails-app/services/package/TagService.groovy
tags.split(/(?!(?&lt;=\\)),/) .collect { it.trim().replaceAll(/\\,/, ",") } .each { if (it.size() &gt; 0) {
obj.tags.each { otag -&gt;
if (it.tag == it) {
// skip if we already have it tagged
return
}
}
def t
if (Tag.countByTag(it) &gt; 0) {
t = Tag.findByTag(it)
} else {
t = new Tag(tag: it).save()
}
obj.addToTags(t).save(flush: true)
}
}
// ...</pre>
<p>This way, we can even have commas in tags, via: &ldquo;foo, bar\, baz&rdquo; (tags: [&ldquo;foo&rdquo;, &ldquo;bar, baz&rdquo;])</p>
<h2>Tips</h2>
<ul>
<li>Codecs are static (I forgot.  You ever forget?  Happened to me).  I wasted a crapload of time on a problem in there before I switched to a tag-lib, <em>et voila</em>, everything's fixed</li>
<li>Constraints are also static, so if you want to constrain yourself to a list of strings, but want to be able to change the strings, store an integer and use that as an index to an array of strings stored in Config.  For bonus points, store a portion of a property key so you can internationalize, and use the portion of the key as the default value.</li>
<li>If you want to always ensure that a condition is met when querying, stick the query in a service and pass the service a closure of your criteria:</li>
</ul>
<pre lang="groovy">In your service...
// ...
def ListWithRating (Closure c) {
Obj.withCriteria {
and {
c.delegate = delegate
c()
le('rating', maxRating)
}
}
}</pre>
<pre lang="groovy">In your controller...
// ...
def criteria = {
eq('type', params.type)
}
listService.listWithRating(criteria)</pre>
<ul>
<li>If you want to associate something with anything (i.e.: a comment with any other domain), store the domain's class name (with <code>obj.class.toString().split(/\\./)[-1]</code>) with the comment, along with the object's id, then get it back the same way.  You can check that the object exists with dynamic class-loading:</li>
</ul>
<pre lang="groovy">def object = Class.forName("package.${objectType}", true, Thread.currentThread().getContextClassLoader())
.get(objectId)</pre>
<p>That&rsquo;s about all for now, but I&rsquo;m sure as the project progresses, I&rsquo;ll come up with more and I&rsquo;ll either post about them or collect them somewhere.</p>
</article>
<footer>
<p>Page generated on On Grails</p>
</footer>
</main>
<script type="text/javascript">
document.querySelectorAll('.tag').forEach(tag => {
let text = tag.innerText;
tag.innerText = '';
tag.innerHTML = `<a href="/tags.html#${text}">${text}</a>`;
});
</script>
</body>
</html>