<?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>El blog de Deigote</title>
	<atom:link href="http://blog.deigote.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.deigote.com</link>
	<description>El mundo de Deigote. Un diario de cualquier cosa que me resulte interesante (si a alguien más se lo resulta, es otro cantar). Espero que os guste o disguste. Incluso que os deje indiferentes sería una opción tan buena como cualquier otra.</description>
	<lastBuildDate>Mon, 29 Apr 2013 16:19:19 +0000</lastBuildDate>
	<language>es-ES</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Grails &#8211; small and simple method to convert objects to JSON</title>
		<link>http://blog.deigote.com/2013/01/12/grails-small-and-simple-method-to-convert-objects-to-json/</link>
		<comments>http://blog.deigote.com/2013/01/12/grails-small-and-simple-method-to-convert-objects-to-json/#comments</comments>
		<pubDate>Sat, 12 Jan 2013 09:03:14 +0000</pubDate>
		<dc:creator>Deigote</dc:creator>
				<category><![CDATA[Informática, internet y tecnología]]></category>
		<category><![CDATA[convert]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[method]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[simple]]></category>

		<guid isPermaLink="false">http://blog.deigote.com/?p=752</guid>
		<description><![CDATA[I was playing around with Grails and JSON and came up with a small method to convert a given collection of objects into JSON (typically, domain class objects, but it would work with anything). It&#8217;s nothing new or fancy, but maybe usefull for anybody who is starting to explore Grails [...]]]></description>
				<content:encoded><![CDATA[<p>I was playing around with Grails and JSON and came up with a small method to convert a given collection of objects into JSON (typically, domain class objects, but it would work with anything). It&#8217;s nothing new or fancy, but maybe usefull for anybody who is starting to explore Grails JSON capabilities. For the sake of the example, I&#8217;ll put the method in a JSONUtils class:</p>
<pre class="brush:groovy">
import grails.converters.JSON
class JSONUtils {
	protected static buildJSON(objectsToBuild, properties) {
		objectsToBuild.inject([], {
			objects, object -> objects << (properties.inject([:], {
				objectMap, property -> objectMap << [(property): object[property]]
			}))
		}) as JSON
	}
}
</pre>
<p>You could use it in a controller as following:</p>
<pre class="brush:groovy">
import static JSONUtils.buildJSON
class PersonController {
	def personService	
	static personJSONProperties = [ 'name', 'gender', 'age']

	def peopleByAge(Integer age) {
		buildJSON(personService.findByAge(age), personJSONProperties)
	}
}
</pre>
<p>I'm thinking that this could be a small but usefull AST transformation...</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.deigote.com/2013/01/12/grails-small-and-simple-method-to-convert-objects-to-json/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Bash &#8211; find directories of certain sizes</title>
		<link>http://blog.deigote.com/2013/01/11/bash-find-directories-of-certain-sizes/</link>
		<comments>http://blog.deigote.com/2013/01/11/bash-find-directories-of-certain-sizes/#comments</comments>
		<pubDate>Fri, 11 Jan 2013 12:49:15 +0000</pubDate>
		<dc:creator>Deigote</dc:creator>
				<category><![CDATA[Informática, internet y tecnología]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[command]]></category>
		<category><![CDATA[command line]]></category>
		<category><![CDATA[du]]></category>
		<category><![CDATA[filter]]></category>
		<category><![CDATA[find]]></category>
		<category><![CDATA[grep]]></category>
		<category><![CDATA[regular expressions]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[sh]]></category>
		<category><![CDATA[size]]></category>
		<category><![CDATA[sysadmin]]></category>

		<guid isPermaLink="false">http://blog.deigote.com/?p=747</guid>
		<description><![CDATA[I often find myself trying to know which directories are consuming most of my persistent memory (I would say hard disk, but it isn&#8217;t a disk &#8211; and probably, even hard &#8211; anymore), and always get disappointed with myself for not being able to remember the way to do it [...]]]></description>
				<content:encoded><![CDATA[<p>I often find myself trying to know which directories are consuming most of my persistent memory (I would say hard disk, but it isn&#8217;t a disk &#8211; and probably, even hard &#8211; anymore), and always get disappointed with myself for not being able to remember the way to do it in the terminal <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':)' class='wp-smiley smiley-19' /> . If you are dealing with files, you can use the allmighty find command with the size filter, for example:</p>
<pre class="brush:bash">find . -type f -size +100M</pre>
<p>But that won&#8217;t work with directories. After all, I guess they don&#8217;t take much spaces themselves &#8211; the files contained by them are the ones that does <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-)' class='wp-smiley smiley-19' /> . So what I usually end up doing is finding directories with a certain depth, and then calculate their sizes and filter with grep. This would be an example:</p>
<pre class="brush:bash">find $HOME -type d -mindepth 1 -maxdepth 3 -exec du -hs {} \; | grep -E "[0-9]{1}(\.[0-9]{1,2})?G" | sort -n</pre>
<p>This would list the directories contained in the user&#8217;s home, recursing til a max depth of 3 levels, and them calculate all their sizes. After that, it would filter by the sizes whose size is 1 gigabyte or more. Last, the sizes are sorted with a numeric criteria. You can change the last letter to filter by megabytes (M), and the count of the first regular expression so it takes only numbers of a given lenght. For example, to get sizes in the range [100M-1G), you would use the following regular expression: "[0-9]{3}(\.[0-9]{1,2})?M&#8221;. And to find directories with a size of at least 10 gigabytes, you would use: &#8220;[0-9]{2}(\.[0-9]{1,2})?G&#8221;. You can also change the mindepth and maxdepth params in order to filter how deep you want the recursion. And if you don&#8217;t provide a maxdepth param and set the base directory as /, the whole filesystem will be analized :). </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.deigote.com/2013/01/11/bash-find-directories-of-certain-sizes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails &#8211; generic methods for equals and hashCode calculation</title>
		<link>http://blog.deigote.com/2012/12/27/grails-generic-methods-for-equals-and-hashcode-calculation/</link>
		<comments>http://blog.deigote.com/2012/12/27/grails-generic-methods-for-equals-and-hashcode-calculation/#comments</comments>
		<pubDate>Thu, 27 Dec 2012 21:11:38 +0000</pubDate>
		<dc:creator>Deigote</dc:creator>
				<category><![CDATA[Informática, internet y tecnología]]></category>
		<category><![CDATA[equals]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[hashcode]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.deigote.com/?p=725</guid>
		<description><![CDATA[In modern versions of Grails, you can use the Groovy annotation EqualsAndHashCode for generating the equals and hashCode methods of your domain classes using an AST transformation, but if you are in any 1.x.x Grails version (that uses a Groovy version prior to 1.8.0), you won&#8217;t be able to use [...]]]></description>
				<content:encoded><![CDATA[<p>In modern versions of Grails, you can use the Groovy annotation <a href="http://groovy.codehaus.org/api/index.html?groovy/transform/EqualsAndHashCode.html">EqualsAndHashCode</a> for generating the <em>equals</em> and <em>hashCode</em> methods of your domain classes using an AST transformation, but if you are in any 1.x.x Grails version (that uses a Groovy version prior to 1.8.0), you won&#8217;t be able to use this.</p>
<p>I&#8217;ve seen tons of duplicated code (Tolkien fans <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> would refer to it as &#8220;The Programmers Bane&#8221;) in the projects I&#8217;ve worked for <em>hashCode</em> and <em>equals</em> methods, even in the ones that use the Apache Commons helpers (<a href="http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/builder/EqualsBuilder.html">EqualsBuilder</a> and <a href="http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/builder/HashCodeBuilder.html">HashCodeBuilder</a>), so I decided to post a pair of methods that I usually use to work out this problem:</p>
<pre class="brush:groovy">
import org.apache.commons.lang.builder.EqualsBuilder
import org.apache.commons.lang.builder.HashCodeBuilder
class DomainClassUtils {
	...
	static boolean equals(Object one, Object another) {
		one != null &#038;&#038; another != null &#038;&#038; 
		((obj.respondsTo('instanceOf') &#038;&#038; obj.instanceOf(this.getClass())) || 
		 this.getClass().isInstance(obj)) &#038;&#038; 
		(one.is(another) || 
		 one.getClass().equalsProperties.inject(new EqualsBuilder()) {
			builder, property ->
			builder.append(one[property], another[property])
		}.isEquals())
	}
	
	static int hashCode(Object one) {
		one.getClass().equalsProperties.inject(new HashCodeBuilder()) {
			builder, property ->
			builder.append(this[property])
		}.toHashCode()
	}
}
</pre>
<p>This methods will calculate equals and hashcode for domain class objects (note the use of the <a href="http://grails.org/doc/latest/ref/Domain%20Classes/instanceOf.html">instanceOf </a> method if available) that declares a static property named <em>equalsProperties</em>. For example:</p>
<pre class="brush:groovy">
import DomainClassUtils

class SomeDomainClass {
	Integer someProperty
	String anotherProperty
	AnotherDomainClass andAnotherProperty

	static equalsProperties = ['someProperty', 'andAnotherProperty']

	boolean equals(Object obj) {
		DomainClassUtils.equals(this, obj)
	}

	int hashCode() {
		DomainClassUtils.hashCode(this)
	}
}
</pre>
<p>This still involves duplicating the DomainClassUtils method invokations code, but this can be easily avoided injecting the methods using your prefered mechanism (in increasing order of preference, I could list the following ones: inheritance, composition, metaprogramming, category/mixin transformation, your custom AST transformation).</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.deigote.com/2012/12/27/grails-generic-methods-for-equals-and-hashcode-calculation/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Bash &#8211; How to dynamically evaluate and set a variable</title>
		<link>http://blog.deigote.com/2012/12/19/bash-how-to-dynamically-evaluate-and-set-a-variable/</link>
		<comments>http://blog.deigote.com/2012/12/19/bash-how-to-dynamically-evaluate-and-set-a-variable/#comments</comments>
		<pubDate>Wed, 19 Dec 2012 14:54:51 +0000</pubDate>
		<dc:creator>Deigote</dc:creator>
				<category><![CDATA[Informática, internet y tecnología]]></category>
		<category><![CDATA[bash]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[indirect reference]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[shell]]></category>
		<category><![CDATA[terminal]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[variables]]></category>

		<guid isPermaLink="false">http://blog.deigote.com/?p=719</guid>
		<description><![CDATA[One of the things that opens the gate to truly code reusation in Bash is, in my opinion, the hability of evaluate and set variables in a dynamic way. By dynamic, I mean that the variable name is constructed dynamically, or passed as a parameter, and ends up being in [...]]]></description>
				<content:encoded><![CDATA[<p>One of the things that opens the gate to truly code reusation in Bash is, in my opinion, the hability of evaluate and set variables in a dynamic way. By dynamic, I mean that the variable name is constructed dynamically, or passed as a parameter, and ends up being in another variable (for example, a variable local to a function). In fact, this is usually called <em>indirect reference</em> in Bash documentation.</p>
<h4>Assigning a variable value</h4>
<p>I usually have in my <em>functions.sh</em> file something like the following:</p>
<pre class="brush:bash">
[22:57] $ cat functions.sh 
function execute_and_log {
	echo "Executing '$1' ..."
	export ${2}="$(eval $1)"
}
[22:57] ~ $ source functions.sh 
[22:57] ~ $ execute_and_log "ls /usr" LS_RESULT 
[22:57] ~ $ echo $LS_RESULT
Executing 'ls /usr' ...
X11/ X11R6@ bin/ include/ lib/ libexec/ llvm-gcc-4.2/ local/ sbin/ share/ standalone/ texbin@
</pre>
<p>As you can see, I pass the variable name where I want to store my result as a parameter to the function. The trick is to wrap the variable that contains the variable name with braces. Note that if you don&#8217;t use export (that in most cases is not needed), it won&#8217;t work, I&#8217;m not sure why. Another possibility is to use the allmighty eval, which gives you an unglier sintax, but allows you to avoid the export:</p>
<pre class="brush:bash">
[22:59] $ cat functions.sh 
function execute_and_log {
	echo "Executing '$1' ..."
	eval "$2=\"$(eval $1)\""
}
[22:59] ~ $ source functions.sh 
[22:59] ~ $ execute_and_log "ls /usr" LS_RESULT 
[22:57] ~ $ echo $LS_RESULT
Executing 'ls /usr' ...
X11/ X11R6@ bin/ include/ lib/ libexec/ llvm-gcc-4.2/ local/ sbin/ share/ standalone/ texbin@
</pre>
<h4>Evaluating a variable value</h4>
<p>Imagine that in the previous example you don&#8217;t want to log only the command to execute, but also the result. You then need to evaluate the value of a variable whose name is contained in another variable (the function second param in this case). In this case, I only know how to do it using eval, which would give you the following:</p>
<pre class="brush:bash">
[11:11] ~ $ cat functions.sh 
function execute_and_log {
	echo "Executing '$1' ..."
	eval "$2=\"$(eval $1)\""
	eval echo "Result is \$$2"
}
[11:11] ~ $ source functions.sh ; execute_and_log "ls /usr" LS_RESULT 
Executing 'ls /usr' ...
Result is X11/ X11R6@ bin/ include/ lib/ libexec/ llvm-gcc-4.2/ local/ sbin/ share/ standalone/ texbin@
</pre>
<p>As you can see, we can use eval both to assign and evaluate, in this second case just by escaping the dollar sign. Really powerful <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':)' class='wp-smiley smiley-19' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.deigote.com/2012/12/19/bash-how-to-dynamically-evaluate-and-set-a-variable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Temacos traducidos: Pearl Jam &#8211; Gone</title>
		<link>http://blog.deigote.com/2012/11/30/temacos-traducidos-pearl-jam-gone/</link>
		<comments>http://blog.deigote.com/2012/11/30/temacos-traducidos-pearl-jam-gone/#comments</comments>
		<pubDate>Fri, 30 Nov 2012 08:25:48 +0000</pubDate>
		<dc:creator>Deigote</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[gone]]></category>
		<category><![CDATA[grunge]]></category>
		<category><![CDATA[letra]]></category>
		<category><![CDATA[Música]]></category>
		<category><![CDATA[pearl jam]]></category>
		<category><![CDATA[rock]]></category>
		<category><![CDATA[traducción]]></category>

		<guid isPermaLink="false">http://blog.deigote.com/?p=711</guid>
		<description><![CDATA[Nunca he sido seguidor de Pearl Jam, la verdad. Es de esos grupos que cuando alguien me lo recomendó, ya tenían una carrera consumada, y nunca sabía por qué album empezar. Los intentos que he hecho nunca habían terminado siendo fructíferos, y lo había dejado correr hasta que mi hermano, [...]]]></description>
				<content:encoded><![CDATA[<p>Nunca he sido seguidor de <a href="http://en.wikipedia.org/wiki/Pearl_Jam">Pearl Jam</a>, la verdad. Es de esos grupos que cuando alguien me lo recomendó, ya tenían una carrera consumada, y nunca sabía por qué album empezar. Los intentos que he hecho nunca habían terminado siendo fructíferos, y lo había dejado correr hasta que mi hermano, quien si no <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-)' class='wp-smiley smiley-19' /> (que por cierto es bajista de los archifantásticos <a href="http://www.lesvivo.com/" title="Les Vivo">Les Vivo</a>, como siempre aprovecho para recordar <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=')' class='wp-smiley smiley-22' /> me recomendó su disco sin título (o titulado como la propia banda, <a href="http://en.wikipedia.org/wiki/Pearl_Jam_%28album%29">Pearl Jam</a>), también conocido como &#8220;el del aguacate&#8221; por motivos obvios para cualquiera que vea la portada <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-)' class='wp-smiley smiley-19' /> . </p>
<p>Todo el album me parece buenísimo, pero la canción que consiguió que me enganchase a él de primeras fue <a href="http://en.wikipedia.org/wiki/Gone_%28Pearl_Jam_song%29">Gone</a>, un pedazo de tema que me tuvo obsesionado unos días, como siempre me pasa, y cuya letra me parece espectacular. Aquí os dejo la versión de estudio del mismo, aunque una vez que la tengáis escuchada, merece la pena darle una orejada a la <a href="http://www.youtube.com/watch?v=2WoEpTnDsK8">fantástica versión que hicieron para AOL</a> con <a href="http://en.wikipedia.org/wiki/Eddie_Vedder">Eddie Vedder</a> a guitarra y voz.</p>
<p><iframe width="560" height="315" src="http://www.youtube.com/embed/ASev80YOng4" frameborder="0" allowfullscreen></iframe></p>
<p>A continuación la letra original y mi traducción, que como siempre tendrá errores varios cuyas correcciones serán más que bienvenidas <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-)' class='wp-smiley smiley-19' /> : </p>
<table class="song">
<thead>
<tr>
<th>Original</th>
<th>Traducción</th>
</tr>
</thead>
<tbody>
<tr>
<td>No more upset mornings<br />
No more trying evenings<br />
This American Dream I am disbelieving<br />
When the gas in my tank feels like money in the bank<br />
Gonna blow it all this time, take me one last ride<br />
For the lights of this city, they only look good when I&#8217;m speeding<br />
I wanna leave em all behind me cause this time I&#8217;m gone<br />
Long gone,<br />
This time I&#8217;m letting go of it all<br />
So long,<br />
This time I&#8217;m gone</p>
<p>In the far off distance<br />
As my taillights fade<br />
No one thinks to witness but they will someday<br />
Feel like a question is forming<br />
And the answer&#8217;s far<br />
I will be what I could be<br />
Once I get out of this town</p>
<p>For the lights of this city<br />
They have lost all feeling<br />
Gonna leave em all behind me cause this time I&#8217;m gone<br />
Long gone,<br />
This time I&#8217;m letting go of it all<br />
So long,<br />
Long gone, I&#8217;m letting go of it all<br />
Yeah, This time I&#8217;m gone</p>
<p>If nothing is everything<br />
If nothing is everything I&#8217;ll have it all<br />
If nothing is everything then I will have it all
</td>
<td>
No más mañanas disgustado,<br />
No más tardes duras,<br />
Estoy descreido de este sueño americano<br />
Cuando sienta la gasolina de mi depósito como dinero en el banco<br />
Voy a echarlo todo a perder esta vez, a hacer mi último viaje<br />
Porque las luces de esta ciudad sólo me gustan cuando voy rápido<br />
Quiero dejarlas todas atrás porque esta vez me voy<br />
Me voy lejos<br />
Esta vez voy a dejarlo todo<br />
Tanto tiempo,<br />
esta vez me voy.</p>
<p>En la lejana distancia<br />
Mientras mis luces traseras se desvanecen<br />
Nadie piensa en ser testigo, pero lo harán algún día,<br />
Siento que una pregunta toma forma<br />
Y que la respuesta está lejos<br />
Seré lo que podría ser<br />
una vez deje esta ciudad.</p>
<p>Porque las luces de esta ciudad<br />
Han perdido todo su significado,<br />
Quiero dejarlas todas atrás porque esta vez me voy<br />
Me voy lejos<br />
Esta vez voy a dejarlo todo<br />
Tanto tiempo,<br />
esta vez me voy.</p>
<p>Si nada lo es todo,<br />
Si nada lo es todo, lo tendré todo<br />
Si nada lo es todo, entonces lo tendré todo
</td>
</tr>
</tbody>
</table>
<p>Me quedo con los últimos versos. Si nada lo es todo, siempre se puede volver a empezar <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-)' class='wp-smiley smiley-19' /> .</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.deigote.com/2012/11/30/temacos-traducidos-pearl-jam-gone/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Groovy: using parameters with default values to separate method configuration from method body</title>
		<link>http://blog.deigote.com/2012/11/23/groovy-using-parameters-with-default-values-to-separate-method-configuration-from-method-body/</link>
		<comments>http://blog.deigote.com/2012/11/23/groovy-using-parameters-with-default-values-to-separate-method-configuration-from-method-body/#comments</comments>
		<pubDate>Fri, 23 Nov 2012 08:37:00 +0000</pubDate>
		<dc:creator>Deigote</dc:creator>
				<category><![CDATA[Informática, internet y tecnología]]></category>
		<category><![CDATA[default values]]></category>
		<category><![CDATA[extract]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[method]]></category>
		<category><![CDATA[parameters]]></category>
		<category><![CDATA[programación]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[tricks]]></category>

		<guid isPermaLink="false">http://blog.deigote.com/?p=702</guid>
		<description><![CDATA[And with that huge title , I want to talk about a little technique that I like to use in Groovy by taking advantage of the method parameters with default values feature. By method configuration and method body I am refering to two typical parts of a business logic method [...]]]></description>
				<content:encoded><![CDATA[<p>And with that huge title <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> , I want to talk about a little technique that I like to use in Groovy by taking advantage of the <a href="http://groovy.codehaus.org/Extended+Guide+to+Method+Signatures#ExtendedGuidetoMethodSignatures-ArgumentswithDefaultValues"><em>method parameters with default values</em></a> feature. By <em>method configuration</em> and <em>method body</em> I am refering to two typical parts of a business logic method (for example, a method of a Grails service) that you have probably seen a lot. Imagine a method like the following:</p>
<pre class="brush:groovy">
def updateContractAddress(contract, newAddress) 
{
   // Method configuration
   def client = contract.client
   def country =  CountryService.findByPostalCode(newAddress.postalCode)
   def currentAddress = client.address

   // Method body
   client.previousAddresses << currentAddress
   client.address = new Address
   client.save()
}
</pre>
<p>As you can see, the method has two different parts:</p>
<ul>
<li>In the first one, we just configure some variables that we will use in order to clean up our code, or may to not calling the same method twice (as would happen, for example, with the implicit method Contract.getClient(), that would be called three times in the variable client was inlined).</li>
<li>In the second one, the actual method business logic is performed.</li>
</ul>
<p>This is actually the method implementation, the previous stuff is just boiler plate code. In fact, in Java I have seen a lot the pattern of separating the previous code in multiple methods, in order to separate this two parts:</p>
<pre class="brush:groovy">
def updateContractAddress(contract, newAddress) 
{
   def client = contract.client
   def country =  CountryService.findByPostalCode(newAddress.postalCode)
   def currentAddress = client.address
   updateContractAddress(contract, newAddress, client, country, currentAddress)
}

private updateContractAddress(contract, newAddress, client, country, currentAddress) 
{
   client.previousAddresses << currentAddress
   client.address = new Address
   client.save()
}
</pre>
<p>Not bad. As I always say when joking, almost every life problem can be solved by applying an <em>extract to method</em> refactoring (yes, I am a funny guy <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':lol:' class='wp-smiley smiley-10' /> ). But in Groovy we have another alternative that I find to be more elegant and easy to read. </p>
<p>As you know (and if don't, you should <a href="http://groovy.codehaus.org/Extended+Guide+to+Method+Signatures#ExtendedGuidetoMethodSignatures-ArgumentswithDefaultValues">read this</a> <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-)' class='wp-smiley smiley-19' /> ), Groovy supports default values for a method arguments. So, you can do the following:</p>
<pre class="brush:groovy">def method(a, b = 3, c = []) { ... } </pre>
<p>That is the same as doing:</p>
<pre class="brush:groovy">
def method(a) { method(a, 3, [] }
def method(a,b) { method(a, b, [] }
def method(a,b,c) { ... }
</pre>
<p>In fact, I think this is what the compiler actually do, making the feature a simple code generator that takes place in preprocessing time (but that is just me guessing <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-)' class='wp-smiley smiley-19' /> ). Anyway, what you may not know is that the optional parameters can be assigned with method calls, and that this method calls can use the rest of the parameteres. So, the original code can be as following:</p>
<pre class="brush:groovy">
def updateContractAddress(contract, newAddress, client = contract.client, 
      currentAddress = client.address, country =  CountryService.findByPostalCode(newAddress.postalCode))
{
   client.previousAddresses << currentAddress
   client.address = new Address
   client.save()
}
</pre>
<p>Now we can focus on the method body without being distracted by all this boilerplate code, but if we want to take a look at it, is just a few lines above, and we don't need to navigate the class as the previous solution. And for free, we obtain a parametrized method: in we need to pass the client as a parameter in the future, we can do it without modifying a single line <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-)' class='wp-smiley smiley-19' /> .</p>
<p>What I love about this trick is that it can aslo be used with Closures, so you can do stuff like the following:</p>
<pre class="brush:groovy">
[ name: 'diego', lastName: 'toharia', country: 'spain' ].each { 
   factName, factValue, capitalizedFactValue = factValue.capitalize() ->
   person[factName] = capitalizedFactValue
}
</pre>
<p>Ha <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> . Love it.</p>
<h4>Bonus track</h4>
<p>When using this last trick, be careful: if the method that receives your closure checks the number of arguments it receives in order to invoke it with the proper number of arguments, you can see how your method initialization is replaced by an unexpected value! An example of this would be the closure passed to a Grails validator:</p>
<pre class="brush:groovy">
class SomeDomainClass {
   String prop
   static constraints = {
      prop(nullable: true, validator: { prop, domainClass, propIsEmpty = prop.trim() != "" -> 
         propIsEmpty || validateProp(prop)
      }
   }
}
</pre>
<p>In this example, the custom validator for the property prop init the propIsEmpty parameter in the closure signature, but Grails is smarter: if you pass a closure with one argument, it invokes it with the property. If it can receives two arguments, it passes the property and the object. But if the closure declare three arguments, it passes the current validation errors as well, so you will find that propIsEmpty won't have what you expected <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> . So use it carefully <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-)' class='wp-smiley smiley-19' /> . </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.deigote.com/2012/11/23/groovy-using-parameters-with-default-values-to-separate-method-configuration-from-method-body/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Temacos traducidos: Middle Brother &#8211; Million Dollar Bill</title>
		<link>http://blog.deigote.com/2012/11/16/temacos-traducidos-middle-brother-million-dollar-bill/</link>
		<comments>http://blog.deigote.com/2012/11/16/temacos-traducidos-middle-brother-million-dollar-bill/#comments</comments>
		<pubDate>Fri, 16 Nov 2012 07:50:00 +0000</pubDate>
		<dc:creator>Deigote</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[folk]]></category>
		<category><![CDATA[letra]]></category>
		<category><![CDATA[middle brother]]></category>
		<category><![CDATA[million dollar bill]]></category>
		<category><![CDATA[Música]]></category>
		<category><![CDATA[rock]]></category>
		<category><![CDATA[traducción]]></category>

		<guid isPermaLink="false">http://blog.deigote.com/?p=691</guid>
		<description><![CDATA[Letra original y traducción de la canción Million Dollar Bill del grupo estadounidense de folk rock Middle Brother, además de un par de versiones del mismo tema, en directo y en estudio.]]></description>
				<content:encoded><![CDATA[<p>La música me apasiona lo suficiente como para que cuando encuentro un tema nuevo que me engancha mucho, ocurran dos fenómenos a lo largo de un breve periodo de tiempo:</p>
<ul>
<li>Me obsesione con esa canción, escuchándola muchas veces, berreándola en el coche, intentando tocarla con la acústica, y a veces, Dios no lo quiera, grabándola con el Garage Band a ver qué suena.</li>
<li>Me dedique a ponérsela a mis allegados, o a compartirla compulsivamente en las distintas redes sociales de las que hago uso.</li>
</ul>
<p>Normalmente, el segundo fenómeno implica enviarle una traducción de la letra a mi mujer, de esa manera sé que las posibilidades de que ella también se enganche crecen exponencialmente <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> . Así que a partir de ahora, cuando eso ocurra, intentaré aprovechar para compartir el tema y la traducción <em>con España y el mundo</em> (apagar modo reality :lol ).</p>
<p>La canción que hoy traigo es de un grupo llamado <a href="http://en.wikipedia.org/wiki/Middle_Brother_%28band%29">Middle Brother</a> (Hermano del medio, vaya, como yo <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> ), una banda de folk rock estadounidense que representa la palabra americanada, pero en el buen sentido <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> . El tema en cuestión es el que cierra su único álbum a día de hoy, de mismo nombre, y se llama Million Dollar Bill. La escuché gracias a mi <em>dealer</em> musical habitual, mi hermano (bajista de los archifantásticos <a href="http://www.lesvivo.com/" title="Les Vivo">Les Vivo</a>), y me tiene absolutamente enganchado. Aquí os dejo una versión hecha en la calle tras conducir por la noche después de un concierto (o eso dicen, por sus pintas me lo creo):</p>
<p><iframe width="560" height="315" src="http://www.youtube.com/embed/HE04t59uRY0" frameborder="0" allowfullscreen></iframe></p>
<p>Aunque también podéis escuchar la <a href="http://www.youtube.com/watch?v=2Lu7Mhff2wo">preciosa versión de estudio</a>, que aunque suena mucho mejor, es menos divertida de ver <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-)' class='wp-smiley smiley-19' /> . Y a continuación, mi traducción, que seguramente tenga fallos (y por supuesto, agradeceré correcciones <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-)' class='wp-smiley smiley-19' /> ).</p>
<table class="song">
<thead>
<tr>
<th>Original</th>
<th>Traducción</th>
</tr>
</thead>
<tbody>
<tr>
<td>
When it hits me that she&#8217;s gone<br />
I think I&#8217;ll run for President<br />
And get my face put on the million dollar bill<br />
So when these rich men that she wants<br />
Show her ways that they can take care of her<br />
I&#8217;ll have found a way to be there with her still</p>
<p>oooh, oooh, oooh, oooh, oooh,</p>
<p>When it hits me that shes gone<br />
I&#8217;ll think I&#8217;ll be an astronaut<br />
Make the moon my home and leave this world behind<br />
So when she steps out to the night and find the light that makes her pretty<br />
She&#8217;ll be facing me everytime she shines</p>
<p>oooh, ooooh, ooooh, ooooh, oooh</p>
<p>When it hits me that shes left me alone<br />
When I finally move on with my life<br />
Her goodbye written into stone<br />
And her shadow moving through the night</p>
<p>When it hits me that shes gone<br />
I&#8217;ll think I&#8217;ll be a movie star<br />
Be the finest man the world has ever seen<br />
The lovers that she has found<br />
Tell her ways they have learned to talk to her<br />
Behind each perfect word is a little bit of me
</td>
<td>
Cuando me dé cuenta que se ha ido<br />
creo que me presentaré a Presidente,<br />
y pondré mi cara en el billete de un millón de dolares.<br />
Para que cuando esos hombres ricos que ella desea<br />
le enseñen maneras en las que pueden cuidar de ella<br />
yo haya encontrado una manera de seguir estando con ella</p>
<p>Uuuuuh uuuh, Uuuuuh uuuh uuuh, Uuuuuh uuuh uuuh, Uuuuuh uuuh uuuh.</p>
<p>Cuando me dé cuenta que se ha ido<br />
creo que seré un astronauta,<br />
haré de la luna mi hogar y dejaré este mundo atrás.<br />
Para que cuando ella salga por la noche y encuentre la luz que la hace bella,<br />
esté frente a mi cada vez que brille.</p>
<p>Uuuuuh uuuh, Uuuuuh uuuh uuuh, Uuuuuh uuuh uuuh, Uuuuuh uuuh uuuh</p>
<p>Cuando me dé cuenta de que me ha dejado solo,<br />
cuando finalmente pase página y siga con mi vida,<br />
su adiós escribo en una piedra,<br />
y su sombra moviéndose a través de la noche.</p>
<p>Cuando me dé cuenta de que se ha ido,<br />
creo que seré una estrella de cine,<br />
seré el hombre más elegante que el mundo haya visto.<br />
Los amantes que ha encontrado<br />
le hablarán de una forma que han aprendido para hablar con ella<br />
detrás de cada palabra perfecta habrá un poco de mi</p>
<p>Uuuuuh uuuh, Uuuuuh uuuh uuuh, Uuuuuh uuuh uuuh, Uuuuuh uuuh uuuh
</td>
</tr>
</tbody>
</table>
]]></content:encoded>
			<wfw:commentRss>http://blog.deigote.com/2012/11/16/temacos-traducidos-middle-brother-million-dollar-bill/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Grails Puppet module</title>
		<link>http://blog.deigote.com/2012/11/13/grails-puppet-module/</link>
		<comments>http://blog.deigote.com/2012/11/13/grails-puppet-module/#comments</comments>
		<pubDate>Tue, 13 Nov 2012 13:31:22 +0000</pubDate>
		<dc:creator>Deigote</dc:creator>
				<category><![CDATA[Informática, internet y tecnología]]></category>
		<category><![CDATA[devops]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[module]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[puppet]]></category>
		<category><![CDATA[sysadmin]]></category>

		<guid isPermaLink="false">http://blog.deigote.com/?p=685</guid>
		<description><![CDATA[A Grails puppet module made by OSOCO, that allows you to install diferent Grails versions in a puppet node. Has been tested with Debian and Gentoo, so it should work with Ubuntu as well, and has it source code available in Github (so it's free software).]]></description>
				<content:encoded><![CDATA[<p><span class="info">This is an english version of the post I published in Mindfood in Spanish.</span></p>
<h4>About the module</h4>
<p>The next Puppet module I wanted to talk about is the <a href="https://github.com/osoco/puppet-grails">Grails puppet module</a>. Same as <a href="http://blog.deigote.com/tag/puppet/">the other modules</a> for <a href="http://blog.deigote.com/2012/10/29/puppet-git-and-subversion-modules/#about-puppet">Puppet</a>, is published on <a title="OSOCO's Github" href="http://github.com/osoco">OSOCO&#8217;s Github account</a>, and is one of the most simple, but one of the most used in our infrastructures, for obvious reasons <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> .</p>
<p>This module allows you to install multiple versions of Grails in a puppet node. The usage couldn&#8217;t be simpler, as you can see in the following code:</p>
<pre class="brush:ruby">
class jenkins {
    ...
    grails { "grails-1.3.5":
        version => '1.3.5',
        destination => '/opt'
    }

    grails { "grails-1.3.9":
        version => '1.3.9',
        destination => '/opt'
    }

    grails { "grails-2.0.0":
        version => '2.0.0',
        destination => '/opt'
    }

    grails { "grails-2.0.1":
        version => '2.0.1',
        destination => '/opt'
    }
    ...
}
</pre>
<p>In this example, a class <em>jenkins</em> declare multiple Grails installations (in order to launch the tests battery for each project with the proper Grails version) by adding various <em>grails</em> resources that is parametriced by the Grails version and the destination directory. The Grails module will resolve the download URL (that since 1.3.6 version must point to Amazon S3 instead of being self-hosted as in previous versions), and retrieve and unpack the ZIP only if necessary (i.e if the given Grails version is not already installed in the specified destination directory).</p>
<h4>Dependencies</h4>
<p>The module depends on <a href="https://github.com/osoco/puppet-wget">OSOCO&#8217;s Puppet Wget module</a>, so you should checkout both modules into your modules directory. Or, if you are using <a href="https://github.com/rodjek/librarian-puppet">puppet-librarian</a>, you can add the following to your <em>Puppetfile</em> file:</p>
<pre class="brush:ruby">
mod "wget",
   :git => "git://github.com/osoco/puppet-wget.git"
mod "grails",
   :git => "git://github.com/osoco/puppet-grails.git"
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.deigote.com/2012/11/13/grails-puppet-module/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Android GCM Sender</title>
		<link>http://blog.deigote.com/2012/11/12/android-gcm-sender/</link>
		<comments>http://blog.deigote.com/2012/11/12/android-gcm-sender/#comments</comments>
		<pubDate>Mon, 12 Nov 2012 08:46:19 +0000</pubDate>
		<dc:creator>Deigote</dc:creator>
				<category><![CDATA[Informática, internet y tecnología]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[gcm]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[heroku]]></category>
		<category><![CDATA[notifications]]></category>
		<category><![CDATA[push]]></category>
		<category><![CDATA[sender]]></category>

		<guid isPermaLink="false">http://blog.deigote.com/?p=658</guid>
		<description><![CDATA[Android GCM Sender, a webapp that allows you to send configurable push notifications to your Android devices. Developed in Grails using the Grails Android GCM plugin and Ajaxify, and hosted in Heroku.]]></description>
				<content:encoded><![CDATA[<p><span class="info">In case you are a spanish reader, I published <a href="http://mindfood.osoco.es/index.php/android-gcm-sender/">an spanish version of this post</a> in <a href="http://mindfood.osoco.es/">OSOCO&#8217;s blog, Mindfood</a></span></p>
<h4>Motivation</h4>
<p>Imagine you are developing an Android app that need to receive push notifications. The application in charge of sending them to <acronym title="Google Cloud Messaging">GCM</acronym> is being developed by another team, and not only is not finished yet, but also that team may be in another department, or even in another company. You want to make sure your Android app fullfill the specifications (i.e it reacts in a way when receives a certain push notification), but you don&#8217;t want to depend on that other team (and neither want to develope a sender app yourself <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> ).</p>
<h4>Solution</h4>
<p>Well, that need of a configurable GCM sender app is the second artifact <a href="https://twitter.com/asantalla">Adrian Santalla</a> and <a href="http://deigote.com">I</a> developed in our two first <a title="OSOCO hacker fridays" href="http://mindfood.osoco.es/index.php/hacker-fridays-o-catalizadores-de-la-innovacin/">OSOCO&#8217;s hacker fridays</a>, (being the first <a title="Grails Android GCM Plugin" href="http://blog.deigote.com/2012/10/31/grails-android-gcm-plugin/">the Grails Android GCM plugin</a>), the <strong>Android GCM Sender</strong>.</p>
<div id="attachment_659" class="wp-caption alignright" style="width: 310px"><a href="http://blog.deigote.com/wp-content/uploads/2012/11/Android-GCM-Sender-Subscribe-your-devices-and-add-your-project-ID.png"><img class="wp-image-659 " style="width: 300px;" title="Android GCM Sender - Subscribe your devices and add your project ID" src="http://blog.deigote.com/wp-content/uploads/2012/11/Android-GCM-Sender-Subscribe-your-devices-and-add-your-project-ID.png" alt="" width="300" height="296" /></a><p class="wp-caption-text">Subscribe your device tokens by using the supplied URL, and introduce your project ID</p></div>
<p>Started as a test app for the plugin, we felt it would be easy to evolve it until the point of being useful to anybody: we just needed to parametrice the project ID (that you will get by <a href="http://developer.android.com/guide/google/gcm/gs.html">creating a Google API project</a> <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=')' class='wp-smiley smiley-22' /> and create an action that let Android devices subscribe. You can visit the Android GCM sender in the following URL: <strong><a title="Android GCM Sender" href="http://grails-android-gcm-sender.herokuapp.com/" target="_blank">http://grails-android-gcm-sender.herokuapp.com/</a></strong>.</p>
<h4>Usage</h4>
<p>The first step would be to subscribe your Android device ID using the URL <a title="Android GCM Sender - subscribe your device" href="http://grails-android-gcm-sender.herokuapp.com/device/subscribe?deviceToken=yourDeviceToken&amp;projectId=yourProjectId">http://grails-android-gcm-sender.herokuapp.com/device/subscribe?deviceToken=yourDeviceToken&amp;projectId=yourProjectId</a>. Don&#8217;t forget to substitute <em>yourDeviceToken</em> and <em>yourProjectId</em> with your project ID and Android device token, and remember that this URL is designed to be invoked through some kind of HTTPBuilder inside the Android app &#8211; that&#8217;s why it doesn&#8217;t any output :-). But if you want to use it directly in your browser you can do that as well <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> .</p>
<div id="attachment_668" class="wp-caption alignright" style="width: 310px"><a href="http://blog.deigote.com/wp-content/uploads/2012/11/Android-GCM-Sender-compose-and-send-your-push-message.png"><img class="size-full wp-image-668 " style="width: 300px;" title="Android GCM Sender - compose and send your push message" src="http://blog.deigote.com/wp-content/uploads/2012/11/Android-GCM-Sender-compose-and-send-your-push-message.png" alt="" width="300" height="231" /></a><p class="wp-caption-text">Compose your message, send it to the selected devices and see the message result</p></div>
<p>After that, write your project ID in the Android GCM Sender homepage form and press the refresh button. You will be presented a form that allows you to send a message (simple or composed) to one or many Android devices. Please note that two fake devices will be always available in case you want to do some tests with them. After filling the form, you can press the Send button, and the message result will be shown to you. And if your device ID and project ID are valid ones, you should receive a push notification with the message you composed in the previous view :-D.</p>
<p>Please bear in mind that, in order to keep our data small, your device and project ID are only kept for 24 hours &#8211; think of it as a feature <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> since you don&#8217;t have to worry about unsubscribing and stuff like that. In fact, since the database is in memory, we don&#8217;t have access to it.</p>
<h4>Source code</h4>
<p>The Android GCM sender is up and running in <a href="http://www.heroku.com/">Heroku</a>, but you can see the source code in <a href="https://github.com/osoco/grails-android-gcm-server-example">OSOCO&#8217;s Github account</a>, and even host it yourself if you want. The app is developed using <a href="http://grails.org" title="Grails - the search is over">Grails</a>, and the UI is spiced up with <a href="https://github.com/deigote/ajaxify" title="Ajaxify - your links and forms with Ajax ">Ajaxify</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.deigote.com/2012/11/12/android-gcm-sender/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Execute around pattern in Groovy</title>
		<link>http://blog.deigote.com/2012/11/07/execute-around-pattern-in-groovy/</link>
		<comments>http://blog.deigote.com/2012/11/07/execute-around-pattern-in-groovy/#comments</comments>
		<pubDate>Wed, 07 Nov 2012 09:41:29 +0000</pubDate>
		<dc:creator>Deigote</dc:creator>
				<category><![CDATA[Informática, internet y tecnología]]></category>
		<category><![CDATA[around]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[execute]]></category>
		<category><![CDATA[execute around]]></category>
		<category><![CDATA[groovy]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://blog.deigote.com/?p=638</guid>
		<description><![CDATA[The execute around pattern seems to be a common practice in fuctional related languages (although probably Rafael Luque would claim that, as almost everything else , made it first appearance in Smalltalk, and Marcin Gryszko would say that is just the old plain template method ), but it&#8217;s probably kind [...]]]></description>
				<content:encoded><![CDATA[<p>The execute around pattern seems to be a common practice in fuctional related languages (although probably <a href="http://osoco.es/equipo#rluque" title="Rafael Luque at OSOCO">Rafael Luque</a> would claim that, as almost everything else <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> , made it first appearance in Smalltalk, and <a href="http://grysz.com/">Marcin Gryszko</a> would say that <a href="https://twitter.com/mgryszko/status/266160296773709824">is just the old plain template method</a> <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-D' class='wp-smiley smiley-2' /> ), but it&#8217;s probably kind of new to Groovy programmers who come from Java, where it can be implemented, but doesn&#8217;t feel as natural as in Groovy. </p>
<p>The idea is pretty simple: when you have different peaces of code that are enclosed by the same &#8220;header&#8221; and &#8220;footer&#8221; code, you should extract this header and footer to a new method that receives the changing code as a parameter. Simple but powerful. The typical example is the usage of a resource that must be opened before using it and closed after:</p>
<pre class="brush:groovy">
def someWritingMethod(filePath, stuffToWrite) {
   file.open(filePath)
   file.write(stuffToWrite)
   file.close()
}

def someReadingMethod(filePath, charsToRead) {
   file.open(filePath)
   def readStuff = file.read(charsToRead)
   file.close()
   readStuff
}
</pre>
<p>With execute around, this could be changed to the following:</p>
<pre class="brush:groovy">
def someWritingMethod(filePath, stuffToWrite) {
   withFile(filePath) { file ->
      file.write(stuffToWrite)
   }
}

def someReadingMethod(filePath, charsToRead) {
   withFile(filePath) { file ->
      file.read(charsToRead)
   }
}

private withFile(filePath, Closure fileUser) {
   def file = file.open(filePath)
   def result = fileUser(file)
   file.close()
   result
}
</pre>
<p>As you can see, the second code have multiple benefits: first and most important, we avoid duplicated code, the worse thing that a programmer could do. Secondly, we simplify our business logic methods by not defining variables that will be used later (for example, in someReadingMethod, we define readStuff for later returning this, forcing the person that is mantaining our code to read more of it just to be sure that the readStuff variable is not modified later).</p>
<p>This is the most simple case, but there are tons of usages that you wouldn&#8217;t probably think of. Here is a Grails inspired example that deals with one of our most beloved friends from the Java world, the try-catch:</p>
<pre class="brush:groovy">
class UserController {
     
    def userService

    def updateUser(userId) {
        treatExpectedExceptions('index', userId) {
            userService.updateUser(userId, params)
        }
    }

    def updateUserGroup(userId, groupId) {
        treatExpectedExceptions('showGroup', userId) {
            userService.changeUserGroup(userId, groupId)
        }
    }

    private treatExpectedExceptions(actionToRedirect, userId, Closure exceptionThrower) {
         try {
            exceptionThrower()
            flash.message = "action.$actionToRedirect.success"
            redirect action: action, id: userId
         } 
         catch (MultipleValidationException validationException) {
            flash.error = "action.$actionToRedirect.validation.failure"
            redirect action: action, id: userId, params: [ invalidFields : formatInvalidFields(validationException) ]
         }
         catch (UserNotFoundException userNotFoundException) {
            response.sendError HttpServletResponse.SC_NOT_FOUND
         }
    }
}
</pre>
<p>As you can see, the user controller always follows the same structure: it tries to perform some business logic with a supplied user id. When the logic fails because of the user id not corresponding to an existing user, a 404 response is sent. If the logic fails because the changes made to the user are not valid, a error message is set and the invalid fields are included in the redirect parameters in order to be formatted in the view. And if the logic doesn&#8217;t fail, a success message is set and a plain redirect is done.</p>
<p>Here you can sense another benefit of using the pattern: when another programmer have to add a new method to the controller, he will see the existing code and probably will try to adapt the new method to use the treatExpectedExceptions, leading the UserController to be a uniform and easy to understand class. And by not having to rewrite all the exceptions logic, the UserController has became an easy to extend class too <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-)' class='wp-smiley smiley-19' /> .</p>
<p>And this is just an example that I made up while writting the post, but probably could be used in multiple controllers in the projects I&#8217;m currently working <img src='http://blog.deigote.com/wp-includes/images/blank.gif' alt=':-)' class='wp-smiley smiley-19' /> . So, as you can see, is a really simple idea that can be really powerful.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.deigote.com/2012/11/07/execute-around-pattern-in-groovy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
