Aug 24 2006

Grails Has Many Relationships

In Getting Started with Grails I went over some installation quirks in Grails to generating a scaffolding for a blog post domain model. In this entry, we will create a comments domain model class and link both domain classes so that post can have many comments. To start off, lets add some fields in your model (remember that up to now we have not defined our database schema).

Open the grails-app/domain/Post.groovy domain class, created in Getting Started with Grails, and add two string fields to represent the title and post data. Add a date to represent the created at date. The post domain class should look something like the following:

class Post {
  Long id
  Long version
  String title
  String post
  Date createAt

  // toString, equals, hashCode
}

If you start the grails application via the ‘grails run-app’ target and direct your browser to http://localhost:8080/blogjet/post/list you will be able to create, read, update, and delete posts with a title and post data.
Continue reading


Aug 21 2006

Gettings Started With Grails

So if you want to get started with Grails after reading Holy Guacamole Web Development with Grails then you are in the right place. In the next few paragraphs I will go over how to go from installing Grails to generating the scaffolding for a domain model. Just to provide a context for the code, lets just imagine we are building yet another blog engine.

INSTALLATION
Installing Grails is pretty straight forward. Just download and following the installation guide available from the official Grails website. I will make one observation that on OS X I add to change mode of the grails and ant scripts under the Grails installation directory. You might have to do the following if you are using a non Windows platform:

chmod u+x grails
chmod u+x ant

Also make sure you have the JAVA_HOME, GRAILS_HOME environment variables set and add GRAILS_HOME/bin to the system path. Once you have grails installed you can create a Grails application directory structure by running the following command:

grails create-app

The ‘create-app’ command line option is a ant build target. As noted, this command will create a directory structure for the Grails application and this directory structure is similar to that used by Ruby on Rails. But before Grails creates anything, you will be prompted to enter the name of the application. Let’s name the application blogjet for a lack of a better name.

That is it, you are all set to start generating your domain model classes. You might be wondering, ‘But what about the database configuration?’ Well, unlike Ruby on Rails, Grails does read you mind and guess that you want to test drive Grails not waste an extra five minutes configuring out the database connection. By default Grails will use HSQLDB as an in-memory database for you get get started. Just in case you ever want to use a different database you can modify the data source configuration file:

grails-app/conf/ApplicationDataSource.groovy

MODEL
Before we can proceed we need to create a domain model class. Change directories to the blogjet directory. To create a domain class enter the following command from the Grails application directory.

blogjet$>grails create-domain-class

Just as before when creating the Grails application, you will be prompted for name, this time for the domain class. Enter ‘Post’ as the domain class name. The create-domain-class target will create a Groovy class in grails-app/domain named Post.groovy:

class Post {
  Long id
  Long version

  String toString() { "${this.class.name} :  $id" }

  boolean equals(other) {
    if(other?.is(this))return true
    if(!(other instanceof Post)) return false
    if(!id || !other?.id || id!=other?.id) return false
      return true
    }
    int hashCode() {
    int hashCode = 0
    hashCode = 29 * (hashCode + ( !id ? 0 : id ^ (id >>> 32) ) )
  }
}

For brevity’s sake I will not display the toString, equals, and hasCode methods in future references of domain classes.

CONTROLLER
At this point we are ready to create the controller for our blog. Execute the following from the Grails application directory:

blogjet$>grails create-controller

Again, you will prompted for a name. Enter Post for the controller’s name. This command will create a PostController.groovy file in the grails-app/controllers directory.

class PostController {
  def index = { }
}

You can create a CRUD scaffold for posts by modifying the Post controller in the following fashion:

class PostController {
  def scaffold = Post
  def index = { }
}

STARTUP
Grails comes with the Jetty servlet container as part of its installation. To start the server run the following command from the command prompt:

blogjet$>grails run-app

The Jetty server will start on port 8080 so you can direct your browser to http://localhost:8080/blogjet/post/list to create, read, update, and delete blog posts.

RECAP
In the course of this post, we created a new Grails application by executing the ‘grails create-app’ target. In a similar fashion we created a domain and controller class. We did not modify our datasource configuration so we are using the default in-memory database in development mode as we are familiarizing ourselves with Grails. Grails comes with the Jetty servlet container and we can start the server by executing the ‘grails run-app’ target. We were able to create a CRUD scaffold with just one line of Groovy code in the the controller.

Yes, I know there are still a lot more question than answers especially since our models don’t have any data fields. In the next post we will go ahead and flush this out, add data fields to our models, and add has many relationships.

Technorati Tags: , , , , , , , ,


