<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ted Naleid &#187; metaprogramming</title>
	<atom:link href="http://naleid.com/blog/category/metaprogramming/feed/" rel="self" type="application/rss+xml" />
	<link>http://naleid.com/blog</link>
	<description>Groovy, Grails and OS X tips and tricks</description>
	<lastBuildDate>Wed, 16 Jun 2010 17:38:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Groovy Each Iterator with Peek-ahead at Next Collection Value</title>
		<link>http://naleid.com/blog/2010/06/15/groovy-each-iterator-with-peek-ahead-at-next-collection-value/</link>
		<comments>http://naleid.com/blog/2010/06/15/groovy-each-iterator-with-peek-ahead-at-next-collection-value/#comments</comments>
		<pubDate>Wed, 16 Jun 2010 04:55:10 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[shortcut]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=191</guid>
		<description><![CDATA[Groovy closures combined with iterators make it simple to create our own enhanced iterators that let us process a collection how we want to.
I write my own custom iterators all the time and name them something descriptive.  This makes the code much more readable. Rather than trying to decipher what a for loop is [...]]]></description>
			<content:encoded><![CDATA[<p>Groovy closures combined with iterators make it simple to create our own enhanced iterators that let us process a collection how we want to.</p>
<p>I write my own custom iterators all the time and name them something descriptive.  This makes the code much more readable. Rather than trying to decipher what a for loop is trying to do, we wrap up all of that iteration logic into a meaningful name and we cleanly separate that iteration from the processing that we&#8217;re doing with each element.</p>
<p>This kind of design is a core concept in Uncle Bob&#8217;s <a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882" onclick="pageTracker._trackPageview('/outgoing/www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882?referer=');">Clean Code</a>, one of my favorite programming books in the last few years.</p>
<p>This example iterates over a collection and calls the passed in closure until we hit a value greater than 5.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> eachUntilGreaterThanFive <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> collection, closure <span style="color: #669966;">-&gt;</span>
    <span style="color: #996600;">for</span> <span style="color: #669966;">&#40;</span> value <span style="color: #996600;">in</span> collection <span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span> value  <span style="color: #669966;">&gt;</span> <span style="color: #cc66cc;">5</span> <span style="color: #669966;">&#41;</span> <span style="color: #000000; font-weight: bold;">break</span>
        closure<span style="color: #669966;">&#40;</span>value<span style="color: #669966;">&#41;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> a <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">5</span>, <span style="color: #cc66cc;">6</span>, <span style="color: #cc66cc;">7</span><span style="color: #669966;">&#93;</span>
&nbsp;
eachUntilGreaterThanFive<span style="color: #669966;">&#40;</span>a<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
    <span style="color: #663366;">println</span> it
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>prints:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #cc66cc;">1</span>
<span style="color: #cc66cc;">2</span>
<span style="color: #cc66cc;">3</span>
<span style="color: #cc66cc;">4</span>
<span style="color: #cc66cc;">5</span></pre></div></div>

<p>This code makes it obvious what the iterator is doing (looping till we hit a condition) as well as what will happen with each element iterated over (print it out).</p>
<p>For a real life example, I had a need to iterate over a list of values and where I needed both the current object as well as a peek at the next object in the list.</p>
<p>Doing this is Java is a bit of a pain, but groovy makes it easy to write and (hopefully) to read, we can also add it directly onto the Collection metaClass so that it&#8217;s available for all of our Collection instances:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #aaaadd; font-weight: bold;">Collection</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">eachWithPeek</span> <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> closure <span style="color: #669966;">-&gt;</span>
    <span style="color: #000000; font-weight: bold;">def</span> last <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">null</span>
    delegate<span style="color: #669966;">?</span>.<span style="color: #663399;">each</span> <span style="color: #669966;">&#123;</span> current <span style="color: #669966;">-&gt;</span>
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>last<span style="color: #669966;">&#41;</span> closure<span style="color: #669966;">&#40;</span>last, current<span style="color: #669966;">&#41;</span>
        last <span style="color: #669966;">=</span> current
    <span style="color: #669966;">&#125;</span>
    <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>last<span style="color: #669966;">&#41;</span> closure<span style="color: #669966;">&#40;</span>last, <span style="color: #000000; font-weight: bold;">null</span><span style="color: #669966;">&#41;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>These test cases show that as we iterate through the collection, we can see the current item and peek at the next one (if any).  If the collection is empty, we don&#8217;t execute the closure it, and if we&#8217;re at the end of the list there isn&#8217;t anything to peek at:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&#91;</span><span style="color: #669966;">&#93;</span>.<span style="color: #006600;">eachWithPeek</span> <span style="color: #669966;">&#123;</span> current, peek <span style="color: #669966;">-&gt;</span>
    <span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #000000; font-weight: bold;">false</span> <span style="color: #808080; font-style: italic;">// shouldn't get here, nothing to iterate through</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">1</span><span style="color: #669966;">&#93;</span>.<span style="color: #006600;">eachWithPeek</span> <span style="color: #669966;">&#123;</span> current, peek <span style="color: #669966;">-&gt;</span>
    <span style="color: #000000; font-weight: bold;">assert</span> current <span style="color: #669966;">==</span> <span style="color: #cc66cc;">1</span>
    <span style="color: #000000; font-weight: bold;">assert</span> peek <span style="color: #669966;">==</span> <span style="color: #000000; font-weight: bold;">null</span>  <span style="color: #808080; font-style: italic;">// only 1 element, nothing to peek at</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> results <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span><span style="color: #669966;">&#93;</span>
<span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">5</span><span style="color: #669966;">&#93;</span>.<span style="color: #006600;">eachWithPeek</span> <span style="color: #669966;">&#123;</span> current, peek <span style="color: #669966;">-&gt;</span>
    results <span style="color: #669966;">&lt;&lt;</span> <span style="color: #669966;">&#91;</span>current, peek<span style="color: #669966;">&#93;</span>
<span style="color: #669966;">&#125;</span>
<span style="color: #000000; font-weight: bold;">assert</span> results <span style="color: #669966;">==</span> <span style="color: #669966;">&#91;</span><span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">1</span>, <span style="color: #cc66cc;">2</span><span style="color: #669966;">&#93;</span>, <span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">2</span>, <span style="color: #cc66cc;">3</span><span style="color: #669966;">&#93;</span>, <span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">3</span>, <span style="color: #cc66cc;">4</span><span style="color: #669966;">&#93;</span>, <span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">4</span>, <span style="color: #cc66cc;">5</span><span style="color: #669966;">&#93;</span>, <span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">5</span>, <span style="color: #000000; font-weight: bold;">null</span><span style="color: #669966;">&#93;</span><span style="color: #669966;">&#93;</span></pre></div></div>

]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2010/06/15/groovy-each-iterator-with-peek-ahead-at-next-collection-value/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Grails build-test-data plugin version 1.0 released</title>
		<link>http://naleid.com/blog/2010/03/17/grails-build-test-data-plugin-version-1-0-released/</link>
		<comments>http://naleid.com/blog/2010/03/17/grails-build-test-data-plugin-version-1-0-released/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 04:48:53 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=171</guid>
		<description><![CDATA[I&#8217;ve finally released version 1.0 of the grails build-test-data plugin.
If you&#8217;re not familiar with build-test-data, the quick summary is that it puts a build() method on all grails domain objects.  Calling that method will automatically construct and save an instance of that domain object that conforms to all of the domain&#8217;s constraints.  It [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve finally released version 1.0 of the <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/Home" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/Home?referer=');">grails build-test-data plugin</a>.</p>
<p>If you&#8217;re not familiar with build-test-data, the quick summary is that it puts a <code>build()</code> method on all grails domain objects.  Calling that method will automatically construct and save an instance of that domain object that conforms to all of the domain&#8217;s constraints.  It also allows you to override the values that you want to explicitly set.  It makes your tests much cleaner and less fragile as you only need to specify the values that actually matter to a particular test method instead of building a huge graph of objects just to satisfy constraints.</p>
<p>The plugin has been quite stable for the past 6 months or so, and has survived upgrades from grails 1.0.X through grails 1.2.1 with minimal changes.  Because of this, I&#8217;ve decided to move the version from 0.2.3 to 1.0 to indicate that the plugin is stable and ready to be used.  I&#8217;ve also added the <a href="http://bitbucket.org/tednaleid/grails-test-data/src/tip/build-test-data/LICENSE" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/src/tip/build-test-data/LICENSE?referer=');">LICENSE</a> file releasing the plugin under the Apache 2.0 open source license (the same license as grails).  It was always open source, but I had neglected to add the official license file in the past.</p>
<p>If you&#8217;re not familiar with the build-test-data plugin, the <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/Home" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/Home?referer=');">documentation on the wiki</a> is thorough, I&#8217;ve also given <a href="http://naleid.com/blog/2009/07/14/grails-build-test-data-presentation/">a presentation on build-test-data</a> that explains why it&#8217;s better than other existing data generation technologies. </p>
<p>The biggest changes for this release compared to the last are a number of bugfixes around making sure that both sides of a one-to-many relationship get populated correctly and that there isn&#8217;t a need to <code>refresh()</code> from the database.</p>
<p>Previously, if you had an Author that <code>hasMany</code> Books, and each Book <code>belongsTo</code> an Author, you&#8217;d need to <code>refresh</code> the Author if you tried to build a new book with an existing author:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">Author eap <span style="color: #669966;">=</span> Author.<span style="color: #006600;">findByName</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;Edgar Allan Poe&quot;</span><span style="color: #669966;">&#41;</span>
<span style="color: #aaaadd; font-weight: bold;">Book</span> b <span style="color: #669966;">=</span> <span style="color: #aaaadd; font-weight: bold;">Book</span>.<span style="color: #006600;">build</span><span style="color: #669966;">&#40;</span>author: eap, title: <span style="color: #aa0000;">&quot;The Tell-Tale Heart&quot;</span><span style="color: #669966;">&#41;</span>
&nbsp;
assertEquals eap.<span style="color: #006600;">name</span>, b.<span style="color: #006600;">author</span>.<span style="color: #006600;">name</span>  <span style="color: #808080; font-style: italic;">// works, linked in OK previously</span>
assertEquals <span style="color: #cc66cc;">1</span>, eap.<span style="color: #006600;">books</span>.<span style="color: #663399;">size</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #808080; font-style: italic;">// FAILED previously WORKS now, previously the book wasn't added properly to the author side of things</span></pre></div></div>

<p>The previous workaround was to call <code>eap.refresh()</code> to reload the author from the database, or to have the user manually <code>addToBooks(b)</code>.  Both solutions were ugly and kludgy and this issue has now been fixed.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2010/03/17/grails-build-test-data-plugin-version-1-0-released/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Interrogating Arbitrary Groovy Closures for Values</title>
		<link>http://naleid.com/blog/2010/01/24/interrogating-arbitrary-groovy-closures-for-values/</link>
		<comments>http://naleid.com/blog/2010/01/24/interrogating-arbitrary-groovy-closures-for-values/#comments</comments>
		<pubDate>Mon, 25 Jan 2010 01:24:25 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=136</guid>
		<description><![CDATA[Inspired by this question on stackoverflow, I decided to create a utility class that allowed me to determine generically what calls a closure makes (without actually letting it make any calls).  This lets me see what it&#8217;s trying to do before letting it actually do it.

It works by overriding the delegate of the closure [...]]]></description>
			<content:encoded><![CDATA[<p>Inspired by <a href="http://stackoverflow.com/questions/2128115/access-values-of-static-closure-in-groovy" onclick="pageTracker._trackPageview('/outgoing/stackoverflow.com/questions/2128115/access-values-of-static-closure-in-groovy?referer=');">this question on stackoverflow</a>, I decided to create a utility class that allowed me to determine generically what calls a closure makes (without actually letting it make any calls).  This lets me see what it&#8217;s trying to do before letting it actually do it.<br />
<span id="more-136"></span><br />
It works by overriding the delegate of the closure (a delegate intercepts all method and property get/set calls that have not already been dealt with).  It assigns it to an instance of the ClosureInterrogator which implements the propertyMissing and methodMissing methods.  Any property or set method that is called gets saved in a map that is returned to the caller.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> ClosureInterrogator <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">private</span> <span style="color: #aaaadd; font-weight: bold;">Map</span> closureValueMap <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span>:<span style="color: #669966;">&#93;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">static</span> <span style="color: #aaaadd; font-weight: bold;">Map</span> extractValuesFromClosure<span style="color: #669966;">&#40;</span>Closure closure<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> interrogator <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ClosureInterrogator<span style="color: #669966;">&#40;</span>closure<span style="color: #669966;">&#41;</span>
        <span style="color: #000000; font-weight: bold;">return</span> interrogator.<span style="color: #006600;">closureValueMap</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> ClosureInterrogator<span style="color: #669966;">&#40;</span>Closure closure<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> oldResolveStrategy <span style="color: #669966;">=</span> closure.<span style="color: #006600;">getResolveStrategy</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #000000; font-weight: bold;">def</span> oldDelegate <span style="color: #669966;">=</span> closure.<span style="color: #006600;">getDelegate</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        closure.<span style="color: #006600;">delegate</span> <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">this</span>
        closure.<span style="color: #006600;">resolveStrategy</span> <span style="color: #669966;">=</span> Closure.<span style="color: #006600;">DELEGATE_FIRST</span>
&nbsp;
        <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #669966;">&#123;</span>
            closure<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #669966;">&#125;</span> <span style="color: #000000; font-weight: bold;">finally</span> <span style="color: #669966;">&#123;</span>        
            closure.<span style="color: #006600;">setDelegate</span><span style="color: #669966;">&#40;</span>oldDelegate<span style="color: #669966;">&#41;</span>
            closure.<span style="color: #006600;">setResolveStrategy</span><span style="color: #669966;">&#40;</span>oldResolveStrategy<span style="color: #669966;">&#41;</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">// property getter</span>
    <span style="color: #000000; font-weight: bold;">def</span> propertyMissing<span style="color: #669966;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> name<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">return</span> closureValueMap<span style="color: #669966;">&#91;</span>name<span style="color: #669966;">&#93;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #808080; font-style: italic;">// property setter</span>
    <span style="color: #000000; font-weight: bold;">def</span> propertyMissing<span style="color: #669966;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> name, value<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        closureValueMap<span style="color: #669966;">&#91;</span>name<span style="color: #669966;">&#93;</span> <span style="color: #669966;">=</span> value
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> methodMissing<span style="color: #669966;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> name, args<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>args.<span style="color: #663399;">size</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">==</span> <span style="color: #cc66cc;">1</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
            closureValueMap<span style="color: #669966;">&#91;</span>name<span style="color: #669966;">&#93;</span> <span style="color: #669966;">=</span> args<span style="color: #669966;">&#91;</span><span style="color: #cc66cc;">0</span><span style="color: #669966;">&#93;</span>
        <span style="color: #669966;">&#125;</span> <span style="color: #996600;">else</span> <span style="color: #669966;">&#123;</span>
            closureValueMap<span style="color: #669966;">&#91;</span>name<span style="color: #669966;">&#93;</span> <span style="color: #669966;">=</span> args
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>This technique is the basis for all groovy mocking techniques and libraries, it&#8217;s also the main technique used to create a <acronym title="Domain Specific Language">DSL</acronym> with groovy.</p>
<p>Here is a sample class that has a closure (&#8220;something&#8221;) that we want to extract the values from.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> SomeClass <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">static</span> something <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span>
        key1 <span style="color: #aa0000;">&quot;value1&quot;</span>              <span style="color: #808080; font-style: italic;">// calls methodMissing(&quot;key1&quot;, [&quot;value1&quot;])</span>
        key2<span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;value2&quot;</span><span style="color: #669966;">&#41;</span>             <span style="color: #808080; font-style: italic;">// calls methodMissing(&quot;key2&quot;, [&quot;value2&quot;])</span>
        key3 <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;value3&quot;</span>            <span style="color: #808080; font-style: italic;">// calls propertyMissing(&quot;key3&quot;, &quot;value3&quot;)</span>
        key4 <span style="color: #aa0000;">&quot;foo&quot;</span>, <span style="color: #aa0000;">&quot;bar&quot;</span>, <span style="color: #aa0000;">&quot;baz&quot;</span>   <span style="color: #808080; font-style: italic;">// calls methodMissing(&quot;key4&quot;, [&quot;foo&quot;,&quot;bar&quot;,&quot;baz&quot;])</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>If we call &#8220;extractValuesFromClosure&#8221; on the &#8220;something&#8221; closure, we&#8217;ll get back a map that has all of the values we want in it.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> closureValueMap <span style="color: #669966;">=</span> ClosureInterrogator.<span style="color: #006600;">extractValuesFromClosure</span><span style="color: #669966;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> SomeClass<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">something</span><span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value1&quot;</span> <span style="color: #669966;">==</span> closureValueMap.<span style="color: #aa0000;">&quot;key1&quot;</span>  <span style="color: #808080; font-style: italic;">// calls propertyMissing(&quot;key1&quot;)</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value2&quot;</span> <span style="color: #669966;">==</span> closureValueMap.<span style="color: #aa0000;">&quot;key2&quot;</span>  <span style="color: #808080; font-style: italic;">// calls propertyMissing(&quot;key2&quot;)</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value3&quot;</span> <span style="color: #669966;">==</span> closureValueMap.<span style="color: #aa0000;">&quot;key3&quot;</span>  <span style="color: #808080; font-style: italic;">// calls propertyMissing(&quot;key3&quot;)</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;foo&quot;</span>, <span style="color: #aa0000;">&quot;bar&quot;</span>, <span style="color: #aa0000;">&quot;baz&quot;</span><span style="color: #669966;">&#93;</span> <span style="color: #669966;">==</span> closureValueMap.<span style="color: #aa0000;">&quot;key4&quot;</span>  <span style="color: #808080; font-style: italic;">// calls propertyMissing(&quot;key4&quot;)</span></pre></div></div>

<p>This class will work with any type of closure, such as this closure used by the <a href="http://www.grails.org/Mail+plugin" onclick="pageTracker._trackPageview('/outgoing/www.grails.org/Mail+plugin?referer=');">grails mail plugin</a> to send mail.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> mailClosure <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span>
   to <span style="color: #aa0000;">&quot;fred@g2one.com&quot;</span>,<span style="color: #aa0000;">&quot;ginger@g2one.com&quot;</span>
   from <span style="color: #aa0000;">&quot;john@g2one.com&quot;</span>
   cc <span style="color: #aa0000;">&quot;marge@g2one.com&quot;</span>, <span style="color: #aa0000;">&quot;ed@g2one.com&quot;</span>
   bcc <span style="color: #aa0000;">&quot;joe@g2one.com&quot;</span>
   subject <span style="color: #aa0000;">&quot;Hello John&quot;</span>
   body <span style="color: #aa0000;">'this is some text'</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> results <span style="color: #669966;">=</span> ClosureInterrogator.<span style="color: #006600;">extractValuesFromClosure</span><span style="color: #669966;">&#40;</span>mailClosure<span style="color: #669966;">&#41;</span>
<span style="color: #663366;">println</span> results
<span style="color: #808080; font-style: italic;">// prints:</span>
<span style="color: #808080; font-style: italic;">// [to:[fred@g2one.com, ginger@g2one.com], from:john@g2one.com, cc:[marge@g2one.com, ed@g2one.com], bcc:joe@g2one.com, subject:Hello John, body:this is some text]</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> results.<span style="color: #006600;">to</span>.<span style="color: #006600;">every</span> <span style="color: #669966;">&#123;</span> it.<span style="color: #006600;">endsWith</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;g2one.com&quot;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#125;</span></pre></div></div>

<p>If we wanted to assert that within a test environment, we&#8217;re only sending e-mail to a specific domain, this would be one technique to assert it before we actually send the e-mail off.</p>
<p>ClosureInterrogator is generic enough that it could also be used on a number of Grails/GORM domain closures such as &#8220;constraints&#8221; and &#8220;mapping&#8221;.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2010/01/24/interrogating-arbitrary-groovy-closures-for-values/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Modularizing Groovy Config Files With a Dash of Meta-Programming</title>
		<link>http://naleid.com/blog/2009/07/30/modularizing-groovy-config-files-with-a-dash-of-meta-programming/</link>
		<comments>http://naleid.com/blog/2009/07/30/modularizing-groovy-config-files-with-a-dash-of-meta-programming/#comments</comments>
		<pubDate>Fri, 31 Jul 2009 04:56:07 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[config]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=60</guid>
		<description><![CDATA[This is a continuation of a sporadic set of blog posts about some practical uses for groovy metaprogramming.
Groovy Config DSL Overview
In Java, configuration is normally done with properties files.  They&#8217;re kind of a pain because they&#8217;re inflexible, don&#8217;t allow executable code, and don&#8217;t easily provide a heirarchy.
Groovy greatly improves on Java by building in [...]]]></description>
			<content:encoded><![CDATA[<p>This is a continuation of a sporadic <a href="http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/">set</a> <a href="http://naleid.com/blog/2008/05/07/what-methods-does-my-groovygrails-class-have/">of blog</a> <a href="http://naleid.com/blog/2009/06/01/groovy-metaclass-overriding-a-method-whilst-using-the-old-implementation/">posts</a> about some practical uses for groovy metaprogramming.</p>
<h2>Groovy Config DSL Overview</h2>
<p>In Java, configuration is normally done with properties files.  They&#8217;re kind of a pain because they&#8217;re inflexible, don&#8217;t allow executable code, and don&#8217;t easily provide a heirarchy.</p>
<p>Groovy greatly improves on Java by building in support for a simple configuration DSL using the <a href="http://groovy.codehaus.org/ConfigSlurper" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/ConfigSlurper?referer=');">ConfigSlurper</a>.<span id="more-60"></span></p>
<p>To use it, just instantiate a new ConfigSlurper and give it the name of a groovy script file that you&#8217;d like it to parse.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// SampleConfig.groovy, a simple groovy script</span>
person <span style="color: #669966;">&#123;</span>
    firstName <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;Ted&quot;</span>
    address <span style="color: #669966;">&#123;</span>
        city <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;Minneapolis&quot;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// TestConfiguration.groovy</span>
<span style="color: #000000; font-weight: bold;">def</span> configObject <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConfigSlurper<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">parse</span><span style="color: #669966;">&#40;</span>SampleConfig<span style="color: #669966;">&#41;</span></pre></div></div>

<p>This creates a ConfigObject, which is a subclass of a Map and can be similarly accessed using dot notation</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #663366;">println</span> configObject
<span style="color: #808080; font-style: italic;">// prints: [person:[firstName:Ted, address:[city:Minneapolis]]]</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;Minneapolis&quot;</span> <span style="color: #669966;">==</span> configObject.<span style="color: #006600;">person</span>.<span style="color: #006600;">address</span>.<span style="color: #006600;">city</span></pre></div></div>

<p>ConfigSlurper is built into groovy and is heavily used for <a href="http://www.grails.org/doc/1.1.x/guide/3.%20Configuration.html" onclick="pageTracker._trackPageview('/outgoing/www.grails.org/doc/1.1.x/guide/3._20Configuration.html?referer=');">Grails configuration</a>.  Grails is a &#8220;convention over configuration&#8221; framework, but anytime you want to modify the conventions, you&#8217;re likely going to be touching a config file.  Grails plugin authors also often use config files to drive plugin behavior.</p>
<p>In larger projects, these config files can start to get quite large and unwieldy.  </p>
<h3>How ConfigSlurper Does It&#8217;s Thing</h3>
<p>DSLs in groovy, like the ConfigSlurper DSL, work by intercepting calls to methods and property setters.  If you look at the internals of the <a href="https://svn.codehaus.org/groovy/trunk/groovy/groovy-core/src/main/groovy/util/ConfigSlurper.groovy" onclick="pageTracker._trackPageview('/outgoing/svn.codehaus.org/groovy/trunk/groovy/groovy-core/src/main/groovy/util/ConfigSlurper.groovy?referer=');">ConfigSlurper.parse(Script script, URL location) method</a> (the big one at the bottom), you&#8217;ll see that it heavily messes with the metaClass of the configuration script by creating custom versions of invokeMethod and getProperty.</p>
<p><b>Intercepting Methods</b></p>
<p>When you have a config script that says:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">person <span style="color: #669966;">&#123;</span>
    firstName <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;ted&quot;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>What you&#8217;re saying is call the &#8220;person&#8221; method and pass the <code>{ firstName = "ted" }</code> closure to it.  </p>
<p>Normally, this would blow up because you haven&#8217;t defined a &#8220;person&#8221; method.  With the modified metaClass, invokeMethod instead adds &#8220;person&#8221; as a key in the config map and then runs the closure associated with person.  Any subsequent method calls or properties in that closure are assigned as the value in the map to the &#8220;person&#8221; key.</p>
<p><b>Intercepting Property Assignments</b></p>
<p>Property assignment (like <code>firstName = "ted"</code>) works a little differently.  Every script has something associated with it called a <a href="http://groovy.codehaus.org/api/groovy/lang/Binding.html" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/api/groovy/lang/Binding.html?referer=');">binding</a>.  The binding holds script-wide variables that aren&#8217;t explicitly declared.  When parsed by ConfigSlurper, calls that would normally set variables in the script&#8217;s binding are monitored and inserted into the map at the appropriate place in the stack.</p>
<p>So with the modified metaClass and binding the config above turns into this when slurped:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&#91;</span>person:<span style="color: #669966;">&#91;</span>firstName:ted<span style="color: #669966;">&#93;</span><span style="color: #669966;">&#93;</span></pre></div></div>

<p>If we had explicitly declared the name property, it wouldn&#8217;t get in the binding, and wouldn&#8217;t be part of the resulting config map.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">person <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> firstName <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;ted&quot;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// result: [person:[:]]</span></pre></div></div>

<h2>Modularizing Config Scripts</h2>
<p>I got to thinking about how nice <a href="http://www.grails.org/doc/1.1.x/ref/Tags/render.html" onclick="pageTracker._trackPageview('/outgoing/www.grails.org/doc/1.1.x/ref/Tags/render.html?referer=');">gsp files are to manage with the ability to include other gsp fragments</a>.  It would be great if we could do the same kind of thing with config files.  That would let us better manage large config files.  It would also let us define external config files that we pull in at run time, or config templates that we want to override just a piece or two out of.  All from inside the config file itself.</p>
<p>Something like:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// SecurityConfig.groovy</span>
security <span style="color: #669966;">&#123;</span>
    includeScript<span style="color: #669966;">&#40;</span> SecurityDefaults <span style="color: #669966;">&#41;</span>
    active <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">true</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// SecurityDefaults.groovy</span>
username <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;mysql&quot;</span>
password <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;sekr1t&quot;</span>	    
url <span style="color: #669966;">&#123;</span>
    port <span style="color: #669966;">=</span> <span style="color: #cc66cc;">2112</span>    
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>Loading SecurityConfig would have everything in SecurityDefaults and also set active = true:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> configObject <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConfigSlurper<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">parse</span><span style="color: #669966;">&#40;</span> SecurityConfig <span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #663366;">println</span> configObject
<span style="color: #808080; font-style: italic;">// [security:[username:mysql, password:sekr1t, url:[port:2112], active:true]]</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> configObject.<span style="color: #006600;">security</span>.<span style="color: #006600;">active</span> <span style="color: #669966;">==</span> <span style="color: #000000; font-weight: bold;">true</span>
<span style="color: #000000; font-weight: bold;">assert</span> configObject.<span style="color: #006600;">security</span>.<span style="color: #006600;">url</span>.<span style="color: #006600;">port</span> <span style="color: #669966;">==</span> <span style="color: #cc66cc;">2112</span></pre></div></div>

<h3>A Solution</h3>
<p>Getting the same functionality in config files ended up being a bit more difficult a problem to solve than I first expected.  A big part of that was due to some misconceptions I had about how the ConfigSlurper was working as a DSL, as well as what exactly a groovy Script was and how it differed from a regular Groovy class.	</p>
<p>It turns out that when a groovy script is compiled, it&#8217;s contents are placed inside a concrete implementation of the abstract Script.run() method.   So this:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// MyGroovyScript.groovy</span>
person <span style="color: #669966;">&#123;</span>
    firstName <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;Ted&quot;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>Is functionally equivalent to this:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> MyGroovyScript <span style="color: #000000; font-weight: bold;">extends</span> Script <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> run<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
	person <span style="color: #669966;">&#123;</span>
     	    firstName <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;Ted&quot;</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>	    
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>So one way to solve the problem is to create an abstract subclass of script and implement the &#8220;includeScript&#8221; method.  All &#8220;includeScript&#8221; needs to do is override the metaClass and binding of the child script so that it uses <i>the same metaClass and binding as the parent script</i>.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">abstract</span> <span style="color: #000000; font-weight: bold;">class</span> ComposedConfigScript <span style="color: #000000; font-weight: bold;">extends</span> Script <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> includeScript<span style="color: #669966;">&#40;</span>scriptClass<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> scriptInstance <span style="color: #669966;">=</span> scriptClass.<span style="color: #006600;">newInstance</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
        scriptInstance.<span style="color: #006600;">metaClass</span> <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">metaClass</span>
        scriptInstance.<span style="color: #006600;">binding</span> <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConfigBinding<span style="color: #669966;">&#40;</span><span style="color: #000000; font-weight: bold;">this</span>.<span style="color: #006600;">getBinding</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">callable</span><span style="color: #669966;">&#41;</span>
        scriptInstance.<span style="color: #669966;">&amp;</span>run.<span style="color: #663366; font-weight: bold;">call</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>ConfigSlurper modifies the metaClass and binding before loading the parent class to keep track of things as the script executes, it doesn&#8217;t care who&#8217;s actually calling the methods.</p>
<p>This lets us do exactly what we want, the only limitation to this approach is that the parent script needs to explicitly state that it&#8217;s a class that extends ComposedConfigScript and implements the run() method:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">// SecurityConfig.groovy</span>
<span style="color: #000000; font-weight: bold;">class</span> SecurityConfig <span style="color: #000000; font-weight: bold;">extends</span> ComposedConfigScript <span style="color: #669966;">&#123;</span>	        
    <span style="color: #000000; font-weight: bold;">def</span> run<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> <span style="color: #808080; font-style: italic;">// normal contents of a config file go in here</span>
&nbsp;
        security <span style="color: #669966;">&#123;</span>
            includeScript<span style="color: #669966;">&#40;</span> SecurityDefaults <span style="color: #669966;">&#41;</span>
            active <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">true</span>
        <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// SecurityDefaults.groovy</span>
username <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;mysql&quot;</span>
password <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;sekr1t&quot;</span>	    
url <span style="color: #669966;">&#123;</span>
    host <span style="color: #669966;">=</span> <span style="color: #aa0000;">&quot;example.com&quot;</span>
    port <span style="color: #669966;">=</span> <span style="color: #cc66cc;">2112</span>    
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// OtherClass.groovy</span>
<span style="color: #000000; font-weight: bold;">def</span> configObject <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ConfigSlurper<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">parse</span><span style="color: #669966;">&#40;</span> SecurityConfig <span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #663366;">println</span> configObject
<span style="color: #808080; font-style: italic;">// prints: [security:[username:mysql, password:sekr1t, url:[host:example.com, port:2112], active:true]]</span></pre></div></div>

<p>Using this technique lets us modularize our config files.  This helps us both better organize things as well as decouple pieces of information that don&#8217;t necessarily belong together (like log4j info and website url information).  </p>
<p>I had tried a number of other techniques that would let me use includeScript without declaring an explict class (like using a <a href="http://groovy.codehaus.org/Using+the+Delegating+Meta+Class" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/Using+the+Delegating+Meta+Class?referer=');">DelegatingMetaClass</a> for the Script class and <a href="http://groovy.codehaus.org/Static+Import+Usage" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/Static+Import+Usage?referer=');">static import</a>) but wasn&#8217;t able to get them working to my satisfaction.  Those solutions are great for most cases, but break down with all the meta-magic that&#8217;s already happening with the ConfigSlurper. </p>
<p>Another option that could be considered, would be to patch the ConfigSlurper implementation to directly allow includeScript functionality.  I&#8217;d be happy to submit a patch that does this if people are interested in this functionality.<br />
<script type="text/javascript">var dzone_url = 'http://naleid.com/blog/2009/07/30/modularizing-groovy-config-files-with-a-dash-of-meta-programming/';</script><br />
<script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/07/30/modularizing-groovy-config-files-with-a-dash-of-meta-programming/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Grails build-test-data presentation</title>
		<link>http://naleid.com/blog/2009/07/14/grails-build-test-data-presentation/</link>
		<comments>http://naleid.com/blog/2009/07/14/grails-build-test-data-presentation/#comments</comments>
		<pubDate>Wed, 15 Jul 2009 03:28:56 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=59</guid>
		<description><![CDATA[I gave a presentation tonight on the build-test-data grails plugin at the Groovy Users of Minnesota (GUM) meeting that was well received.
Lots of good questions from the people in attendance.  Thanks to everyone for showing up.
Here&#8217;s a version of it on slideshow:
Grails build-test-data Plugin
View more documents from tednaleid.

I also released a new bugfix version [...]]]></description>
			<content:encoded><![CDATA[<p>I gave a presentation tonight on the <a href="http://bitbucket.org/tednaleid/grails-test-data/wiki/Home" onclick="pageTracker._trackPageview('/outgoing/bitbucket.org/tednaleid/grails-test-data/wiki/Home?referer=');">build-test-data</a> grails plugin at the <a href="http://groovy.mn" onclick="pageTracker._trackPageview('/outgoing/groovy.mn?referer=');">Groovy Users of Minnesota (GUM)</a> meeting that was well received.</p>
<p>Lots of good questions from the people in attendance.  Thanks to everyone for showing up.</p>
<p>Here&#8217;s a version of it on slideshow:<span id="more-59"></span></p>
<div style="width:650px;text-align:left" id="__ss_1723277"><a style="font:14px Helvetica,Arial,Sans-serif;display:block;margin:12px 0 3px 0;text-decoration:underline;" href="http://www.slideshare.net/tednaleid/grails-buildtestdata-plugin-1723277" title="Grails build-test-data Plugin" onclick="pageTracker._trackPageview('/outgoing/www.slideshare.net/tednaleid/grails-buildtestdata-plugin-1723277?referer=');">Grails build-test-data Plugin</a><object style="margin:0px" width="650" height="547"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=build-test-datapresentation-090714222053-phpapp01&#038;stripped_title=grails-buildtestdata-plugin-1723277" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><embed src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=build-test-datapresentation-090714222053-phpapp01&#038;stripped_title=grails-buildtestdata-plugin-1723277" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="650" height="547"></embed></object>
<div style="font-size:11px;font-family:tahoma,arial;height:26px;padding-top:2px;">View more <a style="text-decoration:underline;" href="http://www.slideshare.net/" onclick="pageTracker._trackPageview('/outgoing/www.slideshare.net/?referer=');">documents</a> from <a style="text-decoration:underline;" href="http://www.slideshare.net/tednaleid" onclick="pageTracker._trackPageview('/outgoing/www.slideshare.net/tednaleid?referer=');">tednaleid</a>.</div>
</div>
<p>I also released a new bugfix version of build-test-data earlier today (0.2.2).  Mostly fixed bugs, but there&#8217;s also a new config setting that lets you disable the plugin in specified environments (suggested by Scott Vlaminck @ <a href="http://refactr.com"/>refactr</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/07/14/grails-build-test-data-presentation/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Groovy closures make unit testing with &#8220;soft asserts&#8221; simple</title>
		<link>http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/</link>
		<comments>http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/#comments</comments>
		<pubDate>Fri, 26 Jun 2009 04:25:45 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[closures]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=58</guid>
		<description><![CDATA[A recent blog post, Cedric Beust asks about how to cleanly implement &#8220;soft asserts&#8221;.  Soft asserts are test assertions that don&#8217;t &#8220;fail fast&#8221;.  Instead, all of the assertion failures in the test method are collected and reported at the end of the test.
So far, the proposals in the comments look fairly clunky to [...]]]></description>
			<content:encoded><![CDATA[<p>A recent blog post, <a href="http://beust.com/weblog/archives/000514.html" onclick="pageTracker._trackPageview('/outgoing/beust.com/weblog/archives/000514.html?referer=');">Cedric Beust asks about how to cleanly implement &#8220;soft asserts&#8221;</a>.  Soft asserts are test assertions that don&#8217;t &#8220;fail fast&#8221;.  Instead, all of the assertion failures in the test method are collected and reported at the end of the test.</p>
<p>So far, the proposals in the comments look fairly clunky to me and include defining whole sets of new methods like &#8220;assertEqualsButContinue(&#8220;foo&#8221;, &#8220;foo&#8221;)&#8221;, chaning assertions together jQuery-style, or using lists to hold all of our assertions.</p>
<p>Wouldn&#8217;t it be a lot nicer if we could continue to use the same methods that we&#8217;re already using?</p>
<p>In groovy, enabling soft assertions is easy with a little closure magic.<span id="more-58"></span></p>
<p>Closures have a property called the &#8220;resolveStrategy&#8221; that determines where the code inside the closure should look to resolve method names.  The default resolve strategy is OWNER_FIRST.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">Closure closure <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #663366;">println</span> <span style="color: #aa0000;">&quot;foo&quot;</span> <span style="color: #669966;">&#125;</span>
<span style="color: #000000; font-weight: bold;">assert</span> closure.<span style="color: #006600;">getResolveStrategy</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">==</span> Closure.<span style="color: #006600;">OWNER_FIRST</span></pre></div></div>

<p>OWNER_FIRST means that if something isn&#8217;t defined inside the closure (local scope), it should check the owner of the closure to see if it can resolve it.  The owner of the closure is the declaring class or another closure that contains our closure.</p>
<p>Closures also have a property called the &#8220;delegate&#8221;.  By default, the delegate is equal to the owner, but we have the ability to change the delegate to something else.  We can also change the resolveStrategy for the closure so when something isn&#8217;t defined, the delegate is the first place that is checked.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Original <span style="color: #669966;">&#123;</span>
   <span style="color: #000000; font-weight: bold;">def</span> closure <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> value<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#125;</span>   
&nbsp;
   <span style="color: #000000; font-weight: bold;">def</span> value <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aa0000;">&quot;value from owner&quot;</span> <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> SomethingElse <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> value <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aa0000;">&quot;value from delegate&quot;</span> <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> obj <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Original<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value from owner&quot;</span> <span style="color: #669966;">==</span> obj.<span style="color: #006600;">closure</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// the owner is the enclosing class, and its the same as the delegate by default</span>
<span style="color: #000000; font-weight: bold;">assert</span> obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">owner</span>.<span style="color: #000000; font-weight: bold;">class</span> <span style="color: #669966;">==</span> Original
<span style="color: #000000; font-weight: bold;">assert</span> obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">owner</span> <span style="color: #669966;">==</span> obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">delegate</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// but we can change the closure's delegate to something else if we want</span>
obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">delegate</span> <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> SomethingElse<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// by default, the closure looks at the owner before the delegate, value is unchanged</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value from owner&quot;</span> <span style="color: #669966;">==</span> obj.<span style="color: #006600;">closure</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> 
<span style="color: #000000; font-weight: bold;">assert</span> obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">getResolveStrategy</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">==</span> Closure.<span style="color: #006600;">OWNER_FIRST</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// changing the closure's resolve strategy switches who gets to handle value()</span>
obj.<span style="color: #006600;">closure</span>.<span style="color: #006600;">resolveStrategy</span> <span style="color: #669966;">=</span> Closure.<span style="color: #006600;">DELEGATE_FIRST</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #aa0000;">&quot;value from delegate&quot;</span> <span style="color: #669966;">==</span> obj.<span style="color: #006600;">closure</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>Groovy also has a <a href="http://groovy.codehaus.org/Using+invokeMethod+and+getProperty" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/Using+invokeMethod+and+getProperty?referer=');">special metaClass method called invokeMethod</a> that allows you to manipulate any method calls that are invoked on that metaClass.</p>
<p>Using these two things in conjunction, we can write a small class that lets us collect JUnit assertion errors thrown by any method starting with &#8220;assert&#8221;.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> SoftAsserts <span style="color: #669966;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">def</span> oldDelegate
    <span style="color: #000000; font-weight: bold;">def</span> failedAssertions <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span><span style="color: #669966;">&#93;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">static</span> softAsserts<span style="color: #669966;">&#40;</span>closure<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">new</span> SoftAsserts<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">bundleAsserts</span><span style="color: #669966;">&#40;</span>closure<span style="color: #669966;">&#41;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">private</span> bundleAsserts <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> closure <span style="color: #669966;">-&gt;</span>
        closure.<span style="color: #006600;">resolveStrategy</span> <span style="color: #669966;">=</span> Closure.<span style="color: #006600;">DELEGATE_ONLY</span>
        oldDelegate <span style="color: #669966;">=</span> closure.<span style="color: #006600;">delegate</span>
        closure.<span style="color: #006600;">delegate</span> <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">this</span>
        closure<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>   
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>failedAssertions<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #aaaadd; font-weight: bold;">Exception</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;${failedAssertions.size()} failed assertions found:<span style="color: #000099; font-weight: bold;">\n</span>${failedAssertions.message.join('<span style="color: #000099; font-weight: bold;">\n</span>')}&quot;</span><span style="color: #669966;">&#41;</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> <span style="color: #663366;">invokeMethod</span><span style="color: #669966;">&#40;</span><span style="color: #aaaadd; font-weight: bold;">String</span> name, args<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #996600;">if</span> <span style="color: #669966;">&#40;</span>name.<span style="color: #006600;">startsWith</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;assert&quot;</span><span style="color: #669966;">&#41;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">try</span> <span style="color: #669966;">&#123;</span>
                <span style="color: #000000; font-weight: bold;">return</span> oldDelegate.<span style="color: #663366;">invokeMethod</span><span style="color: #669966;">&#40;</span>name, args<span style="color: #669966;">&#41;</span>
            <span style="color: #669966;">&#125;</span> <span style="color: #000000; font-weight: bold;">catch</span> <span style="color: #669966;">&#40;</span>junit.<span style="color: #006600;">framework</span>.<span style="color: #006600;">AssertionFailedError</span> e<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
                failedAssertions <span style="color: #669966;">&lt;&lt;</span> e
            <span style="color: #669966;">&#125;</span>
        <span style="color: #669966;">&#125;</span> <span style="color: #996600;">else</span> <span style="color: #669966;">&#123;</span>
            <span style="color: #000000; font-weight: bold;">return</span> oldDelegate.<span style="color: #663366;">invokeMethod</span><span style="color: #669966;">&#40;</span>name, args<span style="color: #669966;">&#41;</span>         
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>This test class does a static import of the SoftAsserts.softAsserts closure so it can use it in a natural way.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">import</span> <span style="color: #996600;">grails.test.*</span>
<span style="color: #000000; font-weight: bold;">import</span> <span style="color: #996600;">static</span> SoftAsserts.<span style="color: #006600;">softAsserts</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> BookTests <span style="color: #000000; font-weight: bold;">extends</span> GroovyTestCase <span style="color: #669966;">&#123;</span>
    <span style="color: #993333;">void</span> testBookTrueAssertsPasses<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> book <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span>title: <span style="color: #aa0000;">&quot;Infinite Jest&quot;</span><span style="color: #669966;">&#93;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;">// all 4 assertions pass and we are able to refer to local variables </span>
        <span style="color: #808080; font-style: italic;">// like book and local methods like trueMethod() </span>
        softAsserts <span style="color: #669966;">&#123;</span> 
            assertTrue <span style="color: #000000; font-weight: bold;">true</span>
            assertTrue trueMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
            assertNotNull book
            assertEquals <span style="color: #aa0000;">&quot;Infinite Jest&quot;</span>, book.<span style="color: #006600;">title</span>
        <span style="color: #669966;">&#125;</span>
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #993333;">void</span> testBookFalseAssertsCollectsFailures<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span>
        <span style="color: #000000; font-weight: bold;">def</span> book <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span>title: <span style="color: #aa0000;">&quot;Infinite Jest&quot;</span><span style="color: #669966;">&#93;</span>
&nbsp;
        <span style="color: #808080; font-style: italic;">// all 4 assertions throw errors, but all are collected before </span>
        <span style="color: #808080; font-style: italic;">// an exception is actually thrown</span>
        softAsserts <span style="color: #669966;">&#123;</span> 
            assertTrue <span style="color: #aa0000;">&quot;False is not true&quot;</span>, <span style="color: #000000; font-weight: bold;">false</span>
            assertTrue <span style="color: #aa0000;">&quot;falseMethod() is not true&quot;</span>, falseMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
            assertNull <span style="color: #aa0000;">&quot;Book is not null&quot;</span>, book
            assertEquals <span style="color: #aa0000;">&quot;House of Leaves&quot;</span>, book.<span style="color: #006600;">title</span>
        <span style="color: #669966;">&#125;</span>   
    <span style="color: #669966;">&#125;</span>
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> trueMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">true</span> <span style="color: #669966;">&#125;</span>   
&nbsp;
    <span style="color: #000000; font-weight: bold;">def</span> falseMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#123;</span> <span style="color: #000000; font-weight: bold;">false</span> <span style="color: #669966;">&#125;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>The first test shows how a passing test can successfully refer to other variables and methods defined inside the test class.  The second test fails, but it doesn&#8217;t fail till all 4 of the assertions are tried and collected.  It then throws an error with the assertion failure count and the individual error messages:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;">Testcase: testBookFalseAssertsCollectsFailures took <span style="color: #cc66cc;">0.371</span> sec
	Caused an ERROR
<span style="color: #cc66cc;">4</span> failed assertions found:
<span style="color: #000000; font-weight: bold;">False</span> is not <span style="color: #000000; font-weight: bold;">true</span>
falseMethod<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> is not <span style="color: #000000; font-weight: bold;">true</span>
<span style="color: #aaaadd; font-weight: bold;">Book</span> is not <span style="color: #000000; font-weight: bold;">null</span>
expected:<span style="color: #669966;">&lt;</span><span style="color: #669966;">&#91;</span>House of Leaves<span style="color: #669966;">&#93;</span><span style="color: #669966;">&gt;</span> but was:<span style="color: #669966;">&lt;</span><span style="color: #669966;">&#91;</span>Infinite Jest<span style="color: #669966;">&#93;</span><span style="color: #669966;">&gt;</span></pre></div></div>

<p>It might be useful to also print out the individual stack traces for each assertion error, but this is left as an exercise for the reader.</p>
<p>In most situations, I like the fail fast behavior and limiting tests to exercising one feature at a time, but there have been a few test cases where something like this would&#8217;ve been nice.<br />
<script type="text/javascript">var dzone_url = 'http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/';</script><br />
<script type="text/javascript">var dzone_style = '1';</script><br />
<script language="javascript" src="http://widgets.dzone.com/widgets/zoneit.js"></script> </p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/06/25/groovy-closures-make-unit-testing-with-soft-asserts-simple/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Groovy MetaClass: Overriding a method whilst using the old implementation</title>
		<link>http://naleid.com/blog/2009/06/01/groovy-metaclass-overriding-a-method-whilst-using-the-old-implementation/</link>
		<comments>http://naleid.com/blog/2009/06/01/groovy-metaclass-overriding-a-method-whilst-using-the-old-implementation/#comments</comments>
		<pubDate>Tue, 02 Jun 2009 04:32:11 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[metaclass]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=54</guid>
		<description><![CDATA[The need to add some functionality an existing method, but avoiding cutting and pasting the old implementation has come up a few times over the last week.
Sometimes, creating a subclass isn&#8217;t feasible, often because you don&#8217;t control all of the places where that class gets used.
Calling super() without the subclass
All you need to do is [...]]]></description>
			<content:encoded><![CDATA[<p>The need to add some functionality an existing method, but avoiding cutting and pasting the old implementation has <a href="http://stackoverflow.com/questions/920582/how-to-change-behaviour-of-the-methed-in-groovy-using-that-method-in-metaclass/924464#924464" onclick="pageTracker._trackPageview('/outgoing/stackoverflow.com/questions/920582/how-to-change-behaviour-of-the-methed-in-groovy-using-that-method-in-metaclass/924464_924464?referer=');">come up</a> a <a href="http://twitter.com/tednaleid/status/1938388517" onclick="pageTracker._trackPageview('/outgoing/twitter.com/tednaleid/status/1938388517?referer=');">few times</a> over the last week.</p>
<p>Sometimes, creating a subclass isn&#8217;t feasible, often because you don&#8217;t control all of the places where that class gets used.<span id="more-54"></span></p>
<h4>Calling super() without the subclass</h4>
<p>All you need to do is to get a reference to the old method.  Getting methods from the metaClass is easy, if there&#8217;s only one method signature for that method, just use the &#8220;&#038;&#8221; operator:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> oldToOctalString <span style="color: #669966;">=</span> <span style="color: #aaaadd; font-weight: bold;">Long</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #669966;">&amp;</span>toOctalString</pre></div></div>

<p>If there are multiple method signatures for a method, you&#8217;ll need to use the getMetaMethod method and pass in the signature of the method you want.  This is probably the safest way to ensure that you&#8217;re getting the method that you think you&#8217;re getting.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #663366;">println</span> <span style="color: #aaaadd; font-weight: bold;">Long</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">methods</span>.<span style="color: #663399;">findAll</span> <span style="color: #669966;">&#123;</span> it.<span style="color: #006600;">name</span> <span style="color: #669966;">==</span> <span style="color: #aa0000;">&quot;compareTo&quot;</span> <span style="color: #669966;">&#125;</span>.<span style="color: #663399;">join</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #669966;">&#41;</span>
<span style="color: #808080; font-style: italic;">// prints:</span>
<span style="color: #808080; font-style: italic;">// public int java.lang.Long.compareTo(java.lang.Long)</span>
<span style="color: #808080; font-style: italic;">// public int java.lang.Long.compareTo(java.lang.Object)</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">def</span> oldCompareTo <span style="color: #669966;">=</span> <span style="color: #aaaadd; font-weight: bold;">Long</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">getMetaMethod</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;compareTo&quot;</span>, <span style="color: #669966;">&#91;</span>java.<span style="color: #006600;">lang</span>.<span style="color: #aaaadd; font-weight: bold;">Long</span><span style="color: #669966;">&#93;</span> <span style="color: #000000; font-weight: bold;">as</span> <span style="color: #000000; font-weight: bold;">Class</span><span style="color: #669966;">&#91;</span><span style="color: #669966;">&#93;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>Now that you know how to get a reference to the method you want, you can redefine the method, while still letting the old method&#8217;s implementation do all the heavy lifting for you.</p>
<p>Here, we redefine the &#8220;plus&#8221; method on Integer to always work with absolute values, without actually getting our hands dirty in all that messy arithmetic:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> oldPlus <span style="color: #669966;">=</span> <span style="color: #aaaadd; font-weight: bold;">Integer</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">getMetaMethod</span><span style="color: #669966;">&#40;</span><span style="color: #aa0000;">&quot;plus&quot;</span>, <span style="color: #669966;">&#91;</span><span style="color: #aaaadd; font-weight: bold;">Integer</span><span style="color: #669966;">&#93;</span> <span style="color: #000000; font-weight: bold;">as</span> <span style="color: #000000; font-weight: bold;">Class</span><span style="color: #669966;">&#91;</span><span style="color: #669966;">&#93;</span><span style="color: #669966;">&#41;</span>
&nbsp;
<span style="color: #aaaadd; font-weight: bold;">Integer</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">plus</span> <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #aaaadd; font-weight: bold;">Integer</span> n <span style="color: #669966;">-&gt;</span>
    <span style="color: #000000; font-weight: bold;">return</span> oldPlus.<span style="color: #006600;">invoke</span><span style="color: #669966;">&#40;</span> <span style="color: #aaaadd; font-weight: bold;">Math</span>.<span style="color: #006600;">abs</span><span style="color: #669966;">&#40;</span>delegate<span style="color: #669966;">&#41;</span>, <span style="color: #aaaadd; font-weight: bold;">Math</span>.<span style="color: #006600;">abs</span><span style="color: #669966;">&#40;</span>n<span style="color: #669966;">&#41;</span> <span style="color: #669966;">&#41;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #cc66cc;">4</span> <span style="color: #669966;">==</span> <span style="color: #cc66cc;">2</span> <span style="color: #669966;">+</span> <span style="color: #cc66cc;">2</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #cc66cc;">4</span> <span style="color: #669966;">==</span> <span style="color: #669966;">-</span><span style="color: #cc66cc;">2</span> <span style="color: #669966;">+</span> <span style="color: #669966;">-</span><span style="color: #cc66cc;">2</span></pre></div></div>

<p>If you don&#8217;t save the old method (or completely re-implement the logic for plus), you&#8217;ll end up in an infinite loop and throw a java.lang.StackOverflowError:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #aaaadd; font-weight: bold;">Integer</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">plus</span> <span style="color: #669966;">=</span> <span style="color: #669966;">&#123;</span> <span style="color: #aaaadd; font-weight: bold;">Integer</span> n <span style="color: #669966;">-&gt;</span>
    <span style="color: #000000; font-weight: bold;">return</span> <span style="color: #aaaadd; font-weight: bold;">Math</span>.<span style="color: #006600;">abs</span><span style="color: #669966;">&#40;</span>delegate<span style="color: #669966;">&#41;</span> <span style="color: #669966;">+</span> <span style="color: #aaaadd; font-weight: bold;">Math</span>.<span style="color: #006600;">abs</span><span style="color: #669966;">&#40;</span>n<span style="color: #669966;">&#41;</span>
<span style="color: #669966;">&#125;</span>
&nbsp;
<span style="color: #808080; font-style: italic;">// DOESN'T WORK THROWS java.lang.StackOverflowError</span>
<span style="color: #000000; font-weight: bold;">assert</span> <span style="color: #cc66cc;">4</span> <span style="color: #669966;">==</span> <span style="color: #669966;">-</span><span style="color: #cc66cc;">2</span> <span style="color: #669966;">+</span> <span style="color: #669966;">-</span><span style="color: #cc66cc;">2</span>	<span style="color: #808080; font-style: italic;">// FAILS!!!</span></pre></div></div>

<p>This same kind of thing can be done with AOP, but that often feels more heavy than a little metaClass manipulation.  </p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2009/06/01/groovy-metaclass-overriding-a-method-whilst-using-the-old-implementation/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>What methods does my Groovy/Grails class have?</title>
		<link>http://naleid.com/blog/2008/05/07/what-methods-does-my-groovygrails-class-have/</link>
		<comments>http://naleid.com/blog/2008/05/07/what-methods-does-my-groovygrails-class-have/#comments</comments>
		<pubDate>Wed, 07 May 2008 01:11:05 +0000</pubDate>
		<dc:creator>tednaleid</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[metaprogramming]]></category>
		<category><![CDATA[shortcut]]></category>
		<category><![CDATA[metaclass]]></category>
		<category><![CDATA[method]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://naleid.com/blog/?p=21</guid>
		<description><![CDATA[If you&#8217;ve ever wondered what methods a groovy class has available for you to call, all you need to do is ask the metaClass:

&#34;foo&#34;.metaClass.methods*.name

Result:

&#91;&#34;equals&#34;, &#34;getClass&#34;, &#34;hashCode&#34;, &#34;notify&#34;, &#34;notifyAll&#34;, &#34;toString&#34;, &#34;wait&#34;, &#34;wait&#34;, 
&#34;wait&#34;, &#34;charAt&#34;, &#34;codePointAt&#34;, &#34;codePointBefore&#34;, &#34;codePointCount&#34;, &#34;compareTo&#34;, 
&#34;compareTo&#34;, &#34;compareToIgnoreCase&#34;, &#34;concat&#34;, &#34;contains&#34;, &#34;contentEquals&#34;, 
&#34;contentEquals&#34;, &#34;copyValueOf&#34;, &#34;copyValueOf&#34;, &#34;endsWith&#34;, &#34;equals&#34;, 
&#34;equalsIgnoreCase&#34;, &#34;format&#34;, &#34;format&#34;, &#34;getBytes&#34;, &#34;getBytes&#34;,
 &#34;getBytes&#34;, &#34;getChars&#34;, &#34;hashCode&#34;, [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve ever wondered what methods a groovy class has available for you to call, all you need to do is ask the metaClass:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #aa0000;">&quot;foo&quot;</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">methods</span><span style="color: #669966;">*</span>.<span style="color: #006600;">name</span></pre></div></div>

<p>Result:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;equals&quot;</span>, <span style="color: #aa0000;">&quot;getClass&quot;</span>, <span style="color: #aa0000;">&quot;hashCode&quot;</span>, <span style="color: #aa0000;">&quot;notify&quot;</span>, <span style="color: #aa0000;">&quot;notifyAll&quot;</span>, <span style="color: #aa0000;">&quot;toString&quot;</span>, <span style="color: #aa0000;">&quot;wait&quot;</span>, <span style="color: #aa0000;">&quot;wait&quot;</span>, 
<span style="color: #aa0000;">&quot;wait&quot;</span>, <span style="color: #aa0000;">&quot;charAt&quot;</span>, <span style="color: #aa0000;">&quot;codePointAt&quot;</span>, <span style="color: #aa0000;">&quot;codePointBefore&quot;</span>, <span style="color: #aa0000;">&quot;codePointCount&quot;</span>, <span style="color: #aa0000;">&quot;compareTo&quot;</span>, 
<span style="color: #aa0000;">&quot;compareTo&quot;</span>, <span style="color: #aa0000;">&quot;compareToIgnoreCase&quot;</span>, <span style="color: #aa0000;">&quot;concat&quot;</span>, <span style="color: #aa0000;">&quot;contains&quot;</span>, <span style="color: #aa0000;">&quot;contentEquals&quot;</span>, 
<span style="color: #aa0000;">&quot;contentEquals&quot;</span>, <span style="color: #aa0000;">&quot;copyValueOf&quot;</span>, <span style="color: #aa0000;">&quot;copyValueOf&quot;</span>, <span style="color: #aa0000;">&quot;endsWith&quot;</span>, <span style="color: #aa0000;">&quot;equals&quot;</span>, 
<span style="color: #aa0000;">&quot;equalsIgnoreCase&quot;</span>, <span style="color: #aa0000;">&quot;format&quot;</span>, <span style="color: #aa0000;">&quot;format&quot;</span>, <span style="color: #aa0000;">&quot;getBytes&quot;</span>, <span style="color: #aa0000;">&quot;getBytes&quot;</span>,
 <span style="color: #aa0000;">&quot;getBytes&quot;</span>, <span style="color: #aa0000;">&quot;getChars&quot;</span>, <span style="color: #aa0000;">&quot;hashCode&quot;</span>, <span style="color: #aa0000;">&quot;indexOf&quot;</span>, <span style="color: #aa0000;">&quot;indexOf&quot;</span>, <span style="color: #aa0000;">&quot;indexOf&quot;</span>, 
<span style="color: #aa0000;">&quot;indexOf&quot;</span>, <span style="color: #aa0000;">&quot;intern&quot;</span>, <span style="color: #aa0000;">&quot;lastIndexOf&quot;</span>, <span style="color: #aa0000;">&quot;lastIndexOf&quot;</span>, <span style="color: #aa0000;">&quot;lastIndexOf&quot;</span>, <span style="color: #aa0000;">&quot;lastIndexOf&quot;</span>, 
<span style="color: #aa0000;">&quot;length&quot;</span>, <span style="color: #aa0000;">&quot;matches&quot;</span>, <span style="color: #aa0000;">&quot;offsetByCodePoints&quot;</span>, <span style="color: #aa0000;">&quot;regionMatches&quot;</span>, <span style="color: #aa0000;">&quot;regionMatches&quot;</span>, 
<span style="color: #aa0000;">&quot;replace&quot;</span>, <span style="color: #aa0000;">&quot;replace&quot;</span>, <span style="color: #aa0000;">&quot;replaceAll&quot;</span>, <span style="color: #aa0000;">&quot;replaceFirst&quot;</span>, <span style="color: #aa0000;">&quot;split&quot;</span>, <span style="color: #aa0000;">&quot;split&quot;</span>, <span style="color: #aa0000;">&quot;startsWith&quot;</span>,
 <span style="color: #aa0000;">&quot;startsWith&quot;</span>, <span style="color: #aa0000;">&quot;subSequence&quot;</span>, <span style="color: #aa0000;">&quot;substring&quot;</span>, <span style="color: #aa0000;">&quot;substring&quot;</span>, <span style="color: #aa0000;">&quot;toCharArray&quot;</span>, 
<span style="color: #aa0000;">&quot;toLowerCase&quot;</span>, <span style="color: #aa0000;">&quot;toLowerCase&quot;</span>, <span style="color: #aa0000;">&quot;toString&quot;</span>, <span style="color: #aa0000;">&quot;toUpperCase&quot;</span>, <span style="color: #aa0000;">&quot;toUpperCase&quot;</span>, 
<span style="color: #aa0000;">&quot;trim&quot;</span>, <span style="color: #aa0000;">&quot;valueOf&quot;</span>, <span style="color: #aa0000;">&quot;valueOf&quot;</span>, <span style="color: #aa0000;">&quot;valueOf&quot;</span>, <span style="color: #aa0000;">&quot;valueOf&quot;</span>, <span style="color: #aa0000;">&quot;valueOf&quot;</span>, <span style="color: #aa0000;">&quot;valueOf&quot;</span>, 
<span style="color: #aa0000;">&quot;valueOf&quot;</span>, <span style="color: #aa0000;">&quot;valueOf&quot;</span>, <span style="color: #aa0000;">&quot;valueOf&quot;</span><span style="color: #669966;">&#93;</span></pre></div></div>

<p>There&#8217;s a lot of duplication in there, and the order is random, so I&#8217;ll often fix that like this:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #aa0000;">&quot;foo&quot;</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">methods</span><span style="color: #669966;">*</span>.<span style="color: #006600;">name</span>.<span style="color: #663399;">sort</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">unique</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>Result:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;charAt&quot;</span>, <span style="color: #aa0000;">&quot;codePointAt&quot;</span>, <span style="color: #aa0000;">&quot;codePointBefore&quot;</span>, <span style="color: #aa0000;">&quot;codePointCount&quot;</span>, <span style="color: #aa0000;">&quot;compareTo&quot;</span>,
 <span style="color: #aa0000;">&quot;compareToIgnoreCase&quot;</span>, <span style="color: #aa0000;">&quot;concat&quot;</span>, <span style="color: #aa0000;">&quot;contains&quot;</span>, <span style="color: #aa0000;">&quot;contentEquals&quot;</span>, <span style="color: #aa0000;">&quot;copyValueOf&quot;</span>, 
<span style="color: #aa0000;">&quot;endsWith&quot;</span>, <span style="color: #aa0000;">&quot;equals&quot;</span>, <span style="color: #aa0000;">&quot;equalsIgnoreCase&quot;</span>, <span style="color: #aa0000;">&quot;format&quot;</span>, <span style="color: #aa0000;">&quot;getBytes&quot;</span>, <span style="color: #aa0000;">&quot;getChars&quot;</span>,
 <span style="color: #aa0000;">&quot;getClass&quot;</span>, <span style="color: #aa0000;">&quot;hashCode&quot;</span>, <span style="color: #aa0000;">&quot;indexOf&quot;</span>, <span style="color: #aa0000;">&quot;intern&quot;</span>, <span style="color: #aa0000;">&quot;lastIndexOf&quot;</span>, <span style="color: #aa0000;">&quot;length&quot;</span>, <span style="color: #aa0000;">&quot;matches&quot;</span>, 
<span style="color: #aa0000;">&quot;notify&quot;</span>, <span style="color: #aa0000;">&quot;notifyAll&quot;</span>, <span style="color: #aa0000;">&quot;offsetByCodePoints&quot;</span>, <span style="color: #aa0000;">&quot;regionMatches&quot;</span>, <span style="color: #aa0000;">&quot;replace&quot;</span>, <span style="color: #aa0000;">&quot;replaceAll&quot;</span>,
 <span style="color: #aa0000;">&quot;replaceFirst&quot;</span>, <span style="color: #aa0000;">&quot;split&quot;</span>, <span style="color: #aa0000;">&quot;startsWith&quot;</span>, <span style="color: #aa0000;">&quot;subSequence&quot;</span>, <span style="color: #aa0000;">&quot;substring&quot;</span>, <span style="color: #aa0000;">&quot;toCharArray&quot;</span>, 
<span style="color: #aa0000;">&quot;toLowerCase&quot;</span>, <span style="color: #aa0000;">&quot;toString&quot;</span>, <span style="color: #aa0000;">&quot;toUpperCase&quot;</span>, <span style="color: #aa0000;">&quot;trim&quot;</span>, <span style="color: #aa0000;">&quot;valueOf&quot;</span>, <span style="color: #aa0000;">&quot;wait&quot;</span><span style="color: #669966;">&#93;</span></pre></div></div>

<p><span id="more-21"></span><br />
If you haven&#8217;t seen that &#8220;*&#8221; in <code>metaClass.methods*.name</code>, that&#8217;s known as the <a href="http://groovy.codehaus.org/Operators#Operators-SpreadOperator%28.%29" onclick="pageTracker._trackPageview('/outgoing/groovy.codehaus.org/Operators_Operators-SpreadOperator_28._29?referer=');">Spread Operator</a> and it&#8217;s essentially the same thing as saying</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #aa0000;">&quot;foo&quot;</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">methods</span>.<span style="color: #663399;">collect</span> <span style="color: #669966;">&#123;</span> method <span style="color: #669966;">-&gt;</span> method.<span style="color: #006600;">name</span> <span style="color: #669966;">&#125;</span>.<span style="color: #663399;">sort</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">unique</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>If you&#8217;re using Grails and want to know what methods are on your Author class, looking at the groovy class file will give you a clue if you know the patterns, but it can be easy to forget what the exact convention is:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Author <span style="color: #669966;">&#123;</span>
	<span style="color: #aaaadd; font-weight: bold;">String</span> name
	<span style="color: #000000; font-weight: bold;">def</span> hasMany <span style="color: #669966;">=</span> <span style="color: #669966;">&#91;</span>books: <span style="color: #aaaadd; font-weight: bold;">Book</span><span style="color: #669966;">&#93;</span>
<span style="color: #669966;">&#125;</span></pre></div></div>

<p>Just start up a <code>grails console</code> and ask an Author what it can do:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #663366;">println</span> <span style="color: #000000; font-weight: bold;">new</span> Author<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">methods</span><span style="color: #669966;">*</span>.<span style="color: #006600;">name</span>.<span style="color: #663399;">sort</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">unique</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>This will result in:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;$static_methodMissing&quot;</span>, <span style="color: #aa0000;">&quot;&lt;init&gt;&quot;</span>, <span style="color: #aa0000;">&quot;asType&quot;</span>, <span style="color: #aa0000;">&quot;clearErrors&quot;</span>, <span style="color: #aa0000;">&quot;create&quot;</span>, 
<span style="color: #aa0000;">&quot;decodeBase64&quot;</span>, <span style="color: #aa0000;">&quot;decodeHTML&quot;</span>, <span style="color: #aa0000;">&quot;decodeJSON&quot;</span>, <span style="color: #aa0000;">&quot;decodeJavaScript&quot;</span>,
<span style="color: #aa0000;">&quot;decodeURL&quot;</span>, <span style="color: #aa0000;">&quot;decodeXML&quot;</span>, <span style="color: #aa0000;">&quot;encodeAsBase64&quot;</span>, <span style="color: #aa0000;">&quot;encodeAsHTML&quot;</span>,
 <span style="color: #aa0000;">&quot;encodeAsJSON&quot;</span>, <span style="color: #aa0000;">&quot;encodeAsJavaScript&quot;</span>, <span style="color: #aa0000;">&quot;encodeAsURL&quot;</span>, <span style="color: #aa0000;">&quot;encodeAsXML&quot;</span>, 
<span style="color: #aa0000;">&quot;equals&quot;</span>, <span style="color: #aa0000;">&quot;findAll&quot;</span>, <span style="color: #aa0000;">&quot;getBooks&quot;</span>, <span style="color: #aa0000;">&quot;getClass&quot;</span>, <span style="color: #aa0000;">&quot;getConstraints&quot;</span>, <span style="color: #aa0000;">&quot;getErrors&quot;</span>, 
<span style="color: #aa0000;">&quot;getHasMany&quot;</span>, <span style="color: #aa0000;">&quot;getId&quot;</span>, <span style="color: #aa0000;">&quot;getLog&quot;</span>, <span style="color: #aa0000;">&quot;getMetaClass&quot;</span>, <span style="color: #aa0000;">&quot;getName&quot;</span>, <span style="color: #aa0000;">&quot;getProperties&quot;</span>, 
<span style="color: #aa0000;">&quot;getProperty&quot;</span>, <span style="color: #aa0000;">&quot;getVersion&quot;</span>, <span style="color: #aa0000;">&quot;hasErrors&quot;</span>, <span style="color: #aa0000;">&quot;hashCode&quot;</span>, <span style="color: #aa0000;">&quot;ident&quot;</span>, <span style="color: #aa0000;">&quot;invokeMethod&quot;</span>, 
<span style="color: #aa0000;">&quot;methodMissing&quot;</span>, <span style="color: #aa0000;">&quot;notify&quot;</span>, <span style="color: #aa0000;">&quot;notifyAll&quot;</span>, <span style="color: #aa0000;">&quot;setBooks&quot;</span>, <span style="color: #aa0000;">&quot;setErrors&quot;</span>, <span style="color: #aa0000;">&quot;setHasMany&quot;</span>,
<span style="color: #aa0000;">&quot;setId&quot;</span>, <span style="color: #aa0000;">&quot;setMetaClass&quot;</span>, <span style="color: #aa0000;">&quot;setName&quot;</span>, <span style="color: #aa0000;">&quot;setProperties&quot;</span>, <span style="color: #aa0000;">&quot;setProperty&quot;</span>, 
<span style="color: #aa0000;">&quot;setVersion&quot;</span>, <span style="color: #aa0000;">&quot;toString&quot;</span>, <span style="color: #aa0000;">&quot;validate&quot;</span>, <span style="color: #aa0000;">&quot;wait&quot;</span><span style="color: #669966;">&#93;</span></pre></div></div>

<p>In there, you can see the methods that were decorated on the Author object by grails including <code>encodeAs</code> and <code>decode</code> as well as getters and setters for explicit and implicit variables.   One limitation of this method is that some methods are only added by grails dynamically once the method is executed.  Notice how there isn&#8217;t an <code>addToBooks</code> method in the list?  That&#8217;s because the method really isn&#8217;t there right now.  It gets added by grails as part of a methodMissing call.  We can force grails to decorate our class by calling one of the dynamic methods (like <code>count()</code>):</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">def</span> a <span style="color: #669966;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Author<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
<span style="color: #000000; font-weight: bold;">def</span> origMethods <span style="color: #669966;">=</span> a.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">methods</span><span style="color: #669966;">*</span>.<span style="color: #006600;">name</span>.<span style="color: #663399;">sort</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">unique</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
<span style="color: #808080; font-style: italic;">// call one of the dynamic methods so grails fully decorates the metaClass</span>
a.<span style="color: #663399;">count</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span> 
<span style="color: #000000; font-weight: bold;">def</span> newMethods <span style="color: #669966;">=</span> a.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">methods</span><span style="color: #669966;">*</span>.<span style="color: #006600;">name</span>.<span style="color: #663399;">sort</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">unique</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>
<span style="color: #663366;">println</span> newMethods <span style="color: #669966;">-</span> origMethods  <span style="color: #808080; font-style: italic;">// what methods got added?</span></pre></div></div>

<p>Subtracting the original methods from newly decorated method list will give you this set of dynamic methods that grails adds when you ask for a dynamic method.</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;addToBooks&quot;</span>, <span style="color: #aa0000;">&quot;count&quot;</span>, <span style="color: #aa0000;">&quot;createCriteria&quot;</span>, <span style="color: #aa0000;">&quot;delete&quot;</span>, <span style="color: #aa0000;">&quot;discard&quot;</span>, <span style="color: #aa0000;">&quot;executeQuery&quot;</span>, 
<span style="color: #aa0000;">&quot;executeUpdate&quot;</span>, <span style="color: #aa0000;">&quot;exists&quot;</span>, <span style="color: #aa0000;">&quot;find&quot;</span>, <span style="color: #aa0000;">&quot;findAllWhere&quot;</span>, <span style="color: #aa0000;">&quot;findWhere&quot;</span>, <span style="color: #aa0000;">&quot;get&quot;</span>, <span style="color: #aa0000;">&quot;getAll&quot;</span>, 
<span style="color: #aa0000;">&quot;list&quot;</span>, <span style="color: #aa0000;">&quot;lock&quot;</span>, <span style="color: #aa0000;">&quot;merge&quot;</span>, <span style="color: #aa0000;">&quot;refresh&quot;</span>, <span style="color: #aa0000;">&quot;removeFromBooks&quot;</span>, <span style="color: #aa0000;">&quot;save&quot;</span>, <span style="color: #aa0000;">&quot;withCriteria&quot;</span>,
 <span style="color: #aa0000;">&quot;withTransaction&quot;</span><span style="color: #669966;">&#93;</span></pre></div></div>

<p>If you see a method that you want to use, but can&#8217;t remember the signature, again, all you have to do is ask:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #663366;">println</span> <span style="color: #000000; font-weight: bold;">new</span> Author<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">methods</span>.<span style="color: #663399;">findAll</span> <span style="color: #669966;">&#123;</span>it.<span style="color: #006600;">name</span> <span style="color: #669966;">==</span> <span style="color: #aa0000;">&quot;withCriteria&quot;</span><span style="color: #669966;">&#125;</span><span style="color: #669966;">*</span>.<span style="color: #006600;">parameterTypes</span></pre></div></div>

<p>Result showing the 2 method signatures for <code>withCriteria</code>:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&#91;</span><span style="color: #669966;">&#91;</span><span style="color: #000000; font-weight: bold;">interface</span> java.<span style="color: #006600;">util</span>.<span style="color: #aaaadd; font-weight: bold;">Map</span>, <span style="color: #000000; font-weight: bold;">class</span> groovy.<span style="color: #006600;">lang</span>.<span style="color: #006600;">Closure</span><span style="color: #669966;">&#93;</span>, <span style="color: #669966;">&#91;</span><span style="color: #000000; font-weight: bold;">class</span> groovy.<span style="color: #006600;">lang</span>.<span style="color: #006600;">Closure</span><span style="color: #669966;">&#93;</span><span style="color: #669966;">&#93;</span></pre></div></div>

<p>There is also a <code>properties</code> method on the metaClass that you can query in a similar manner:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #663366;">println</span> <span style="color: #000000; font-weight: bold;">new</span> Author<span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">metaClass</span>.<span style="color: #006600;">properties</span><span style="color: #669966;">*</span>.<span style="color: #006600;">name</span>.<span style="color: #663399;">sort</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span>.<span style="color: #006600;">unique</span><span style="color: #669966;">&#40;</span><span style="color: #669966;">&#41;</span></pre></div></div>

<p>Result:</p>

<div class="wp_syntax"><div class="code"><pre class="groovy" style="font-family:monospace;"><span style="color: #669966;">&#91;</span><span style="color: #aa0000;">&quot;books&quot;</span>, <span style="color: #aa0000;">&quot;class&quot;</span>, <span style="color: #aa0000;">&quot;constraints&quot;</span>, <span style="color: #aa0000;">&quot;errors&quot;</span>, <span style="color: #aa0000;">&quot;hasMany&quot;</span>, <span style="color: #aa0000;">&quot;id&quot;</span>, <span style="color: #aa0000;">&quot;log&quot;</span>, <span style="color: #aa0000;">&quot;metaClass&quot;</span>, 
<span style="color: #aa0000;">&quot;name&quot;</span>, <span style="color: #aa0000;">&quot;properties&quot;</span>, <span style="color: #aa0000;">&quot;version&quot;</span><span style="color: #669966;">&#93;</span></pre></div></div>

<p>Knowing about the information that the metaClass puts at your fingertips makes it much easier to poke around in the grails console, or with a simple script.  You can learn a lot of hidden features about a class if you just know how to ask.</p>
]]></content:encoded>
			<wfw:commentRss>http://naleid.com/blog/2008/05/07/what-methods-does-my-groovygrails-class-have/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
