Archive for the 'Groovy' Category


Interceptando métodos inexistentes em Groovy 2

As linguagens dinâmicas estão ganhando um espaço considerável hoje em dia. Para dar um exemplo do poder dessas linguagens, criei um exemplo simples em Groovy (linguagem Java que roda “em cima” da JVM).

Uma das características dessas linguagens, é poder aproveitar a criatividade do desenvolvedor. Daí temos como exemplo uma função que pode ser definida em nossos objetos chamada methodMissing. Essa função é chamada quando algum método não encontrado é chamado em algum objeto. Caso não seja definida, aí sim temos o comportamento padrão do Java, uma exception apontando a falta do método.

No twitter, o @cmilfont perguntou ao @fabiokung sobre um builder de HTML que ele tinha feito em ruby com o mesmo princípio. Usar o methodMissing. Quando eu vi este builder, fiquei pasmo com a simplicidade e objetividade, e tudo isso originou este post. Coloquei alguns tratamentos que não existiam, para valores de atributos das tags.

O exemplo utiliza o poder da função methodMissing para criar um “Builder”, ou então um construtor de HTML dinâmico com base em pseudo-métodos chamados pelo cliente. Imaginem a função abaixo:

def methodMissing(String name, params) {
	if (params[0] instanceof Closure) {
		println "< ${name}>"
		params[0].call()
		println "< / ${name}>"
	} else if (params[0] instanceof String) {
		println "< ${name}>${params[0]}< ${name}>"
	} else if (params[0] instanceof Map) {
		print "< ${name}"
		params[0].each() {chave, valor ->
			print " ${chave}=\"${valor}\""
		}
		if (params.length > 1) {
			if (params[1] instanceof Closure) {
				println ">"
				params[1].call()
				println ""
			}
		} else println " />"
	}
}

No primeiro if, resgatando o parâmetro do tipo closure, apenas faz a chamada a esta closure, para que o novo método seja chamado entre “TAGS” que são o nome do método criado dinâmicamente… Já no caso do parâmetro ser uma String, é encarada como conteúdo inteno da tag e renderizada desta maneira.

Se um map for passado como parâmetro, a interpretação é tida como vários atributos da tag html (método inexistente), e caso ainda tenhamos uma outra closure ali como parâmetro, o comportamento é repetido :)

Com este exemplo, poderíamos construir um simples HTML com o seguinte trecho de código (script) groovy:

html {
    head {
        title "teste de titulo"
    }
    body {
        div(id:3, class:"odd") {
            p "meu texto"
        }
        div id:5, class:"xpto"
    }
}

Prontinho, a JVM com o trecho acima cria nosso super-mega-ultra-elaborado trecho de HTML:

< html >
< head >
< title >teste de titulo< / title >
< / head >
< body >
< div id="3" class="odd" >
< p >meu texto< / p >< / div >
< div id="5" class="xpto" / >
< / body >
< / html >

Groovy é uma linguagem de script muito bacana e poderosa, e como roda em cima da JVM, não é nada mais que Java puro. Pode com certeza e MUITA eficiência substituir aqueles scripts shell que temos em algumas aplicações, trazendo para os desenvolvedores mais liberdade (de chamar um jar com funcionalidades, por exemplo), e conforto (de não depender de alguém de infra estrutura, ou de conhecimento em shell script).

Fica aí a dica e o exemplo do poder…

Valeu!

Understanding Groovy Categories 5

Have you ever used Groovy Categories? Do you even know what its stands for?

Groovy Categories is a great feature from Groovy (inherted from Objective-C) that allows you to have some kind of “extended” control on a class. The category just “add” some more funcionality to your class when you want. It’s different from creating another class that extends from the first one, this approach holds a little more functionality-oriented talk… :)

Categories is nothing more than a Groovy class that you’ve implemented before that effectly adds your functionality. The syntax is very simple and all you have to do, is tell to the runtime environment you’re now using the category.

use (the category class you want to use) {
    //all your code here can access the category funcionality
}
//back to normal code