Aug 20 2006

Holy Guacamole Web Development With Grails

I was original going to name this post Agile Web Development with Grails but I didn’t want Dave Thomas to send me a cease and desist notification like DHH sent the Grails developers back when it was known as Groovy on Rails. For those that didn’t notice, I was trying to be funny in my last comment but at the same time trying to make a point made by others, that the Grails framework borrows heavily from Ruby on Rails. Like Ruby on Rails, Grails is a Model2 based agile web development framework that strongly favors ‘code by convention’ and makes use of great AJAX libraries such as prototype and Yahoo! UI library. In fact, looking at a Grails directory structure one is reminded of Rails. One key difference between Grails and Ruby on Rails, is that Grails is based on a Java EE stack. In Grails the model and controller classes are written using the Groovy programming language. Groovy is a a dynamic scripting language designed for the Java platform.

As a developer, I could care what language I use as long as I gets paid. I am not a designer so I could care less if my code looks pretty especially since I could always reformat and refactor the code. What my boss is going to want is that the framework I use works well with our current Java EE application and the thousands of classes we have already written. In our case, we already make heavy us of Groovy so it is easy for my boss to buy into Grails. Grails is an easy way for Java developers to get the same productivy experienced by Ruby on Rails developers. With Grails you can easily make use of all of the great class library available in Java and unlike other Java web frameworks like RIFE and Struts, Grails abhors XML configuration files.

Getting started with Grails is extremely easy. Just download and unzip Grails and add a GRAILS_HOME environment variable. That is it. You don’t even have to configure any database configuration, because Grails can read your mind. Well, not really, but Grails comes with an in-memory database already configured in development mode. Just create the domain model class and controllers using generators and that is all.

For non Java developers, I think Grails will be more difficult than Ruby on Rails. For one, I have had difficulties trying to debug Groovy code before. Secondly, the when something goes wrong the stack trace is difficult to decipher. Grails has auto-reload support but that still has some quirks. I’ve had to restart the server because I removed a field from my domain model class.

Now, because everyone always asks, what about performance? I attended the Rapid Web Development With Grails session at JavaOne. I wrote about Grails performance in my coverage of the Grails session at JavaOne.

Technorati Tags: , , , , , , , ,


Aug 16 2006

Class HighLite ThreadLocal

Some people think that by not using threads that would make their code thread safe. One way to write thread safe code is to pass state by parameters as much as possible, limit the use of singletons (also a source of memory leaks), syncronize accordingly, and use ThreadLocal objects where appropriate.

The ThreadLocal class is an object container that can store a different object for each thread where it is used. I think of the the ThreadLocal as a HashMap where each thread can set/get it’s own object, where implicitly the key for that object is the thread itself. To create a new ThreadLocal you can do the following:

[source:java]
ThreadLocal counter = new InheritableThreadLocal();
[/source]

Now to get and set the object stored in the counter ThreadLocal and we can do something like:

[source:java]
Integer count = (Integer)counter.get();
if(count == null)
count.set(new Integer(1));
else
count.set(new Integer(count.intValue() + 1);
[/source]

Technorati Tags: , , ,


Aug 12 2006

Top 13 Ruby on Rails Presentations

Here is a list of all the Ruby on Rails presentations that I have bookmarked.

VIDEO
Creating a weblog in 15 minutes – For me, this is the video that started it all.

Snakes and Rubbies: Complete – “On December 3, 2005, Ruby and Python developers from Chicago and vicinity gathered at DePaul University to hear two of the leaders in rapid Web-application development debate the merits of each other’s frameworks.”

Snakes and Rubbies: Persuing beauty with Ruby on Rail – “On December 3, 2005, Ruby and Python developers from Chicago and vicinity gathered at DePaul University to hear two of the leaders in rapid Web-application development debate the merits of each other’s frameworks.”
Continue reading


Aug 12 2006

Scriptaculous Rails

The script.aculo.us JavaScript library is ridiculously simple, and Ruby on Rails makes using it just as simple. Ruby on Rails provides a view helper visual_effect method which can be used in any event, such as an onclick event. Here is an example of the rails visual_effect helper method in action:

[source:html]
<%= content_tag ‘DIV’, ‘Hello, World’, :id => ‘msg’ %>
<%= content_tag ‘DIV’, ‘Click Here’,
:onclick => visual_effect(:highlight, ‘msg’, :duration => 1.0) %>
[/source]

In the above example, when the user clicks where indicated the Hello, World message will highlight for a second. You can also group a series of effects by wrapping them in a SCRIPT tag such as the following opacity effects:
Continue reading