"Hello World" in HTML/CSS/JavaScript/SQL/Ruby/Rails (Tutorial, Ch. 1)


While there are a ton of tutorials out there on every topic I'll be introducing in this eBook, my angle will be to stick with the "give me the general concepts" and "let's just get this rolling" essentials and allow you figure out the details on your own (I'll point you to resources & other tutorials out there). I'll be tailoring the class to anyone who would call themselves reasonably "good with computers" but may have little to no programming experience. However, even if you are 80 years old with decades of programming experience, I'm hoping this eBook will still be helpful to spark an entrepreneurial spirit and/or bring you up to speed on HTML5, CSS3, Rails3, etc....

Section 1 - Install MySQL, Ruby, and Rubygems

Installing stuff can (and often is) unfortunately a pain. Every operating system (OS) has it's own quirks and rarely does everything work perfectly on the first try. But, if you're reading this far then I'm assuming you're up for the challenge and are willing to do some Google searches if you run into trouble. What you need to have installed by the end of this section is an updated version of MySQL 5, Ruby 1.8.7, and Rubygems 1.4.

Installing MySQL (Database Software)

For Windows users, I'd recommend installing WAMP, which gives you MySQL, Apache (which we'll use later), and PHP (which we won't be using, but is a programming language that serves a similar purpose as our beloved Ruby). Once you have WAMP installed make sure to "Start Wampserver" from your list of programs.

For Mac users, you may already have MySQL5 installed (check with mysql --version in Terminal), and if not, go grab the appropriate DMG version here and install it. Ensure that the server is actually running by either looking in your system preferences or typing in Terminal:

 
$ ps aux| grep mysqld

(you should see two processes running). An important last step is to enter the command:


$ echo 'export PATH=/usr/local/mysql/bin:$PATH' >> ~/.profile

...so your "mysql" command will work without having to prepend /usr/local/mysql/bin all the time. Finally, if you have trouble getting things installed, check out this more detailed tutorial, where it also tells you how to set a root user password (a good idea) by typing:


$ mysqladmin -u root password NEWPASSWORD

Installing Ruby (Programming Language)

For Windows, Mac, and Linux users all the instructions you need are located at the Ruby download page. Make sure to download and install Ruby 1.8.7 (not Ruby 1.9.x).

Windows users, you will need to right-click this libmySQL.dll file and save it into your ruby \bin folder (e.g. c:\ruby\bin - but make sure "ruby" is actually replaced with the full path to the ruby folder you just installed). This will enable Ruby to talk successfully to MySQL through your Rails app.

Installing RubyGems (allows us to get Ruby on Rails)

Special note for Windows users. In order for the commands below to work, you will need to add the folder location of the binary files to the environment path variable. To do this, right-click on "My Computer" (or right-click "Computer" in your start menu), click on the Advanced tab, then click the Environment Variables button, highlight the Path variable in the Systems Variable section (find this on the bottom, you'll need to scroll down a bit in there to click on and highlight "Path") and click the Edit button. In the text box it gives you, add to the end these 3 paths: ;c:\ruby\bin and ;c:\wamp\bin\mysql\mysql5.5.8\bin and c:\ruby\lib\ruby\gems\1.8\gems\rails-3.0.3\bin

Make sure these paths match the paths to your ruby, mysql, and rails folders!!!

Once you've saved the path variable (make sure each path is separated by one semi-colon and there are no spaces), close cmd and start a new cmd session.

For Windows, Mac, and Linux users, download this zip file, unzip it, move the folder to a location you can easily access from the command line, and type the following command in the folder location (Mac users: remember to prepend 'sudo' before these commands or else you'll get a permission denied error.


ruby setup.rb

This will set things up for you.

Next, enter the command:


gem install rails 

(this will take a while), then:

Windows users need to use the mysql gem for things to work correctly:


gem install mysql -v=2.8.1

For mac users, use the mysql2 gem:


gem install mysql2

Section 2 - "Hello Worlds" via HTML, CSS, Javascript, MySQL, & Ruby on Rails.

OK, let's get to work. First, we're going to create a MySQL database, a table called Announcements, and a row in that table containing "Hello World"

Note, the mysql> below indicates you're in a mysql command line session, you do not need to repeat that in the commands you type in. Also, the "..." indicates there will be output from the commands that are omitted here.


mysql --user=root
...
mysql> create database my_first_app_development;
...
mysql> use my_first_app_development;
... 
mysql> CREATE TABLE announcements (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, body TEXT, created_at DATETIME, updated_at DATETIME);

Congrats! You just created a database and a table in that database to house some announcements. Don't worry for now if you don't understand what all that stuff means, essentially the table will always assign an increasing id # to an announcement, and you made room for an announcement body (e.g. "Hello World") and some record keeping of when an announcement is created and updated.

Now, let's create an announcement:

  
mysql> INSERT INTO announcements (body, created_at, updated_at) VALUES ('Hello World', NOW(), NOW());

Now you can see your "Hello World" in your database by typing:

  
mysql> SELECT * FROM announcements;
+----+-------------+---------------------+---------------------+
| id | body        | created_at          | updated_at          |
+----+-------------+---------------------+---------------------+
|  1 | Hello world | 2011-01-11 12:08:05 | 2011-01-11 12:08:05 |
+----+-------------+---------------------+---------------------+
1 row in set (0.00 sec)

Pretty cool. OK, now, let's create a Rails app and use it to bring our announcement to the world.


mysql> exit
Bye
mkdir railsapps
cd railsapps
rails new my_first_app -d mysql

This will create a bunch of files in a folder called my_first_app. The "-d mysql" tells Rails to set things up to communicate with MySQL (instead of a default database called SQLite).

Next, let's create a couple files and a folder in our app

Windows users will need to create the following files/folder manually

my_first_app/app/controllers/home_controller.rb
my_first_app/app/models/announcement.rb
my_first_app/app/views/home
my_first_app/app/views/home/index.html.erb

ALSO, you'll need to edit your my_first_app/Gemfile so gem "mysql2" says gem "mysql"

Also edit your my_first_app/config/database.yml file so adapter: mysql2 says adapter: mysql

For Mac users, the "touch" command in a Terminal session will get the job done:


cd my_first_app
touch app/controllers/home_controller.rb
touch app/models/announcement.rb 
mkdir app/views/home
touch app/views/home/index.html.erb


At this point we're now going to be editing files, so you will need to choose a good text editor. For Mac users, I'd recommend Textmate, and for Windows users I'd recommend syn Text Editor (which you can tweak to have nice syntax highlighting like Textmate). You can use whatever you'd like, however. But get VERY familiar and comfortable with your text editor of choice, as you'll be using it a lot.

The following files we'll be editing do really interesting things that we'll be explaining throughout the year. For now, we're just going to get things working.

Ok, now open up your app/controllers/home_controller.rb file and copy/paste in the following (don't copy in the line numbers, use the hover "copy to clipboard" feature to just grab the code):


class HomeController < ApplicationController
  def index
  end
end

..and in your app/models/announcement.rb model


class Announcement < ActiveRecord::Base   
end

..and in your config/routes.rb file make sure it contains this line:


root :to => 'home#index'

OK, finally, make sure your config/database.yml file has the my_first_app_development database named under "development" (it should by default) and your "root" user also has the password entered that you chose above (you'll need to enter it).

Next, delete the public/index.html file (which just says "Welcome aboard" and tells you you're on Rails) and then fire up the ruby web server


rails server
=> Booting WEBrick
=> Rails 3.0.x application starting on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server

...and you'll see it hang there, which is good. If you get any warnings/errors at this point, try to track down the problem (google search the message it gives you).

Now, fire up your favorite web browser and go to http://localhost:3000/ .... and .... you should see a blank white screen! That means it worked! Let's move on to filling in our multiple "Hello Worlds"

"Hello World" in HTML

Open up your app/views/home/index.html.erb file and add the following:


<!DOCTYPE html>
<html>
  <head>
    <title>Hello World!</title>
    <meta name="description" content="A very important announcement." /> 
  </head>
  <body>
    <p>Hello World!</p>
  </body>
</html>

Save it - then refresh your browser at http://localhost:3000/ and you should see a "Hello World."

Nice! You just wrote HTML. If you right-click in your browser and "View Source", you'll see the HTML code that your browser is interpreting to show you the Hello World. At the end of the day, the front-end Web pretty much comes down to servers sending code like this to web browsers asking for it. More on that in tutorial #2. Let's now do a CSS Hello World.

"Hello World" in CSS

OK, with your favorite image program on your computer make a simple PNG image w/ a white background, 80x35 pixels in size, that says "Hello World." You can also screen capture your "Hello World" from your web browser and crop it to those dimensions. If this task is difficult for you, just right-click this link and save the file to your desktop.

Name the file "hello_world.png" and place it in your public/images folder.

Now, open back up your app/views/home/index.html.erb file and let's make some CSS


<!DOCTYPE html>
<html>
  <head>
    <title>Hello World!</title>
    <meta name="description" content="A very important announcement." />
    <style type="text/css">
      #hello_world{
        width: 80px;
        height: 35px;
        background-image:url('/images/hello_world.png');
      }
    </style>
  </head>
  <body>
    <p>Hello World!</p>
    <div id="hello_world"></div>
  </body>
</html>

OK, you just wrote CSS to describe how a DIV element on the web page should look. Refresh your web browser again and you should see two Hello Worlds.

"Hello World" in JavaScript

Let's keep going and insert a block of JavaScript code that your web browser will run for us to print Hello World. Open back up your app/views/home/index.html.erb file and:


<!DOCTYPE html>
<html>
  <head>
    <title>Hello World!</title>
    <meta name="description" content="A very important announcement." />
    <style type="text/css">
      #hello_world{
        width: 80px;
        height: 35px;
        background-image:url('/images/hello_world.png');
      }
    </style>
  </head>
  <body>
    <p>Hello World!</p>
    <div id="hello_world"></div>
    <p><script type="text/javascript">
      document.write('Hello World');
    </script></p> 
  </body>
</html>

Save it and refresh your browser - you should see three Hello Worlds. Let's now move on to Ruby!

"Hello World" in Ruby

Let's fire up a quick irb (Interactive Ruby) session in the terminal (or cmd).


irb
>> @output = 'Hello World'
>> print "\n" + @output + "\n\n"
>> exit

In this example, you created a String instance variable named @output that contained the characters Hello World and told Ruby to print a newline, the contents of @output, and two more newlines. Now let's see how Ruby on Rails helps us do this to display in a web browser.

"Hello World" in Ruby on Rails

Let's open back up our app/views/home/index.html.erb file and add a couple lines


<!DOCTYPE html>
<html>
  <head>
    <title>Hello World!</title>
    <meta name="description" content="A very important announcement." />
    <style type="text/css">
      #hello_world{
        width: 80px;
        height: 35px;
        background-image:url('/images/hello_world.png');
      }
    </style>
  </head>
  <body>
    <p>Hello World!</p>
    <div id="hello_world"></div>
    <p><script type="text/javascript">
      document.write('Hello World');
    </script></p>
    <% @output = 'Hello World' -%>
    <p> <%= @output -%> </p>
  </body>
</html>

Ok, you should now see four Hello Worlds! Let's end with the grand finale, pulling in our announcement from the MySQL database table we created earlier.

"Hello World" in Ruby on Rails w/ MySQL

This may surprise you, but we only need to add one more line of code (demonstrating the power of Ruby on Rails) to our app/views/home/index.html.erb file!


<!DOCTYPE html>
<html>
  <head>
    <title>Hello World!</title>
    <meta name="description" content="A very important announcement." />
    <style type="text/css">
      #hello_world{
        width: 80px;
        height: 35px;
        background-image:url('/images/hello_world.png');
      }
    </style>
  </head>
  <body>
    <p>Hello World!</p>
    <div id="hello_world"></div>
    <p><script type="text/javascript">
      document.write('Hello World');
    </script></p> 
    <% @output = 'Hello World' -%>
    <p> <%= @output -%> </p>
    <p> <%= Announcement.first.body -%> </p> 
  </body>
</html>

Save and refresh your browser, and you'll see your 5 Hello Worlds (HTML, CSS, JavaScript, Ruby on Rails, & Rails w/ MySQL)!