Technipelago AB

Technipelago Blog Stuff that we learned...


Use Perl to fix your old Grails controllers

Publicerad den 1 mar 2012

Use Perl to replace Grails action references with deprecated format redirect(action: show) to redirect(action: 'show') and action closures to action methods

Today I finally took the time to upgrade my largest Grails 1.3.7 application to Grails 2.0.1

You can read about it here.

I started to develop this application during spring 2008 and I've been upgrading to all Grails versions between 1.1 and 1.3.7. This makes the code base somewhat "dynamic". Different code styles and implementations depending on Grails version, best practices at the time, and my skills level.

As a result, lots of old controller code has redirects that reference action closures directly using the action's property instead of the action name.

redirect(action:show, id:params.id)

instead of the recommended:

redirect(action:"show", id:params.id)

I did a "grep" on all my 70 controllers and found out that 50 of them (300+) lines had bad redirects!!!

No way I was going to change all those lines manually.

That's when my old Perl knowledge came to rescue!

Here's the script fixredirect.pl


#!/usr/bin/perl

while(<>) {
  if(/redirect(.+)action:\s*(\w+)/) {
    print "$`redirect$1action: \"$2\"$'";
  } else {
    print $_;
  }
}

 

$ cd grails-app/controllers/...
$ cp *Controller.groovy $HOME/i-am-a-chicken
$ perl -i redirectfix.pl *Controller.groovy

 
Done!
 
All redirect(action:prop) are now changed to redirect(action:"prop")
 
UPDATE!
 
The following script converts
def actionMethod = {arg1, arg2 ->
  // ...
}
to
def actionMethod(arg1, arg2) {
  // ...
}
 
But it's not tested in "production" so please use with caution.
 
#!/usr/bin/perl

while(<>) {
  if(/^\s*def\s+(\w+)\s*=\s*\{([^\-]*)\-\>\s*$/) {
    print "def $1($2) {\n";
  } elsif(/^\s*def\s+(\w+)\s*=\s*\{\s*$/) {
    print "def $1() {\n";
  } else {
    print $_;
  }
}
 
Good old Perl, thank you!

Tags: grails perl controller upgrade


« Tillbaka