Quantcast
Channel: Building Web Apps
Viewing all articles
Browse latest Browse all 27

Lab 1. Set-Up and Static Pages

$
0
0

In this lab, you’ll create a new Rails site from scratch, building it up step by step until you have a four-page site with navigation. This creates the basis upon which all the other labs build.

1. Set-up development environment

The instructions below assume you have the following software installed:

  • Ruby 1.8.6
  • Rails 2.0.2
  • MySQL database server
  • NetBeans 6.0.1

You can use another editor or IDE, but then you’re on your own for the specifics of how to accomplish these tasks. We will, however, provide the command-line alternative to each of the NetBeans Rails commands.

If you are using NetBeans, you must have it configured to use your native Ruby interpreter, and not JRuby.

2. Create your Rails project and its associated databases

a. Create your local database

To create your database using the MySQL command-line client, type

	mysql --u root

in a terminal window. (Note: if you installed MySQL using macports, you’ll probably have to type mysql5 instead of mysql.) This assumes this is a new database server installation and you haven’t set a root password. If you have set a root password, enter

	mysql --u root --p

and it will prompt you for the password.

You should now have a >> prompt, which indicates that you’re in the MySQL monitor. Enter the following commands at this prompt:

	create database labs_development;
	grant all on labs_development.* to 'seminar'@'localhost' identified by 'seminar';

The first command creates the database, and the second command creates the user “seminar” with the password “seminar”.

You don’t need this quite yet, but while you’re at it you might as well create the test database, which is used for running tests:

	create database labs_test;
	grant all on labs_test.* to 'seminar'@'localhost' identified by 'seminar';

Finally, you can create a production database if you’d like, in case you later want to try running in production mode on your development machine:

	create database labs_production;
	grant all on labs_production.* to 'seminar'@'localhost' identified by 'seminar';

b. Create a Rails project

If you’re using NetBeans, Choose File > New Project > Ruby on Rails Project and enter “labs” as the name of the project. By default, NetBeans will create a folder called NetBeans Projects in your home folder, and then within that it will create a folder that matches the name of the project. You can change this if you want, but these defaults should be fine. Make sure that the MySQL database is selected.

When you click Next, unless you’ve updated to a newer version of NetBeans, it is likely to tell you that you have Rails 1.2.6, and that your gems are unavailable. Don’t worry, this is a NetBeans bug.

When you click Finish, you should see a bunch of file creation commands scroll by in the Output window (if that window isn’t visible, choose Window > Output > Output), and now in the Project pane on the left you should see your new project with all of its components.

Note that the NetBeans Projects tab does not show the literal folder structure, but rather a conceptual structure that is somewhat flattened relative to the actual folder structure and has more explicit names (e.g., Configuration instead of config). Switch to the Files tab to see the actual folder structure.

If you’re working from the command line instead, make a folder for your Rails project, change directory (cd) into that folder, and type:

	rails -d mysql labs

c. Configure your Rails project to use your database

Open the file database.yml in the config folder (Configuration if you’re in the NetBeans project view).

In the section that starts with “development:”, change the username from root to seminar, and the password from blank to seminar. Make the same changes in the test and projection sections.

We suggest also deleting the socket: line from the database.yml file from each of the three sections.

d. Run the application

You now have a new, empty Rails application. To run the application, if you’re using NetBeans, right-click on the project name in the Projects pane and choose Run. If you’re working from the command line, make sure you’re in the project’s folder, and enter “ruby script/server”. (If you’re using a Mac or Linux system, you can omit the word “ruby” in all such commands, but it won’t hurt, and is required on Windows.)

Now open your browser and enter http://localhost:3000 (that’s port number 3000 on the local server, which goes by the alias localhost). You should see the standard Rails “Welcome Aboard” page. (If not, look at the log in the output window to see what the error messages are.)

In the Welcome Aboard page in your browser, click on the link “About Your Application’s Environment”. You should see a list of versions that shows that you have Ruby 1.8.6 and version 2.0.2 of the various Rails components.

If you see an error message, it probably means that either your database server is not running, or you didn’t create the labs_development database, or you didn’t create the seminar user with the seminar password, or you didn’t edit the database.yml file properly.

Assuming all is well, now you want to get rid of this welcome page, because from this point forward it will only get in your way. Delete the file index.hmtl in your application’s “public” folder. (Or rename it to something like index.html.old if you want to be able to restore it for old time’s sake.)

Now refresh the page in your browser and you should see:

	Routing Error

	No route matches "/" with {:method=>:get}

Congratulations! You’ve gone to a lot of trouble to create an application that does absolutely nothing except display an error message.

But actually you’ve done a great deal. You now have all the infrastructure in place for your Rails application. Now the fun starts, and you’ll be able to start adding real pages very quickly.

This error message is Rails’ way of saying that it doesn’t know what it is supposed to do when you access the root page of your site, because we haven’t defined anything yet and we’ve taken away the default index.html page.