That’s it. Groovy Core comes with some Categories (ServletCategory, DOMCategory and TimeCategory). The one we use more is the TimeCategory, that adds some calculation methods for us.

Let’s imagine we want to add some days in our current date, using Java you remember how you should do, don’t you?

Get a Calendar Instance, retrieve this calendar’s date, add the ammount of days using the strangest and creepiest method ever and then get the calendar’s date again (actually, get only its time and create a date with it):

//creepiest method
myCalendarInstance.add(Calendar.DAY_OF_MONTH, 10);

You can see in the TimeCategory’s javadoc (link above) that it defines some methods like “getHours(), getDays(), getMinutes()”. This methods we don’t have in some usual Date class, but when we use the TimeCategory object, they just get available for us. The example below show us what should happen when we use the TimeCategory:

Date now = new Date()
println now //just show when am I :) 

use(org.codehaus.groovy.runtime.TimeCategory) {
    now = now + 15.days
}

println now //shows us when we'll be in 15 days!

This will be our output after running this small script:

Sat May 02 02:25:57 BRT 2009
Sun May 17 02:25:57 BRT 2009

That’s it, try the code above and the others methods the TimeCategory gives to you: years, months, hours, minutes and seconds.

Thanks! Be the first to know when I publish some interesting article signing up my feed and following me on twitter!

Changing the default locale for your grails application 5

Thank god grails has a wonderful i18n native support. It’s great change all your application language just by setting one more parameter in the URL (lang). If you do not know this behaviour, check this out.

But sometimes you have to preset the default language because not all your applications will be in english, yap ? To make this you’ll have to set your localeResolver in your resources.groovy spring configuration file. just add this code to it. (note that my code is setting my language to brazilian portuguese – pt_BR)

//this is your resources.groovy file
//
beans = {
   localeResolver(org.springframework.web.servlet.i18n.SessionLocaleResolver) {
      defaultLocale = new Locale("pt","BR")
      java.util.Locale.setDefault(defaultLocale)
   }
}

Another groovier way to access some itens in my list. 0

Hello,

Yesterday I’ve posted this post: Uma maneira bem ‘a-lá groovy’ de se acessar o último elemento de uma lista! (English version here) that explains how we can use negative indexes to access the elements on one list using groovy. And a friend of mine, Paulo Suzart, that works with me commented that using Scala he can have some extra calls one one list.

lista.head //first element
lista.last //last element
lista.tail //all elements except the first one

I myself do not know scala well, ( except for the times he keeps talking about it! LOL). But this comments submitted me to my textmate to explore the list methods, and I got surprised when I saw all that methods exactly reproduced in groovy. My mistake that I did not posted this way in yesterday’s post, but here it is:

def lista = []
lista << “first element”
lista << “second element”
lista << “third element”

println lista.head() //”first element”
println lista.last() //”third element”
println lista.tail() //gives me another list, formed by “second element” and “third element”

That’s it! Hope it helps.

You can follow me on twitter: twitter.com/lucastex

Grails 1.1 is available! 0

Hello!

Good news for today!! I just got @ work and saw in my twitter that Graeme Rocher just updated Grails with the new Version 1.1. This is awesome!!

Here is his twitt: http://twitter.com/graemerocher/status/1305118282
Grails 1.1 release notes: http://www.grails.org/1.1+Release+Notes
Grails 1.1 documentation: http://grails.org/doc/1.1.x/

Some stuff I really liked and I thing will help the day-by-day development:

  • GORM is now independent from Grails
    • Yeah, that is correct, now you can use GORM’s god-blessed-methods in your own groovy project!
  • hasMany associations for primitive types
    • You can use hasMany for primitive types, eg. Strings. Remember that time you had to create one domain class just for encapsulate one string? Now you can have this! :D
  • Global plugins
    • For people that knows Ruby and Rails, this will be like a gem. You install the plugin once with the tag -global and will be available for all apps

Visit the links above and stay tuned!

You can follow me on twitter: http://twitter.com/lucastex
Take care!

Grails 1.1 foi lançado!! 0

