Tuesday, September 11, 2007

How to set up Ruby on Rails on BLUEHOST


This is intended to be a brief introduction to developing ruby on rails applications on a bluehost account. At the bottom of this article you will find a number of resources to help you learn more about ruby on rails and related information, as well as links to some rails tutorials that will go into more depth than this document.

Before you start digging your feet into Ruby on Rails, you should understand exactly what it is. Ruby on Rails is an advanced object-oriented Model-View-Controller application framework. If you didn't fully understand the meaning of the previous sentence, you're going to need to put in some study time before you can jump into rails programming. Ruby On Rails is aimed at advanced programmers; jumping into it before you're ready is likely to be very very hard. This tutorial should be easy enough for anyone to follow, but there's a lot more to rails than you'll be learning here. This tutorial serves as a first step into ruby on rails development on bluehost.

The Model-View-Controller (abbreviated to MVC) design pattern is fairly straight-forward, it simply means that your program is split into three separate components: The Model, View, and Controller. The "Model" is your data, no matter how it's stored. If you're writing a blog, this is where all of your posts and comments would go. The "View" is your interface. In the case of ruby on rails, we're talking about the part that displays your HTML. The controller handles the business logic, and ties the model to the view. MVC programming is beneficial for many reasons.

From this point on it is assumed that you have an understanding of both object-oriented design and MVC, and now you can get into how to develop rails applications on bluehost. A few additional notes before you start:

First of all, you need to have SSH access enabled. You'll need to contact customer support for this, either by emailing support@bluehost.com or by calling support at 1-888-401-4678.

Secondly, you'll see a lot of tutorials referring to a program called "script/server" or "webrick". This is NOT NECESSARY on a bluehost account, and you should never have to use it. This is designed for people who are developing their rails application on their own computer where there is no apache install which is pre-configured to use ruby on rails. However, you do have access to such a server on bluehost, so you do not need to worry about script/server. Do not run it, as it will not even work.

This tutorial is loosely based on the excellent official ruby on rails tutorial which is located at http://wiki.rubyonrails.com/rails/pages/Tutorial, although this document has been adapted to fit some bluehost-specific things.

To begin, log into the server using SSH. You'll need a work area for your rails application. Assuming ahead of time that you may eventually want multiple applications, you should make a work directory and then cd into it. You can name it whatever you would like, but this document assumes that it is called "rails".

% mkdir ~/rails
% cd ~/rails

Now you may create your application. As we are just making a simple Hello World application, we'll assume that the application is named "first".

% rails first
% cd first

Next, we're going to set up a subdomain for this application to run on. Log into your cPanel, click on 'subdomains', then type 'first' into the first text box and click 'Add'. You've now created a new subdomain, first.yourdomain.com, which will be the new home of your ruby on rails application. Now, we're going to make your application's "public" directory be the rootdir of that subdomain with the following commands:

% cd ~/public_html/
% rm -r first
% ln -s /home/YOUR_USERNAME/rails/first/public first

You should now be able to go to http://first.yourdomain.com/, where you will see the Ruby on Rails welcome message. As the welcome page suggests, it is now time to set up your databases.

In cPanel, click on 'MySQL Databases'. The first thing you'll want to do here is add an SQL user for rails to use. You can name this whatever you'd like. We will assume you used 'rails'. cPanel prepends your username to the user name, so you should take note of the actual name created (it should be username_rails).

Next, we're adding a database. Name this database 'first', to match your application name. You will again notice that username_ has been prepended. Finally, we're going to link this username to the database. Select username_rails and username_first from the dropdowns and make sure the 'All' checkbox below them is checked, then click the 'Add User To DB' button.

Now you should repeat this step, with 'firstdev' as the database name, and linking username_rails to it.

Now we're going to edit the database.yml file. Open ~/rails/first/config/database.yml in your favorite editor, and modify the 'development' and 'production' sections to contain the username, password, and database that you just created.

production:
adapter: mysql
database: username_first
host: localhost
username: username_rails
password: password

development:
adapter: mysql
database: username_firstdev
host: localhost
username: username_rails
password: password

Next you should create the actual database data. From the mySQL page in cPanel, you should find a 'phpmyadmin' link. Within phpmyadmin, select the "_first" database from the dropdown on the left, then click on the "SQL" tab along the top. Paste the following into your box and click 'Go':

