Grails is Groovy!

Grails

Grails is a framework that uses the advantages of Groovy, a dynamic type language which is almost a superset of Java, and the principle of “convention over configuration” in order to supply a very easy to use and quick to develop web-applications. It relies on the JVM and Spring as well as some other technologies that are out of scope for this post (Hibernate, templates etc).

Grails is based on MVC design pattern, in case you’re not familiar with it yet – you should, but until you do I’ll give you the highlights:
MVC stands for Model-View-Controller, which separates concerns and thus eliminates dependencies between the data (model), display (view) and business logic (controller). The controller is the entry point to the app, the HTTP request is dispatched to the relevant controller which drive the data from the Model, and might process it using one or more of the Service classes and will choose the proper View for display. The View doesn’t have to be strictly “display” it could also be JSON/XML or any other representation of the data.

In the rest of this post we’ll create the helloworld example and run it – with one major added value: I’ll help you avoid the pitfalls that I ran into. Ready ?

If you already have JDK installed – good for you, if not, you’ll have to install it first (not the JRE!)
It took me less than 10 minutes to download, install and run my first “Hello World!”
All you have to do is:
1. extract the zip file into the location you want it to be
2. add the environment variable GRAILS_HOME – make it point to that folder
3. update the PATH variable to PATH="$PATH:$GRAILS_HOME/bin"

After we’re done with the installation, navigate to the location where you want the project to be created (command prompt if you’re a windows user) and type:
grails create-app hello
after a few seconds, a new directory will be created by the surprising name of…
yes you guessed right: “hello” (convention over configuration anyone?)
Lets get in by typing cd hello and create our first controller. Can you guess the command ?
grails create-controller hello
if you missed this one – don’t be upset, you’ll get the next one.
One of the lines that were printed after the last command should have been:
Created file grails-app/controllers/hello/HelloController.groovy
Open a text-editor and edit HelloController.groovy:

package hello
class HelloController {

    def index() {
        render "Hello World!"
    }
}

That’s it! now, can you guess how to run our app ? that’s right:
grails run-app
it starts running, looking good, it even prints:
Server running. Browse to http://localhost:8080/hello
which seems awesome, but before we get to copy the URL and paste it into the browser…

*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message
transform method call failed at ../../../src/share/instrument/JPLISAgent.c line:
844
Exception in thread "main"
| Error Forked Grails VM exited with error

Hey! that’s not a nice thing to do!
Don’t worry guys, I hear you, here’s how we can fix it:
go to: hello/grails-app/conf
and edit the file BuildConfig.groovy – comment out the following section using /* … */ like this:

/*
grails.project.fork = [
// configure settings for compilation JVM, note that if you alter the Groovy version forked compilation is required
// compile: [maxMemory: 256, minMemory: 64, debug: false, maxPerm: 256, daemon:true],
// configure settings for the test-app JVM, uses the daemon by default
test: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, daemon:true],
// configure settings for the run-app JVM
run: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
// configure settings for the run-war JVM
war: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256, forkReserve:false],
// configure settings for the Console UI JVM
console: [maxMemory: 768, minMemory: 64, debug: false, maxPerm: 256]
]
*/

Now for most of the readers it should work: if you’ll grails run-app paste the following URL into your browser:
http://localhost:8080/hello
you should see the link to the controller that prints “Hello World!

But… if you’re like me… all the wrong things WILL happen: another issue I had was that port 8080 was already in use. To work around that, you can run your app on a different port:
grails -Dserver.port=8090 run-app

That’s it, now you should definitely see in your browser the following page:

sc-300x279

and once you’ll click the controller-link, you’ll receive a sweet “Hello World!” in Grails.

Update: there is actually an open bug for the issue described above, and a fix should be deployed on the next release (Grails 2.3.3)

Grails is Groovy!

A simple calculator in Ruby

Today I ran (again) into the following question:

  • Write a function that doesn’t use eval that calculates input strings with operators +,-,*,/ eg. “5+5*6+4/2″ should output 37

The first time I ran into this question I designed a solution, in Java, which had a SimpleCalculator class, and enam Operation which supported the four basic arithmetic operations: +-*/ each of which had an apply method etc. Very object oriented.

When I read this question today, I figured that it would be a nice exercise to do in Ruby – a few minutes later the result spread, elegantly, over less than 20 lines of code (and I bet that a professional Rubiest can do it in less)!

def is_number? expr
  return false if expr.nil?
  expr = "#{expr}"              # we need this condition in case the expr is a number
  expr.match /^(\d+|\d+\.\d+)$/ # since match() is defined only for strings
end

def calc(expr)  
  return expr.to_i if is_number? expr
  expr.gsub!(" ","") # clean the string from whitespaces
  # pay attention to the order: + and - should come before * and /
  # can you figure out why ?
  arr = expr.split /\+/
  return arr.inject(0){|x,y| calc(x) + calc(y) } if arr.size > 1
  arr = expr.split /\-/  
  return arr.inject(0){|x,y| calc(x) - calc(y) } if arr.size > 1
  arr = expr.split /\*/
  return arr.inject(1){|x,y| calc(x) * calc(y) } if arr.size > 1
  arr = expr.split /\//
  return arr.inject   {|x,y| calc(x) / calc(y) } if arr.size > 1
end

puts calc("5+5* 6+4/2.0")
#output 37

Do you have a better/shorter/more elegant solution ?
Please post it in the comments section!

A simple calculator in Ruby