I'm working on a service in Grails that offers all kinds of methods for getting dates or formats of dates with single line calls. For example, dateTimeService.getBracketDates()
which will return the first and last dates for the current month (e.g., 2/1/2011 and 2/28/2011). It's not rocket science but I have no desire to re-invent the wheel every time I'm creating a new monthly report for our marketing folks.
Tip: Keep a code snippets (experiment) file
One of the awesome things about groovy is that it's a lot like script programming. That makes it very convenient to try pieces of code and functionality you're not sure about before adding it to your project. Be forewarned. I'm a vi nut. I'm aware that dev tools have snippet support. I just find this works for me, and perhaps for you too.
The nice side-effect of this practice is that you build up a semi-structured collection of groovy and coding knowledge to reference in times of need and senior moments (not you, me!). Guess you could use it for old girl (or boy) friend names too. Another nice side-effect might be "instant book" once you insert a few paragraphs between each snippet!
Put a System.exit(0)
at the end of your snippet so that your groovy interpreter doesn't try to execute all the accrued code below. This won't protect you against
using variables that have already been defined lower in the file. All I usually do is attach a number to the end of the variable name to get rid of the name collision. Afterall, all I'm trying to do is validate my code. I used this little practice of mine to refinethe How-to below before subjecting you to what might have been buggy code.
How-to: Gathering list of (specifically-named) files from a directory
Here is one of many ways to accomplish this task. I found this old code snippet from my snippet file and thought I'd share it. By the way, a site I love to consult on little basics like this is Pleac Groovy. It's not the most groovy-tized site in the world, but I like it's get-it-done blue collar perspective.
So this bit of code returns a list of log files that use the the naming convention of <directory path>/<year><month><day>.log
. In particular, this code winnows the list of files down to the files stored in the month of February (i.e., 201102.*\.log). The regular expression is pretty lame. I'm sure you could improve it.
def baseDir = '/tmp/logs'
def originalFiles = new File(baseDir).listFiles()
println "number of files found:"+originalFiles.size()
// here's our closure, a match expression
def screener2 = { it.name =~ /.*201102.*\.log$/}
def screenedList = originalFiles.findAll(screener2)
println "Number of files matching :"+screenedList.size()
println "screenedList :"+screenedList
No comments:
Post a Comment