Sunday, April 5, 2009

RoR says "Hello"

Lets begin with a simple Hello World program in Ruby.

Open a command window and navigate to where you want to create this cookbook web application. I used D:\Developer\Rails.

D:\Developer\Rails>rails -d mysql cookbook

This will create the cookbook subdirectory D:\Developer\Rails\cookbook along with the directory tree with folders for the app, db etc.
Starting with Rails 2.0.2, rails defaults to using SQLite3 database. If you want to use a different database you can specify it using '-d' option as shown above.
To test the web application, browse to the cookbook directory and do :

D:\Developer\Rails\cookbook> ruby script\server

This boots the WEBrick HTTP server by default. You can change the server to use Apache instead.
You can browse to or http://localhost:3000
This shows you the "Welcome Aboard! You are riding Ruby on Rails!". Leave the command window open with the server running.

Lets create a MyTest controller that serves a simple "Hello World" HTML page.

D:\Developer\Rails\cookbook> ruby script\generate controller MyTest

This will create a file apps/controllers/my_test_controller.rb. Right-click on this file and choose Edit.
Edit the file to look like the following :

class MyTestController < ApplicationController
   def index
      render :text => "Hello World!"

Now browse to http://localhost:3000/MyTest
If the page does not open, check the command window where the WEBrick server is running. You will find a lot of debugging messages. If you see an error like "Unknown database cookbook_development' and don't see the database in "D:\Developer\Rails\cookbook\db" then create it and try again.

Congratulations! you just successfully wrote the Hello World program.