3. Creating your first pages

a. Creating your first controller and views

We’re going to start by doing the absolute minimum of work required to create a few static web pages within the Rails structure. As we progress through the lessons, we’ll evolve these to more sophisticated versions that are more representative of good Rails design practices.

We’re going to create a site with four pages:

  • Home
  • About Us
  • Contact Us
  • Resources

To do so, we need a controller, which we’re going to call “static” because we’re using it to access these static pages. Each of the four pages will be created by one action in this controller and its corresponding view.

If you’re using NetBeans, right-click on the name of the project in the Projects pane and choose Generate. The Rails Generator dialog opens, and it defaults to the “controller”, option, which is what we want. Enter “static” for the name, and in the Views field enter “home about contact resources”. Click OK, and the generator will create the controller and open it in the editor.

(If you’re not using NetBeans, enter “ruby script/generate controller static home about contact resources” in a terminal window, at the root of your application.)

In the file static_controller.rb, you’ll see four empty methods, one for each action. We can leave them empty for now.

Now look in the Views folder (inside the apps folder if you’re not in the NetBeans project view), and you’ll find a new folder called “static”, and inside that you’ll find the four view files for the pages we’ve defined.

To see the changes in the browser, you need to first stop and then restart the server. Using NetBeans, click the red X in the the output window labeled “Mongrel for labs on 3000” and then click the green double arrow. (If you’re using the console. type control-C to stop the server and then reissue the script/server command.)

Now click the refresh button in the browser. Still an error message! That’s because Rails doesn’t know which of these pages is our home page. We’ll fix that in a minute.

To see the home page, enter this URL:

	http://localhost:3000/static/home

That tells Rails we want it to run the home action in the static controller. You should now see a page with this exciting content:

	Static#home
	Find me in app/views/static/home.html.erb

That’s the default text Rails puts in the empty view file. Open the file views/static/home.html.erb, and you’ll see the HTML that created this page.

You can replace that HTML with whatever you’d like, perhaps:

<h1>Welcome to RailsQuickStart</h1>
	<p>This is the home page</p>

Now you can refresh the page and you should see the new text. You can do the same for the other three pages, editing their view files, and entering the corresponding action name in the URL to access them.

b. Adding a layout

If you view the source of one of these pages in your browser, you’ll notice that they aren’t well-formed HTML. There’s no doctype, no head section, and so forth — just the raw HTML for the page. We could add that in each view, but that would involve a lot of repetition.

A layout file is the answer. Every view gets wrapped in a layout, so the view only needs to provide the information that is unique to that page.

In your Views folder, you’ll see an empty folder called “layouts”. In the NetBeans projects pane, right-click on layouts, choose New > ERB file, and name the file application.html. NetBeans will append the .erb suffix. (If you’re using another editor, you’ll probably need to specify the full filename, application.html.erb.) This layout file will be used by default for all views, unless there is another layout specific to that controller.

Here’s a minimal HTML wrapper you can paste into that file (first delete the useless boilerplate code that NetBeans inserts):

<?xml version="1.0" encoding="UTF-8"?>
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml">
	    <head>
	        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
	        <title>Page Title Goes Here</title>
	    </head>
	    <body>
	        <p>
	            <%= yield %>
	        </p>
	    </body>
	</html>

This is just standard HTML, with the exception of a single line of ERb code:

<%= yield %>

This line tells Rails that it should insert the code for the current view at this point.

Now you can refresh the browser page, and it should look just the same, except that “Page Title Goes Here” appears in the browser’s title bar. If you view the source, you’ll see that there’s now a proper HTML structure, courtesy of our layout.

c. Add basic navigation links

Now we need a way to navigate to each of our pages without having to enter the full URL. First, let’s add some simple navigation links, using an HTML list (which we’ll style a little later).

Insert the following code in layouts/application.html.erb, immediately after the <body> tag.

  • <%= link_to ‘Home’, {:controller => ‘static’, :action => ’home’} >
  • <= link_to ‘About Us’, {:controller => ‘static’, :action => ’about’} >
  • <= link_to ‘Contact Us’, {:controller => ‘static’, :action => ’contact’} >
  • <= link_to ‘Resources’, {:controller => ‘static’, :action => ’resources’} %>

Now refresh the page in the browser, and you’ll see four ugly links, which at least allow us to easily navigate to each of the four pages.

d. Make the root URL work, and clean up the others

Now we can get to each of the pages, but we still get an error if we try to just browse to the root of the site. Let’s fix this.

Open the file config/routes.rb (in the Configuration folder in the NetBeans project pane). This default file is mostly full of comments that give you some hints about how to add routes, plus two default routes at the end. The first of those default routes is what has been enabling us to navigate to our pages.

To make our home view work as the site’s home page, add the following line immediately above the first default route (so your new line is now the first uncommented line):

     map.root :controller => "static", :action => "home"