Oi,

Uma ótima notícia para a manhã de hoje!!! O framework Grails teve sua versão 1.1 lançada agora cedo! Ontem mesmo eu estava conversando com o Carlin e ele me perguntou se eu sabia quando iria ser liberada… Hoje cedo antes de sair de casa para vir para o trabalho, vi que o Graeme Rocher tava trabalhando em cima das páginas do wiki do grails.org… Bem na página de Releases…. Então o invitável estava para acontecer, precisariamos esperar apenas mais um pouco e teríamos a versão por lá….

1 hora depois, cheguei no trabalho e quando vi! Tava lá no meu twitter o anúncio por parte dele: http://twitter.com/graemerocher/status/1305118282
O release notes está disponível em: http://www.grails.org/1.1+Release+Notes e a documentação está em: http://grails.org/doc/1.1.x/. Tá com muita coisa legal, das quais para “facilitar” o dia a dia, 3 são bem legais:

  • GORM independente de Grails
    • Agora você pode usar o GORM em seu projeto Groovy, sem ter que depender de toda a estrutura do Grails!
  • Associação has-many de tipos primitivos
    • Isso!! Agora é possível ter um hasMany de Strings por exemplo! Antes tinhamos que criar uma classe que iria encapsular a string… :)
  • Plugins globais
    • Para quem conhece ruby, seria como se fosse uma gem, os plugins são instalados uma vez só com a flag -global e ficam disponívels para todos os projetos!

Confiram já no link acima!

Para quem quiser, pode me seguir no twitter e receber as atualizações: http://twitter.com/lucastex
Abraço!

Uma maneira bem ‘a-lá groovy’ de se acessar o último elemento de uma lista! 3

Oi,

Brincando com groovy e lendo alguns artigos durante o fim de semana na internet, vi umas coisas bacanas que facilitam o uso desta linguagem!

Uma coisa que achei bem legal foi uma dica de como acessar uma lista “de trás pra frente”. Isso mesmo, as vezes a gente precisa acessar o último elemento de uma lista certo? Como faríamos?

Vamos imaginar a lista abaixo:

def lista = []
lista << “first item”
lista << “second item”
lista << “third item”

Se eu quisesse imprimir seu conteudo para verificar, teria:

println lista[0] // “first item”
println lista[1] // “second item”
println lista[2] // “third item”

Para acessar o último termo, sem delongas iríamos ter que chamar posicionalmente o último elemento da lista, e para isso teríamos que conhecer seu tamanho. Teríamos:

lista.get(lista.size()-1); //Java
lista[lista.size -1] //groovy

Certo? A coisa bacana é que groovy tem todos os índices de um array/lista espelhados para a sua forma negativa. Ou seja. Se você acessar a segunda posição (lista[1]), irá ir para frente com o número inteiro. Se acessar a segunda posição negativa (lista[-2]), irá percorrer o segundo elemento de trás para frente!

Ou seja, para acessar o último elemento da lista, a forma mais rápida, fácil e com cheiro de groovy é fazer:

println lista[-1] //”third item”

Bacana hein! Valeu!

[]s,

The grooviest way to access the last item in a list 1

Hey!

Do you know that groovy provides a fuuny way to access the last item in a list? Let’s say you have the snippet above:

def lista = []
lista << “first item”
lista << “second item”
lista << “third item”

println lista[0] // “first item”
println lista[1] // “second item”
println lista[2] // “third item”

That’s ok hã. If you are using Java and needs to access the last item in this list, what should you do? I bet would be something like this (that is applicable to groovy):

lista.get(lista.size()-1); //Java
lista[lista.size -1] //groovy

I said “applicable” but doing this does not make me feel “groovier”… How about this trick?

lista[-1] //”third item”

That’s it! The indexes inside a list in groovy are “mirrored” backwards, so you can access the “first item from back to front” using the first negative integer! This is applicable to the rest of the entries:

println lista[-1] // “third item”
println lista[-2] // “second item”
println lista[-3] // “first item”

Take care!

[]s,

Web Analytics