Monday, August 21, 2006

Ajax On Rails

Brief Introduction to Ajax and its Use:

Have you ever realize the fact that the Desktop applications that you use are much more responsive than the Web applications available on internet ? Of course you must have if you ever used a Web application. And the reason for the same is very obvious. In the Web applications, most of the time the client server communication happens involving the data to be posted to the server, processing the data at the server side, and then returning the result. Now when communication over network comes in picture, then the network latency also comes in picture. And this latency makes the Web application slow.

Now this is something which cannot be removed fully. But of course we can try to reduce it to the maximum extent we can. How?

The Answer is Ajax or Asynchronous JavaScript + XML. Here I am assuming that you people already know how Ajax exactly works so I am not going in detail. I would rather try to explain How is Rails and Ajax together are making a difference in the developing the real fast Web Applications. However if you would like to refresh the Ajax concepts a bit more before going ahead read this by Jesse James Garrett, who gave this technique a usable name: Ajax.

Implementing Ajax in your Web Application:

You can use Ajax in your Web application in various ways. One is to use the API of the XMLHttpRequest object directly in your own custom JavaScript. The main problem with this method is that you would need to deal with all compatibility issues of different browsers (which is the most hectic and pissing thing according to my own experience). The other way is to use various JavaScript libraries such as DWR, Prototype, Sajax, and Ajax.NET. The JavaScript libraries provide Ajax services and at the same time take care of the differences between various browsers. And the easiest way is to use the Ajax facilities of Ruby on Rails. Ruby on Rails offers you some powerful built-in Ajax features that makes using Ajax in your Web Application no extra burden anymore.

Pros and Cons of using Ajax in your web application:

Pros:

  1. Optimum use of Bandwidth: Since Ajax makes it possible to render a small portion of the page; therefore you can avoid displaying all the data at the same time by sending heavy request and getting heavy response each time a page loads. Instead, you can send smaller requests and refresh a smaller portion of the page. As the size of the requests (i.e. the data that is being transmitted and received over the network between the client and the server) reduces the bandwidth is also utilized properly.
  2. Responsiveness: Ajax uses DOM (Document Object Model) to manipulate the page currently displayed in your browser within the browser itself instead of creating the whole loop of sending each request to the server and receiving the response with all the unnecessary data that is finally going to be the same as it is in the current page. Thus the Web applications using Ajax become more responsive.

Cons:

  1. Unexpected "Back" button behavior: As the Ajax Web applications update the smaller portion of the web page, so if you trigger a few Ajax actions in a page, and expect to return to the previous page with the single Back button click then it might not be possible.

    Developers have implemented various solutions to this problem. These solutions can involve using invisible IFRAMEs to invoke changes that populate the history used by a browser's back button. Google Maps, for example, performs searches in an invisible IFRAME and then pulls results back into an element on the visible web page. Although the World Wide Web Consortium (W3C) has not formally deprecated the IFRAME element which was introduced in HTML 4, the standard recommends the OBJECT tag instead.
  2. Problem in Book-marking a page: Since the Ajax web pages are updated dynamically, it becomes difficult to book mark a state of the page.

Steps in which Rails implements the Ajax:

  1. A page containing some Ajax is loaded in the Browser.
  2. User triggers an Ajax activity in the Browser by clicking some button, modifying some data on the page, or clicking any link etc.
  3. The client sends the corresponding data required to be processed at the server side using XMLHttpRequest. This is done by the Ajax engine in between the client and the server. This data transmission is called Asynchronous data transmission because the data is actually not sent by the normal HttpRequest object, rather it is sent by the XMLHttpRequest object and through the Ajax Engine and not directly by your browser.
  4. The data received and processed at the server side by the corresponding action handler. The handlers generate and send back the response using XMLHttpResponse object. The response may be some HTML fragment, plain text etc.
  5. The Ajax engine receives the response on the client-side. The JavaScript that is required for this process is auto generated by Rails!! You need not write anything.
  6. A small portion of the user interface changes with the response. The portion that is updated or replaced in this action is mostly in a <div> tag.

Helper Methods to Implement Ajax in Rails:

Although Rails provides various helper methods that can be used to implement Ajax in the views of you web application, the most simple is the link_to() method. But before you can actually use the Ajax in your views of your web application, you need to activate the JavaScript. You need to include the following single line of code to activate the JavaScript for a view:

<%= javascript_include_tag :defaults %>

before the </head> tag.

Now suppose you have a web application that displays the list of the books that you have in your library, and one of the views in your application is there displaying the list of the books. You want to remove certain books that you know are outdated and are no longer in stock. Suppose you have a template called list.rhtml in the app/views/books directory which is displaying the list of the books you have. Now, to add a link to delete the books, you need to add the following lines of code in the list.rhtml template:

<%= link_to 'Destroy', {:action => 'destroy', :id => book}, :confirm => "Are you sure that the book is no more in stocks and you want to delete it?" %>;

The above code, adds an additional link besides show and edit (show and edit links become available just by scaffolding the books table) links in the lists of the books. On clicking the link, the JavaScript popup windows appear with the message that you have given in the "confirm" parameter. On clicking OK, as expected the corresponding book is deleted from the books database. There is another method similar to link_to() called link_to_remote(). This method differs in the number of parameters that it takes. In addition to the name of the link and the action parameter it also takes a DOM element ID. This element is the one the content of which you want to replace in the view after the corresponding action is performed. So, if you want to reload just the list of the books that you have in your library, instead of the whole page, you can replace the above line of code by the following:

<%= link_to_remote 'Destroy', {:action => 'destroy1', :id => list, :update => 'books'}, :confirm => "Are you sure that the book is no more in stocks and you want to delete it?" %>

Did you note the extra :update parameter ? The difference is now that on clicking the Destroy link now, the server will return an updated list of books. And this new list will be placed in the list DOM object which represents the list of books displayed on the page.

Note: The destroy1 action is yet undefined. So we need to define it in the app/controllers/books_controller.rb as follows:

def destroy1
Book.find(@params[:id]).destroy
render :partial => "books"
end


Let’s see what each does here: The first line deletes the book record from the database. The render method in the second line returns the response to the browser. The partial parameter of the render() method ensures that the webpage is reloaded partially. So here the updated list of the remaining books in the library is returned to the browser and is displayed without any need to reload the whole page.

So this is how the Rails uses the Ajax to build powerful and real fast web applications. Although there is much more to explore in this area and use in live applications for you, I would stop here only for now. I hope you people get motivated to some extent so that you start using it. I have already started. Looking forward to my reader’s comments and suggestions also. I would also be coming up with some more useful methods that you can use while using Ajax with Rails.

Till then "Happy Reading and Happy Programming :-) "

Tuesday, August 15, 2006

Migrations - A Unique Feature Offered By Rails Framework

How many times has it happened to you that you decided to start your site development or any other e-business that required a database backend and then as the time passed and your business grew, you felt that the database selection was not good enough or the features that are offered by the newer database version or some other database are now a days more powerful and well suited to your business than it was few years back? It happens right!! And it is very natural because the technology changes day after day and so do the database management. You always want to move ahead to acquire better and more powerful functionality and features available.

But when it comes to migrating from one database to another, it’s a real "Pain in the ASS!!" I hope you would agree to that. And no wonder that this pain holds you back from going ahead and upgrading your database to the newer version and thus ultimately compromising with the revenue. And this is more serious a problem for smaller e-business where you cannot afford the cost involved.

Is there a way to get rid of all that pain while migrating from one DB to another according to the requirement change from time to time? The Answer after Rails coming to rescue us is YES!!

Rails has provided an in-built support to the Database Migration. Before showing you how, let us define what Migration is.

What is Migration: It is a feature of Rails framework that allows you to define the changes in the database schema of your web-application using the Ruby Language and thus making it possible for you to migrate from one database to another as well as upgrading or downgrading the database versions. This also allows you to keep a version control system to keep your database changes synchronized with core code.

If we list the Advantages of Migration in Rails, we can have the following points:

  • Help you achieve Database Independency: No matter what database (MySQL, PostgreSQL or SQLite) you switch to at any point in time, once you have your database schema ready in Ruby, you need not change anything further.
  • Cuts the cost of hiring different people having knowledge of the different databases: As the syntax conversion with database change is taken care of internally by the Ruby code.
  • Liberty to choose different databases: Allows you to choose the best database suited for your application by trying different ones easily as you can easily switch between different versions of a database.
  • Facilitates the synchronization of the same database schema in a team of developers working on a single project: As when someone in your team makes a change to the data abase schema, other just need to update, and execute the command rake migrate. And that's done!!
  • Helps you upgrade the database version on the live servers (production servers): While upgrading the database on the production servers you just need to run the command rake migrate. And that's also done!!

