Learning Rails: Application Generation

Table of Contents

In the last two posts, I installed Rails on both the Debian and Windows boxes.  If you want to read about how I did it and the problems I had to solve then check those posts out.  Now that Rails is finally installed I am ready to start writing my URL shortener.

Rails is a Model, View, Controller, or MVC, architecture. The models represent the data, and are commonly tied to the database objects. Views define the user interface of the application. Controllers provide the business logic by processing the requests, interacting with the models and then passing the data to the views for rendering. The MVC architecture isolates the user interface from the business logic, helping to create more maintainable code.

Generate the Application

The rails command is the heart of the Rails environment. It is used to create new projects, generate code, and run and debug the application. To start a new Rails application I’ll use the rails new APPNAME command, which generates the skeleton of a new application in the APPNAME directory.

$ rails new njeni.us
 create
 create README
 create Rakefile
 ...snip...
 Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.
$ cd njeni.us

There are a lot of directories here, so I'll go over some of the important ones.
  • app – Contains the applications code. Most of the time will be spent in this directory.
    • assets – Contains the static content, like image, javascript and css files.
    • controllers – Contains the application controllers, the business logic of the application.
    • models – Contains the models used to represent the data.
    • views – Contains the views defining the user interface of the application.
  • config – Contains the application’s configuration files.
  • db – Contains the database schema and migrations.
  • public – Contains default HTML files available to the web server. The web server looks for files here first.
  • test – Contains int and functional tests.

When rails new generates a new Rails application, it comes ready to run right out of the box with its own web server. I’ll start it now and leave it running until I’m done for the day. Any code changes will be automatically loaded by the server, so I shouldn’t have to restart it.

$ rails server
=> Booting WEBrick
=> Rails 3.1.1 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2011-10-21 03:04:07] INFO  WEBrick 1.3.1
[2011-10-21 03:04:07] INFO  ruby 1.8.7 (2011-02-18) [x86_64-linux]
[2011-10-21 03:04:07] INFO  WEBrick::HTTPServer#start: pid=4309 port=3000

The web server runs on port 3000 by default.  I can fire up the web browser and navigate to http://localhost:3000/ to check it out.

Rails Start Page

Pretty cool! Clicking the About your application’s environment link displays some interesting information about the development environment.

Generate a Controller

Now I need a home page. The page currently being displayed is a static HTML page located at public/index.html. I could modify that, but that wouldn’t be very railsy(It’s a word!) of me. Instead, I’ll create a controller.

A controller is the user’s entry point to the application. When the user navigates to a URL, Rails attempts to route the request to an action on a controller. The controller represents a resource and the action identifies the operation being performed. Commonly, one of the operations a controller’s action performs is to render a view. (There’s the C and the V from MVC!)

To create my home page I can delete index.html and fire up the rails command again to have it automatically generate a controller for me.

$ rm public/index.html

$ rails generate controller home index
      create  app/controllers/home_controller.rb
       route  get "home/index"
      invoke  erb
      create    app/views/home
      create    app/views/home/index.html.erb
...snip...

The rails generate controller command creates a controller named home with one action named index, as well as the view required to display that action to the user. It also adds a route to the system so that Rails understands how to map a URL to that controller and action.

The new controller lives in app/controllers/home_controller.rb. Taking a look, I see it’s pretty simple.

class HomeController < ApplicationController
  def index
  end
end

All controllers inherit from ApplicationController(app/controllers/application_controller.rb) which in turn derives from ActionController::Base. Each public method in the controller defines an action. Each time a web request is made, Rails attempts to route the request to an appropriate controller and action. The controller is responsible for handling that request. If the action method is empty Rails will handle the request by simply outputting the view associated with the action.

By default, the route for a new controller and action take the form /CONTROLLER/ACTION, so I can navigate to http://localhost:3000/home/index to view my new action. However, this is the home page, so I really want the URL to be http://localhost:3000/, but navigating there gives an error.

No route matches [GET] "/"

To route "/" to my new index action, I need to edit config/routes.rb and add a route from the root of my application to my action.

NjeniUs::Application.routes.draw do
  get "home/index"

  root :to => "home#index"

Rails already added the default route for a new action to the file, get "home/index". To add a route for “/”, I can use the root method. The root method specifies where Rails should route requests for “/”. In this case, I want it to route to home#index.

Now, when I fire up the browser and go to http://localhost:3000/, Rails displays the view for the home#index action.

Default home#index view

Learn more about controllers and routing at Rails Guides.

Modifying the Views

All of the views are located in app/views under directories named after the controller. The view for the index action is app/views/home/index.html.erb. Files with the html.erb extension are html files that allow embedded Ruby. The Ruby is processed at runtime and an html file is built and sent back to the browser.

The default view isn’t very informative, so I will alter it a bit.


Welcome to njeni.us, a project created as part of the <em>Learning Rails</em>
series at <a href="http://naturaljenius.com/learning-rails/">Natural Jenius</a>.

The current time is <%= Time.new %>.

I added the <%= Time.new %> statement in there to play with the erb interpreter.  It should display the current time every time the page is viewed.

That makes a little more sense. But wait, where is the rest of the HTML, like the , and tags? When Rails renders a view, it is combined with a layout. Unless a more specific layout is created, Rails will use app/views/layouts/application.html.erb as the default layout. I’ll modify mine to change the title and add a header that will be displayed at the top of each page.

<!--<span class="hiddenSpellError" pre=""-->DOCTYPE html>
<html>
<head>
  <title>njeni.us</title>
  <%= stylesheet_link_tag    "application" %>
  <%= javascript_include_tag "application" %>
  <%= csrf_meta_tags %>
</head>
<body>
    <h1>njeni.us</h1>

    <%= yield %>

</body>
</html>

There’s the rest of the HTML. In a layout, the yield method will output the content of the view that is being rendered. Here’s what it looks like.

Finally, I want to clean up the style a bit. The CSS files are in app/assets/stylesheets. Application-wide CSS is in application.css, while each controller can also have its own CSS file. I’ll clean up the style of the site by changing the fonts and colors.

body {
        font-size: .75em;
        font-family: 'Lucida Grande', Tahoma, Verdana, Arial, Sans-Serif;
        background-color: #5E8CB6;
        color: white;
}
a { text-decoration: none; }
a:link, a:visited { color: #FF964C; }
a:hover { color: #ff6d00; }

That doesn’t look too bad.

Note: Read more about layouts and rendering at Rails Guides.

Summary

Today I created my new Rails application for njeni.us. I learned how to use the rails command to generate the application, controllers and views, as well as run the development web server. I dug into the directory and file structure, focusing on controllers, routing, views and assets. I didn’t write much code, but I got my feet wet.

This version of the application can be accessed at http://v0.01.njeni.us/. Take a look if you want to see what I ended up with.

Despite the installation issues, I’m enjoying Rails so far. Now that it’s installed everything seems to be going much more smoothly. The code generation and convention over configuration makes starting a new project simple.

Next time, I’ll look at models, databases and how to generate an entire resource. I’ll begin adding the basic URL shortening functionality to the application, and end up with a working bare-bones URL shortener.

Please leave a comment and let me know what you think of the series so far. I welcome any suggestions on how to improve the posts. Glowing praise is always accepted, too.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>