CREATE TABLE `people` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(50) NOT NULL default '',
`street1` varchar(70) NOT NULL default '',
`street2` varchar(70) NOT NULL default '',
`city` varchar(70) NOT NULL default '',
`state` char(2) NOT NULL default '',
`zip` varchar(10) NOT NULL default '',
PRIMARY KEY (`id`),
KEY `name` (`name`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;

Now, click on the SQL tab one more time, and run this query:

INSERT INTO `people` VALUES (1, 'Superman', '123 Somewhere', '', 'Smallville', 'KS', '123456');

Now repeat these two sql queries for your _firstdev database.

The next step is to create a controller.

% ./script/generate controller First list view new edit

After that has been created, you will create your model.

% ./script/generate model Person

Now we're going to modify two files. First, open app/views/first/view.rhtml and make it look like this:



Friends#view


This page will display one friend



<%= @person.name %>

<%= @person.street1 %>

<%= @person.street2 %>

<%= @person.city %>

<%= @person.state %>

<%= @person.zip %>





Next, open app/controllers/first_controller.rb and modify the 'view' method to look like this:

def view
@person = Person.find(1)
end

Congratulations, You now have a working ruby on rails application which reads information from a database. Go to http://first.yourdomain.com/first/view and you should see Superman's information.

You should now go on to read other ruby on rails tutorials. You can find a lot of helpful information at http://wiki.rubyonrails.org/, as well as at http://rubyonrails.org/docs. You should also watch the Ruby On Rails Screencasts, which show you, among other things, how an experienced ruby on rails developer can create a fully functional application in a matter of minutes using ruby on Rails.

ADDITIONAL INFORMATION AND TUTORIALS:
More information on MVC: http://wiki.rubyonrails.com/rails/pages/UnderstandingMVC
Official Ruby On Rails Screencasts. You should watch these: http://media.rubyonrails.org/screencasts
Ruby on Rails wiki. The tutorials listed here are quite helpful: http://wiki.rubyonrails.org/
Why's poignant guide to ruby: You will either enjoy this or hate it, but it's a nice intro to the ruby language: http://poignantguide.net/ruby/

Sunday, September 9, 2007

Installing Ruby On Rails(WINDOWS)

Installing Rails on Windows (step-by-step tutorial)

Ok, so this will basically be somewhat a repeat of the information made by Curt Hibbs in this great hands-on tutorial. However, the versions of all products changed from the time Curt made his tutorial, and in some areas I felt that additional description was required. So, in this tutorial you’ll get a step-by-step instructions on installing Rails on Windows 2000 Server (Windows XP would be very similar).

In order to have a fully working development environment, you can use your PC. You will need to install:

  • Ruby - the language
  • Ruby Gems - the plug-in manager for Ruby
  • Scite or FreeRIDE - IDE for Ruby
  • MySQL - the database
  • MySQL query builder / MySQL admin tools - GUI to create databases, add users and create tables
  • Rails Framework

I. Installing Ruby
This is easy. Just get the latest One-click Installer for Windows (currently 1.8.2-15). Installation is simple, and indeed one-click. Once the installation is complete, check that path to ruby\bin directory is in your PATH variable (Run “cmd”, then type “path” at the prompt and check that the path is there.

The great thing about the one-click installer is that it comes with Ruby Gems, Scite and FreeRIDE preinstalled. The thing to watch out for is that one-click installer does not have the very latest version of Ruby, so when you are reading Ruby Docs, make sure you know which version of Ruby you have (run “ruby -v” in the command prompt).

II. Installing MySQL
This might be more tricky, depending on your home computer’s set up. First, download and run the latest Windows Essentials (x86) version of MySQL (currently 5.0.18). After the files are unzipped, an Instance Config should run automatically (you can run it manually at any time from your MySQL bin directory just run “MySQLInstanceConfig.exe”).

Below are the options to use for the Instance Configuration.

1. Select “Detailed Configuration”

p1.jpg

2. Choose “Developer Machine”

p2.jpg

3. Choose “Multifunctional Database”

p3.jpg

4. Leave the next screen unchanged

p4.jpg

5. Choose “Decision Support / OLAP”

p5.jpg

6. From the security perspective it is better to have “Enable TCP/IP Networking” unchecked, however I wasn’t able to make MySQL work with Rails in that case. So, choose “Enable TCP/IP Networking” for now and leave “Strict mode” checked.

p61.jpg

7. Choose “Best Support for Multilingualism” (MySQL will use Unicode for stored data).

p7.jpg

8. Have both options checked.

p8.jpg

9. Now, create a password for root account. Make sure that you do not use an easily guessable password and do NOT leave these fields blank (ie, do not use blank password for root). Also, leave the “Enable root access from remote machines” unchecked.

p9.jpg

10. Click “Execute”. If everything went ok, you should have green tick marks for all installation steps.

p10.jpg

11. Now, you need to do some basic security tweaking, to make sure nobody hacks your database from the outside. Go to the MySQL directory (c:\mysql by default), open my.ini and add the following line to the [mysqld] section of your server configuration file:

bind-address=127.0.0.1

This line will make sure that only services from your localhost will be able to access database (so, this means you and your web server).

Now, you need to restart MySQL. Go to Services (In Windows 2000: Start -> Programs -> Accessories -> Administrative tools -> Services), find “MySQL”, highlight it, click “Stop” and then “Start” icon.

12. Quickly try if your mysql set up is working, by running this command in the prompt:

mysql.exe -h 127.0.0.1 -u root -p

You will be asked to type your password and if everything is fine, should be presented with the message “Welcome to the MySQL Monitor” and the mysql prompt. It works! You are almost there.

If it does not work - first, make sure that you are entering the password right (check Caps Lock and Language Indicator). Check that MySQL service is running (see step 11). Another usual suspect is your local Firewall (your router firewall will not interfere with the local MySQL installation). A quick fix would be to allow communication for ruby.exe and mysqld-nt.exe on all ports (check your Firewall manual or help).

III. Installing Rails

1. Go into the ruby bin directory and run this command from the command prompt:

gem install rails --include-dependencies

(If this command gives you an error, you do not have the latest version of gems installed. Run “gem -v”, it should be 0.8.10. If it’s an earlier version, I recommend to reinstall the newest package - see beginning of the tutorial).

This command will install rails 1.0 and RDoc documentation for it. It should take up to 5-10 minutes, so do not worry when for a couple of minutes you just see a message “Updating Gem source index for: http://gems.rubyforge.org/” - there is no progress bar or any other indication of activity, but it is doing the work.

At the end you should see something like this:

p11.jpg

2. After that, create a directory for all of your projects. I just have one in the ruby directory. Go into this directory by using the “cd c:\ruby/myprojectsdir” and run

rails firstproject

You should see something similar:

p12.jpg

3. Finally, “cd firstproject” and run

ruby script/server

This will run the file “server” (no extension) in the script subdirectory of “firstproject directory”, which will in turn run the Rails built-in web server WEBrick. Test the web server by opening the following address in your browser:

http://127.0.0.1:3000/

You should see the following pic:

p131.jpg

One of the drawbacks of having a Ruby-based web server is that WEBrick needs to run in its separate command prompt window, so you should be careful not to close the window down incidentally, or you will need to restart the web server.

Congratulations! YOU ARE ALMOST DONE!

IV. MySQL Admin

Here, you have several options, however the tool I love the most - MySQL Control Center - is no longer in development. You can still download it here (v.0.9.2) or here (v.0.9.4). Or you can download MySQL AdministratorQuery Browser from MySQL.com. I haven’t tried those tools yet, so I will show how to work with MySQL CC, but the steps will be very similar. and

Note on MySQL CC and MySQL Administrator / Query Browser:
MySQL CC is not fully compatible with MySQL 5.x, so it might be better to use Administrator and Query Browser. However, MySQL CC is a very easy to use bare-bones program and it allows to do everything you need in this tutorial. If you opt for Administrator / Query Browser set-up, you would use the Administrator only for creating database users (and in future for setting up security, back-ups and restarting MySQL). For all other things you will use the Query Browser (in the Query Browser databases are called “Schemas”, and when you first run QB, you can safely ignore the warning to supply the schema name).

1. Install MySQL Admin and run it.

2. Create a new database connection by clicking the icon shown (or press Ctrl-N):

p14.jpg

3. Fill out the information as shown in the picture below:

p15.jpg

Name: This is any name you want - for GUI purposes only. Call it “My Development Database”.
Host name: This would be either “localhost” or “127.0.0.1″. On some weird configs “localhost” might not work, so try to use either one.
User name: “root”. Leave it as is.
Password: your root password. Remember setting it when installing MySQL? ;)
Make this server the default connection: If you do not have any other databases, tick this box. By running MySQL CC next time, you will automatically connect to the database.

Now, click the “Test” icon, and if successful, click “Add”.

4. Create the database.

Go to the main console. It now should have your database “My Development Database”. Check that it is connected, if not click the “Connect” icon.

Right click on the “Databases” folder and select “New database”. You will be presented with the following prompt. Just name the database “firstproject”, although it does not really matter how you call the database.

p16.jpg

5. Now, back to the main console window, you should see the database name “firstproject” in the list of databases for your server. Double click on the database and then click on the “Tables” subfolder. It should look something like this:

p17.jpg

6. Now, the database for your project has been created, you need to create a test table. Right click the “Tables” folder and choose “New table”. Let’s make two fields: id (type: int) and title (type: varchar).

“id” field is required by Rails and is the usual feature for the majority of tables. You do not usually insert the “id” directly, so we need to make sure that “id” is never empty (not null) and is automatically incremented (0,1,2,3,…). Also, make sure that the “id” is written in lowercase, for Rails to understand that this is your unique id field.

p18.jpg

Now, let’s define “id” as our primary field. Go into the “indexes” tab, select “id” field and press the right arrow, it should end up looking something like this:

p21.jpg

Now, add the “title” and choose the type “varchar”, like this (length of 100 symbols should be enough for your title, but when you will be adding a field for url you would want to change it to 255):

p19.jpg

Finally, click the “Save” icon and you will be asked to name your table. Rails has a special notation for naming tables - basically they have to be in plurals, as they will hold instances of particular class (objects).

Let’s call the table “Stories” (Rails is supposed to know the plural form for “Story”, so let’s try it out). Go back to the main console window and double click the “Tables” subfolder. On the right you will see the list of tables (we have only one at the moment - called “Stories”). Double click the table, it should return an empty set, as you do not have any records yet. (Do not try to create a record - MySQL CC will not correctly do this in MySQL 5.x).

7. Finally, it would be wrong to run your project using a root password. So, you need to create the database user especially for your project. It is very easy to do. In the main console right-click on the “User Administration” folder and select “New User”. Fill out the form as shown:

p22.jpg

Username: rails (this would be the username exclusively used for your project)
Host: localhost
Password: password you will use to access this user account
Priviliges: You should provide the least possible priviliges for the user. The ones selected by default are ok, but you can actually safely leave priviliges to only “Select, Insert, Update and Delete”, as we do not plan to create, drop (delete) or alter (change structure of) tables from our Rails scripts. Finally, select, to which databases you are allowing access. Select ONLY the “firstproject” database and click “Add”.

V. Rails in action

1. Now that the database model was prepared, we need to switch it on for our project. Go into your rails project subdirectory (you remember where you created it, right?). In the “config” subfolder you will find file database.yml. Open it and find the “development” section. In it, change database name to “firstproject”, username to “rails”, password to rails user password. Leave socket unchanged. Here is how it will look like:

development:
adapter: mysql
database: firstproject
username: rails
password: railspass55
socket: /path/to/your/mysql.sock

In order for those changes to work, you will need to restart the WEBrick server. Close the WEBrick window and run the server command again:

ruby script/server

2. You have the database schema defined and you configured Rails to access your database. Now, what we need is to create the class called “Story”. The easiest way to go is to create a scaffold, which is basically a default script to work with the standard database operations under the acronym of CRUD (Create Read Update Delete or in SQL terms: INSERT, SELECT, UPDATE and DELETE). To do this, again go to your script’s directory and run this command:

ruby script\generate scaffold Story

Make sure that you use the capital “S” - this is actually a Ruby rule that you need to follow - class names need to be capitalized. So, this is where the magic happens - you do not need to define the class in Ruby the “hard-way”. You define the class variables (so-called states) only once - in the database, and then those variables are automatically recognized by Rails and a standard CRUD framework is applied, which you can replace with your own code as you go.

3. Finally, check that everything works by going to this link: http://127.0.0.1:3000/stories/

For fun, try creating, updating and deleting records and see how the table records are automatically updated in the MySQL CC or Query Browser.

IN CONCLUSION
Installing Ruby on Rails is not a difficult process, but it takes some time. However, once installed you will not only feel comfortable with basic MySQL administration, but will also get a development environment which is much faster and easier to use than a hosting based alternative. Once you create a web service that can be released to public, you can easily move it to one of the Rails hosting providers.