ONLamp.com
oreilly.comSafari Books Online.Conferences.

advertisement


What Is Ruby on Rails
Pages: 1, 2, 3, 4, 5, 6, 7

URL routing

An incoming URL always maps to some action within a controller. A controller is simply a Ruby class, and each action implemented by the controller is a public method within the controller class. The default mapping from URL to action method is (in "Rails-speak"):

/:controller/:action/:id

This is easiest to explain by an example. If Rails received the URL http://myapp.com/invoices/show/37, Rails would route this to a controller class named InvoicesController and within that class to a method named show. Rails would also pass the 37 to the method as the id member of the parameter hash that also holds the values of query parameters and form fields. The code might look like this:

class InvoicesController
  def show
    @invoice = Invoice.find(params[:id])
  end
end

Because actions are methods grouped within a controller (instead of separate command objects), they can easily share helper methods.

If the default URL routing does not meet your needs, you can easily specify your own routing rules, even using regular expressions. Because Rails implements its own URL routing, you don't need to mess with Apache's mod_rewrite, and your routing rules will work the same under all web servers.

Rails routing rules are Ruby code. Here is an example:

map.connect 'date/:year/:month/:day',
     :controller => 'blog',
     :action => 'by_date',
     :month => nil,
     :day => nil,
     :requirements => {:year => /\d{4}/,
                       :day => /\d{1,2}/,
                       :month => /\d{1,2}/}

With this routing rule, the following URLs are valid:

http://myblog.com/date/2005
http://myblog.com/date/2005/08
http://myblog.com/date/2005/08/01

This rule decomposes a URL containing a date that, perhaps, a blog might use to display the postings for a particular date. A URL that matches this form will map to the BlogController class and the by_date method. The parameter hash will contain values for a four-digit year (/\d{4}/ is a Ruby regular expression), a two-digit month, and a two-digit day. Further, the month and day are optional; if no values are present, the parameter hash will contain the default value of nil.

See the Routing in the Rails manual to learn more.

Filters

Filters allow you to run preprocessing code before Rails executes an action and post-processing code after it completes an action. They are useful for such things as caching or authentication before calling the action, and compression or localization of the response after calling an action. The before_filter processing can either allow the action to be called normally by returning true, or abort the action by returning false (or by performing a render or redirect operation).

For example:

class BankController < ActionController::Base
  before_filter :audit

  private
    def audit
      # record the action and parameters in an audit log
    end
end

class VaultController < BankController
  before_filter :verify_credentials

  private
    def verify_credentials
      # make sure the user is allowed into the vault
    end
end

The ActionController::Filters documentation has more details.

Helpers

Helpers are smart methods (functions) that help your view templates generate HTML. They know to use your model objects and controller classes to create just the right HTML and, in the process, save you a lot of time and effort. Of course, this also means you write fewer lines of code, but I bet you already guessed that.

You can write your own helpers, but as you might expect, several come built into Rails. The link_to helper, for example, generates anchor tags that create links to controllers and actions. For example:

<%= link_to "Help", { :action => "help" } %>

creates a link to the help action (method) in the current controller (whatever controller is handling the current request). The text of the link (what the user sees) is Help.

<%= link_to "Master Help Index",
           { :controller => "help", :action => "index" }
%>

This creates a link to the index method in the HelpController class. The text of the link will be Master Help Index.

<%= link_to "Delete this invoice",
           { :controller => "invoices",
             :action => "delete",
             :id => @invoice.id },
             :confirm => "Are you sure you want to delete this?"
%>

This creates a link to the delete method in the InvoicesController class, and passes an id parameter (presumably the ID of the invoice to delete). This also uses a special confirm option that creates JavaScript to pop up a confirmation dialog letting the user continue or abort.

There is a substantial set of helpers for creating form fields to display and update values in your Active Record model objects, which effectively means values in your database. Assume that your database has a people table with columns for the name, the password, a description, and a Boolean value to indicate whether the person is single or married (OK, so this is a strange table--just humor me). Here's a partial view template with a sampling of form tags that could be used. (Assume that the variable @person contains a person object read from a row of the people table.)

<form action="save_person" method="post">
  Name:
  <%= text_field "person", "name", "size" => 20 %>

  Password:
  <%= password_field "person", "password", "maxsize" => 20 %>

  Single?:
  <%= check_box "person", "single" %>

  Description:
  <%= text_area "person", "description", "cols" => 20 %>

  <input type="submit" value="Save">
</form>

That code generates the following HTML:

<form action="save_person" method="post">
  Name:
  <input type="text" id="person_name" name="person[name]" size="20" value="<%= @person.name %>" />

  Password:
  <input type="password" id="person_password" name="person[password]"
         size="20" maxsize="20" value="<%= @person.password %>" />

  Single?:
  <input type="checkbox" id="person_single" name="person[single] value="1" />

  Description:
  <textarea cols="20" rows="40" id="person_description"
           name="person[description]">
    <%= @person.description %>
  </textarea>

  <input type="submit" value="Save">
</form>

There are helpers to create the option tags for a select list from a collection of rows read from the database; helpers for working with dates, numbers, and currency; and much more.

There are different categories of built-in helpers, in several actual files. To learn more about them, see:

Pages: 1, 2, 3, 4, 5, 6, 7

Next Pagearrow





Sponsored by: