Feb 4 2007

Rails Google Analytics Plugin

I am a big fan of Google Analytics. If you manage a blog, or any type of website for that matter, you should think of adding the little bit of JavaScript code that Google Analytics requires to start breaking down your page views. If you are developing a Rails app take a look at the Google Analytics Plugin. To install the plugin run the following command from the base directory of your Rails app.

script/plugin install http://svn.rubaidh.com/plugins/trunk/google_analytics

Before Google Analytics starts collecting stats on your site you need to configure the plugin. At the very bottom of your config/environment.rb file add the following configuration magic.

[source:ruby]
Rubaidh::GoogleAnalytics.tracker_id = ‘UA-123456-7’
Rubaidh::GoogleAnalytics.domain_name = ‘mydomain.com’
Rubaidh::GoogleAnalytics.environments = [‘production’]
[/source]

Make sure you have the right value for the tracker_id and domain_name. At this point, the Google Analytics code will be placed at the bottom of each page when running under the production environment. If you want to see the plugin in action under a development environment, replace production by development in the configuration snippet above.

One word of warning, the plugin basically works by replaces ‘</body>’ with analytics_code+'</body>’. If you, like me, normally capitalize HTML tag names then plugin will not output the analytics code. Make sure the your view template uses the lower case version of the ending body tag.

Also, you might not want to have Google Analytics collect stats on all your pages. To disable the Google Analytics code from a given action use the following filter function call on your controller.

[source:ruby]
# Don’t collection analytics stats on the about page
skip_after_filter :add_google_analytics_code, :only => [:about]
[/source]

To disable Google Analytics from most of the actions in a controller, except one for the show action, you can use the following code in your controller.

[source:ruby]
# Collect analytics stats only on the show action
skip_after_filter :add_google_analytics_code, :except => [:show]
[/source]

Technorati Tags: , , , , , , , , , ,


Feb 4 2007

Rails Named Routes

I have already gone in some detail about creating custom routes for your Ruby on Rails application. At this time, I would like to recall that you can pass additional parameters to your controller by adding them in your routes.

[source:ruby]
# Sometimes I need an extra parameter xid
map.connect ‘:controller/:action/:id/:xid’
[/source]

The route above will resolve for a url such as the following.

http://mydomain.com/mycontroller/myaction/1/2

For the above url, the controller can access two parameters, params[:id] and params[:xid]. Before nested routes where available in Rails, I would fake nested routes by creating routes like the following.

[source:ruby]
map.connect ‘:controller/:action/:id/comment/:xid’
[/source]

The route above would resolve for a url such as the one below if you had an action post in a controller blog.

http://mydomain.com/blog/post/1/comment/2

Because I was able to fake nested routes for my urls I really don’t understand why there is the need behind them.

Now, with the above background lets create a named route to view a blog post without naming both the controller and action.

[source:ruby]
map.post ‘post/:id’, :controller => ‘post’, :action => ‘show’
[/source]

The name of the route is post, named for the function call map.post. The route will resolve the following url to an action show in the post controller.

http://mydomain.com/post/1

Rails will create a post_url method which can be used in your rhtml view. In the rhtml view you can create the url for this route with the following snippet.

[source:ruby]
<%= post_url :id => @link.id %>
[/source]

In Rails 1.2 this will return an url as you expect.

http://mydomain.com/post/1

In Rails 1.6.1 this would return an string url with the controller and action name in it. If you are using Rails 1.6.1 and want your named route to resolve to the above url, use a different name for :id, such as :xid, in the routes definition.

If you are using Rails 1.2, you don’t have to pass in a hash parameter to the post_url view method. In Rails 1.2, you can pass in your ActiveRecord model for which the post_url method will use the models id in the generated url.

[source:ruby]
<%= post_url @link %>
[/source]

Technorati Tags: , , , , , ,


Feb 2 2007

JDBC and SQL Server 2005

Here is a quick tip. If your Java application is connecting to SQL Server 2005 via JDBC and you get a connection exception, check your that SQL Server has its TCP/IP protocol enabled. It took me a bit of digging to realize this when setting up a new test server. Here are the steps. Open the SQL Server Configuration Manager. In the configuration manager drill down to SQL Server Configuration Manager > SQL SErver 2005 Network Configuration > Protocols for SQLEXPRESS. Verify that the TCP/IP protocol is enabled. I also had to set the correct port number, 1433, in the TCP/IP Properties. After this, I was able to connect to SQL Server 2005 via JDBC.

Since I am on the subject, if you are working with a Java application and want to support SQL Server I recommend you use the jTDS JDBC driver.

Technorati Tags: , , , , , , , ,


Feb 1 2007

Jakarta Commons Lang Builders

I have mentioned different Jakarta libraries before. I described the Jakarta Common BeanUtils library in detail, describing how it is useful when accessing dynamic JavaBeans at runtime. I also scratched at the surface of Jakarta Commons IO with some code samples of FileUtils. Now I want to go over three classes made available from the Jakarta Commons Lang library.