If the above discussion makes you think that you should be using the Rails Migration then please go ahead, otherwise just chuck it here itself and wait for the nightmare where you would need to upgrade to a new database!!

Those who realized the impotrence and potential, please come ahead.....

Now that you have realized the impotrence, without wasting a single second let's see how to use Rails Migration in 3 simple steps:

Step 1: Creating Migration using the migration generator: Run the ruby generator, ruby script/generate migration my_migration to create a new migration file. This would create a new file named as versionnumber_migration_file_name.rb in the db/migrations directory of your project. For example, if you want to create a migration file to upgrade the version of the database you are using in which you want to create a new table called entity, then you could run the following command: ruby script/generate migration add_entity_table. A file named as 002_add_entity_table.rb (assuming you already have a migration file, if not the number will be 001 instead of 002) will be created in the db/migrate directory.

Note:

  1. The Migrations has a naming convention and that is that the name of the migrations that you are creating should either contain underscores (my_migration) or they should be camel-cased (MyMigration)
  2. The name of a migration should be unique and should not match with the name of any of the existing models class failing which the rake migrate will fail.

Step 2: Writing the migration code: In the newly created migration file in the db/migrations directory, define "self.up" and "self.down" methods. These methods tell the system what to do when a database version is upgraded to next version or is downgraded to a lower version.

Note: The version that we are talking abouit here is not the version of the database exactly. Instead it is the verdsion of the migration that we are maintaining in the project. The version number here are 001, 002, and so on. This is a means of keeping a version control over the database scema changes thoughout the development of the project.

For example, if you open the newly created file, 002_add_entity_table.rb, you would see the following lines of code in it:

class AddEntityTable <>

def self.up

end
def self.down

end

end


Note that there is no code at all in the self.up and self.down methods. Now our need is to create a new table whenever we upgrade the database version, so we will write the create_table query in the self.up method as follows:

class AddEntityTable <>

def self.up

create_table :entity do ¦e¦

e.column :first_name, :string

e.column :last_name, :string

e.column :joining_date, :date

end
def self.down

endend


Still, you can see that the self.down method doesn't have a body. Now suppose our need is to delete the newly created table (most obvious) while downgrading to the current version again, then we need to write a drop_table query in the self.down method as follows:

class AddEntityTable <>

def self.up

create_table :entity do ¦e¦

e.column :first_name, :string

e.column :last_name, :string

e.column :joining_date, :date

end
def self.down

drop_table :entity

end

end


Step 3: Run the rake migrate command: That's it dude!! You are done with the migration part. Mind blowing!! Right?

You can also downgrade the database version in the similar manner. You simply need to run the rake command again with the version number to which you want to downgrade. For example, if we want to rollback to the older version, say version 1, we will run the following command: rake migrate VERSION=1. This command will run the self.down of the 002 version file and your database will be at the version 1 again.

Note: The rake migrate VERSION=versionnumber, command takes the keyword VERSION all in caps only.

Wondering how rake works? Here is the explanation!!

The command, rake migrate VERSION=versionnumber, automatically decides what to do. What I mean to say is, if you run this command passing a version number lower than the version which you are currently in, then it will run the self.down methods of the all the migration files starting from current migration version file up till versionnumber-1 migration file. On the other hand if you run this command passing a version number higher than the version which you are currently in, then it will run the self.up methods of the all the migration files starting from current migration version up till versionnumber-1 migration file.

Thursday, August 10, 2006

Why to Use Generics in JAVA

How many times have you faced a Java.lang.ClassCastException while handling Collections?
Even if you are a good programmer then also you must have faced this problem sometimes or the other, and if you are not then of course many a times :-). Actually, it’s not about being a good or bad programmer, but it’s just about how attentive you are while writing the code using Collections. And the Java.lang.ClassCastException occurs while downcasting any java object. i.e. you are actually trying to cast an object which is at a comparatively higher level in the parent-child hierarchy into an object which is at lover level of parent-child hierarchy.