This tells Rails that the root, or home, page of our site is accessed via the home action in the static controller. Save the routes.rb file, and now you should be able to browse to //localhost:3000 and see the home page.

There’s one more bit of cleanup we’ll do while we’re in the routes file. Note that when you click on the links to browse to the other pages, you still see /static/ before the page name. This is ugly, and there’s no need for us to expose the name of our controller to our visitors. Add this line immediately below the map.root line you just added:

     map.connect ":action", :controller => "static"

This tells Rails that if there is only a single word after the host name, then it should use that word as the name of the action, and assume that the controller is “static”.

Save the file, and now when you click on the links for each of the pages, you should see the simpler URL without the word “static”.

e. Add a stylesheet

Now it’s time to make this all a little prettier by adding a CSS stylesheet. You can use any stylesheet you’d like, but to follow along with our example, grab the file “quickstart.css” (it’s in the example code for any of the labs, or right-click here and choose Save Link As…) and save it in the folder /public/stylesheets.

Now you need to add a tag to tell the browser to use this stylesheet. Insert the following line in the head section of layouts/application.html.erb:

<%= stylesheet_link_tag 'quickstart.css' %>

Note that you don’t need to specify that this file is in the stylesheets folder; Rails assumes that by default.

If you refresh the browser now, you should see that the fonts have changed, but it’s still just as ugly. We need to add some divs in the layout to tell the browser what styles to apply. This is just regular HTML/CSS stuff, nothing to do with Rails.

Just grab the updated layout file from the “labs2_end” sample application code (or right-click here and choose Save Link As…). This layout provides a “pagewrapper” div to give the content a defined width and center it; “header” and “navbar” divs for the top of the page; and a “footer” div for the bottom of the page.

The updated layout also adds an id tag to the navigation list, which we’ll explain in the next section.

With the new application layout in place, refresh the browser, and you should finally have something that looks almost like a respectable, if extraordinarily simple, web site.

f. Adding in page titles

All of our pages have the same HTML title (which appears in the browser’s title bar), which isn’t good. Let’s fix that.

When we slipped in the new layout file in the previous section, the title tag in the head section was changed to this:

<title>RailsQuickStart: <%= @page_title %></title>

This provides the text “RailsQuickStart:” as the start of the title for every page, follow by a bit of ERb code that simply inserts the value of the @page_title instance variable. Now we need to set that variable somewhere.

You might think that the natural place to do this would be in the view files, but that won’t work; the layout has already rendered the head section of the page by the time it gets to the view file. So we need to set it in the controller.

So far, all of our controller actions are empty. Now add one line to the home action so it looks like this:

	def home
		@page_title = "Welcome"
	end

and make similar changes to the other three actions. Save the file, and now browse to each of the pages. You’ll see the appropriate titles now appear in the browser’s title bar.

g. Make the navigation buttons highlight

We’re almost done. There’s just one little improvement to make. It would be nice if the navigation buttons highlighted to show which page we’re on.

A standard CSS technique to make this happen is to use a descendant selector. We apply an id to the navigation ul element, with the value of the id indicating the current page. We’ve also added an id to each of the navigation links. A CSS rule highlights the navigation link if the navigation link’s parent has an id that corresponds to the link:

	#home_tab a#home_nav, #about_tab a#about_nav, #subscribe_tab a#subscribe_nav, #resources_tab a#resources_nav, #contact_tab a#contact_nav {
	    background-color: #333;
	}

This is just standard CSS, nothing to do with Rails. But we need to somehow change the id for the ul tag that wraps the navigation list, depending on which page we’re on.

This change has already been slipped in to the layout file we swapped in a couple steps ago. The tag that starts the list looks like this:

<ul id="<%= @current_tab %>">

This sets the id for the ul element to the value of the instance variable @current_tab. Now we just need to set that in static_controller, just as we did for the page title. So the controller now looks like this:

	def home
    @page_title = "Home"
    @current_tab = "home_tab"
  end

  def about
    @page_title = "About Us" 
    @current_tab = "about_tab"   
  end

  def contact
    @page_title = "Contact Us"
    @current_tab = "contact_tab"
  end

  def resources
    @page_title = "Resources"
    @current_tab = "resources_tab"
  end

Now the tabs stay highlighted to indicate the page we’re on.

It may seem clumsy to have to set the tab and the page title in the controller like this, especially since they’re really aspects of the view. In a more elaborate design, we could pull these values from a database, so they could be set by a non-technical site administrator and didn’t clutter up the controller. But for now, this is the simplest way to do it.

Moving On

That concludes Lab 1. You now have a simple static site, which makes use of a few little bits of Ruby to set and use instance variables, and also uses a layout file to provide the parts that are common to all pages. This gives us a core structure that we can easily extend in the later labs.


Viewing all articles
Browse latest Browse all 27

Trending Articles