The Java base class Object has three methods (toString, equals, hashCode) that programmers often override in their own classes. Just about anyone can safely override toString. As a general rule of thumb, it is recommended that if you override the equals method you also override the hashCode. These three methods are just too common, repetitive, and boring to implement and Jakarta Commons Lang library has builder classes to help you quickly and safely implement them.

For the following code samples, lets assume we have defined a simple Person class with a name and age field of type String and int respectively. We’ll also assume that the methods are defined inside said class.

Implementing toString
The ToStringBuilder class allows for a consist implementation of the toString method. To use it, just instantiate a object of ToStringBuilder and append the displayable field name and value. This method might remind you of StringBuilder. Here is a code example of how to use ToStringBuilder, modified from the Jakarta Commons Lang documentation.

[source:java]
public Strign toString() {
return new ToStringBuilder(this)
.append(“name”, name)
.append(“age”, age)
.toString();
}
}
[/source]

If an instance of our Person class would model someone named John who is 20, then the the toString mehthod would produce the following.

techknow.Person@61de33[name=John,age=20]

In my mind, that still looks geeky but fortunately for use the string builder accepts a ToStringStyle object as a parameter. Just subclass ToStringStyle and override a few methods to tweak the toString output.

Implementing equals
The EqualsBuilder class is helpful to implement the basic equals method. Continuing with our example of a basic Person POJO object with a name and age field, we could do something as follows.

[source:java]
public boolean equals(Object obj) {
if (obj instanceof Person == false) {
// Not even the same class
return false;
}
if (this == obj) {
// The same object reference
return true;
}
Person rhs = (Person)obj;
return new EqualsBuilder()
.appendSuper(super.equals(obj))
.append(name, rhs.name)
.append(age, rhs.age)
.isEquals();
}
[/source]

Implemeting hashCode
As you can gather by now, we can use the HashCodeBuilder class to quickly implement the hashCode method. Again, if for a given class you override the equals method you also need to override hashCode. Following our example, for a simple Person class, we can code something like the following.

[source:java]
public int hashCode() {
// Pick a hard-coded, randomly chosen, non-zero,
// odd number ideally different for each class
return new HashCodeBuilder(17, 37)
.append(name)
.append(age)
.toHashCode();
}
[/source]

One note, the code in these examples is based on version Commons Lang 2.2. All of the code example above are based on the Commons Lang API documentation. Consult your documentation, use as directed.

Technorati Tags: , , , , , , , , ,


Jan 29 2007

Java 7: The Closure Debate

Closures are code blocks; think of them as function literals that can be assigned to a variable and passed as a parameter to a function. Another name for closures that I have heard use is functors. Ruby and Groovy have closures and both of these languages run on the Java Platform. So why do we need closures in the Java language? Another good question is, but aren’t anonymous inner classes just like closures? The man the is trying to best answer these questions is Neal Gafter. Neal is rallying the Java community to include closures at the language level in next release of Java.

The issue of closures in Java 7 is a hotly debated topic and as software engineers and Java developers we will hear more on the subject for the foreseeable future. To get everybody up to date on closures here are some articles on the subject.

1. Closure – The computer science definition of a closure via Wikipedia.
2. Closure – The definition of a closure code block according to Martin Fowler.
3. Java Closure Poll – As of this written 70% are for closures.
4. Closures for the Java Programming Language – Closures for Java specification page.
5. A Definition of Closures – An detailed article by Neal Gafter.
6. Neal Gafter JavaPolis 2006 Interview – A 9 minute video interview of Neal Gafter.
7. Advanced Topics In Programming Languages: Closures For Java – A two hour talk by Neal Gafter on closures in Java in Google Video.
8. Considering Closures for Java – An interview with Neal Gafter on Artima.
9. Inner Classes or Closures – A detailed blog post on Artima about closures and inner classes.
10. When is a closure not a closure? – More on the subject.
11. Crossing borders: Closures – Bruce Tate has written a tutorial on closures using the Ruby programming language.

I’ll be updating this post with new resources as they are made available.

Technorati Tags: , , , , , , , , , , , , , , ,


Jan 29 2007

MySQL Optimization Tutorial

A while back I wrote a little introductory MySQL Administration tutorial. The tutorial had your basic information about starting the database server and creating databases. Now, I would like to jot down some commands that are useful when trying to optimize a SQL query on MySQL.

The first thing you need is to have a normalized database. This tutorial assumed you do and will not go into how to normalized you database schema.

In my limited experience with MySQL optimization techniques I have found that the single most important thing you can do is to create indices for foreign key columns and other columns used in the where clause. Here is the command to create an index.

[source:sql]
create index <index_name> on <table_name>(<column_name>);
[/source]
Continue reading