You must be thinking, why the hell I am talking about this java Exception explicitly while discussing the Generics feature. The reason is that Generics are the most useful mans of avoiding this ClassCastException exception while working with Collections. In a way Collections are the main application area of Generics. This is because Collections can store anything i.e. Objects. And when you have objects stored in Collections, such as Hashtable, you obviously need to remember what you inserted and what you have to take out. The main problem is that, when you take the object out, then you need to explicitly cast that object into an appropriate type, depending on what you inserted initially before you can perform any operation specific to the type of the Object.

Let’s look at the following code snippet:

1 public void createCollection () {
2 ArrayList testlist = new ArrayList();
3 testlist.add(new String("sanjeev"));
4 testlist.add(new Integer(9)); // to cause runtime ClassCastException
5 iterateThroughCollection(testlist);
6 }
7
8
9 protected void iterateThroughCollection(Collection collection) {
10 Iterator i = collection.iterator();
11 while (i.hasNext()) {
12 String element = (String) i.next();
13 }
14 }

Here first we declared a Collection ArrayList (using method createCollection()) testlist and put two items in it. Note that one item is an Integer and the other is a String type. Then we are iterating through the collection and taking out each element of it and typecasting it to String object.

So what happens when you actually execute the createCollection() method? Of course you would get a ClassCastException!! This is because; as I mentioned the Collection classes store each element as Object. This is advantageous in terms of providing us the flexibility and abstraction, but looking a little deeper you realize that it requires you doing an extra work of figuring out what Objects were inserted in collection before they can be used in your code after taking them out of the collection.

Let’s see why??

Going back to the code snippet again now, there are two Objects in the testlist collection, an Integer and a String. But as they are "stored" as Objects, we require typecasting them explicitly to the original data types (see line 12 of the code snippet above). And this is something which the developer should take care of as downcasting (Object to whatever type you inserted originally, String or Integer in this case) is not checked by the compiler. In this way there is always chance that the developers forget and a ClassCastException is thrown, as it happens in the above example. The above code will compile successfully but will fail at the runtime throwing ClassCastException at the line 12; while trying to cast the Integer Object to String Object!!

Now, if you can relate any of your past nightmares to this problem and feel that it would be worthy to remove this problem altogether without taking much of an effort and without increasing the complexity of the code, go ahead and read the rest of the post, otherwise just chuck it here itself and wait for the next nightmare to come back to this line again. As I feel eventually you will have to come!!!

Formers please move ahead in every aspect (reading as well as smart coding practice :-))

Using Generics you can avoid such problems while using Collections in JAVA. Before getting into deep explanation, let’s have a proper definition. Here it goes:

Note: If you are a C++ programmer, you can relate Generics to the C++ templates, as it is similar to the C++ templates in syntax and semantics both and comparatively a little simpler. But there is a difference. The difference lies in the fact that templates generate a new class for each specialization while Generics don't. Also Generics, unlike C++ templates, do not permit “template metaprogramming.”

Generics in Java 1.5: Generics in Java is a means of creating parameterized objects, i.e. specifying the objects that a class can work with at the time of declaring the objects. This is done by passing parameters in angular braces <>. These objects are then evaluated at the compile time itself unlike at the run time as is the case without Generics.

OK....I don't think those lines gave you very clear idea.

Let’s look at it with another example:

ArrayList<string> testlist = new ArrayList<string>();

Look at the above declaration. Did you notice the <Type>(); attached with the classname ArrayList? Of course you did!! So there you are. This is the whole concept of declaring the generic objects. The code is read as “of Type”, so the above ArrayList declaration will be read as “ArrayList of String testlist.” Looking at the code, you would never deny that it is quite clear and readable. Moreover, I feel that it gives you a very clear idea of what the collection is going to contain and therefore what kind of operations you can carry out on the items that you will retrieve from this collection. The above ArrayList, testlist, now can contains only String Objects and therefore the complier knows that the elements are going to be String types and therefore you need not actually typecast the retrieved objects to String.

Thus, we achieved the following out of it:
  1. Eliminated an unsafe cast and a number of extra parentheses form your code.
  2. Inserted valuable information (that the testlist will only contain the String objects) about the object in the declaration itself.
  3. Provided ability to the compiler to verify at the compile time that the type constraints are not violated at run time.
  4. Improved readability and robustness.
And most importantly the above three factors increase your self confidence and you can say your boss (If you still face a ClassCastException) with certainty that your code is innocent :-).

So before closing, let's see the above example with Generics:

1 public void createCollection() {
2 ArrayList<string> testlist = new ArrayList<string>();
3 testlist.add(new String("sanjeev"));
4 // testlist.add(new Integer(9)); this line wont compile as the ArrayList is already declared of String Type and here you are trying to put in Integer.
5 iterateThroughCollection(testlist);
6 }
7
8
9 protected void iterateThroughCollection(Collection<string> collection) {
10 Iterator<string> i = collection.iterator();
11 while (i.hasNext()) {
12 String element = i.next();
13 }
14 }

At the end, I would like to say the following hoping that you will also agree to this:

"Use generics everywhere you can as one time effort in gentrifying your code is well worth the gains in clarity and type safety."

In the next post related to Generics, I would like to tell you some rules in generics which if you keep in mind, will help you to use generics efficiently. Till then, Happy Reading and Happy Programming. :-)

Tuesday, August 08, 2006

Time to Get On Rails with Ruby

Ruby on Rails: - Very commonly heard phrase, (kind of, as it seems to me :-) ). Most of us who are even a little bit interested in tying something new, must have heard about the new (not quite new now !!) language (Ruby) with the fairly simple and powerful framework (Rails). Even if you have missed it by any chance, now the time has come to "Get on Rails with Ruby" because I personally feel that you cannot afford to miss it. Why?? Let’s Explore.

Before going into the explanation, why we should start using Ruby or start rolling on Ruby with Rails, let us get an idea of what is Ruby and Rails separately. So here we go with the definitions:

Ruby: This is another (not as, "Yet Another!!”) purely Object-oriented programming language originated in Japan in the early 1990s. The main feature that makes it popular among the web application developers or any developer in general is that it offers you cleaner and simper syntax. And a clean and simple syntax of course makes your application far easier to maintain, debug, test, and scale, all which is required to make our life simpler. Ruby is a mixture of good features of various other languages. For example, it is as easy to use and learn as Python, as conceptually elegant as Smalltalk, and as pragmatic as Perl. You can easily get an idea about the growing popularity of Ruby by the fact that now more and more English language books and documentation have become available on Internet about a programming language developed in Japan.

Rails: Rails is another a framework that itself is developed in ruby which is required to web applications with database-backend. So what? Is that the immediate question in your mind? Quite obvious. You need some solid reasons to even thinking of trying something. So here goes the simple reason: The very sentence that makes me go and try the framework immediately is that you actually can develop a web application many a times faster than using any other Java framework available till date and that also without compromising the quality you offer to your end-users!

But how?

Ruby language itself is the partial answer. This is because Ruby offers many a features that are impossible in other languages or too hectic to implement in some languages. And when coordinated with Rails, the advantage is doubled. This is because Rails exploit all the explicit features that Ruby offers to become allow you to develop faster and stronger web applications. Rails is able to exploit the feature because of the two basic principles that it follows: less lines of code and convention over configuration.

Less Software: As the word says means you need to write fewer lines of code to implement maximum of the functionality required by your application. After all which developer doesn't want to write as fewer lines of code as possible to get the maximum work done!! And this is made possible by combined power of the Rails framework and Ruby library. Smaller code in turn reduces the time you waste in debugging, understanding, maintaining, and enhancing your application in future.
We will also have a look at how is that shorter code to get maximum functionality possible with Rails.

Convention over Configuration: Rails do not require you to put hell lot of settings in various configuration files that are required by your current framework to run your application. Rails put an end to the complex XML configuration files. Rails instead believe in few simple conventions. As the conventions are understood by Rails, it automatically picks up the settings it requires to run your web application. This is made possible by utilizing the information that is already contained by your web application code and the backend database.


If it hasn’t clicked in your mind till now that you should explore further or try to use Ruby On Rails to enhance your web applications, then chuck it here itself, otherwise wait for the next post shortly coming up. In the next post, I would try to explain you Ruby On Rails with a small example so that you can try that yourself.