Ruby-on-Rails
  Home arrow Ruby-on-Rails arrow Page 2 - Web Development: Ruby on Rails
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
RUBY-ON-RAILS

Web Development: Ruby on Rails
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 4
    2007-03-22

    Table of Contents:
  • Web Development: Ruby on Rails
  • 15.1 Writing a Simple Rails Application to Show System Status
  • 15.2 Passing Data from the Controller to the View
  • 15.3 Creating a Layout for Your Header and Footer

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Web Development: Ruby on Rails - 15.1 Writing a Simple Rails Application to Show System Status


    (Page 2 of 4 )

    Problem

    You would like to get started with Rails by building a very simple application.

    Solution

    This example displays the running processes on a Unix system. If you're developing on Windows, you can substitute some other command (such as the output of a dir) or just have your application print a static message.

    First, make sure you have the rails gem installed.

    To create a Rails application, run the rails command and pass in the name of your application. Our application will be called "status".

      $ rails status
            create
            create   app/controllers
            create   app/helpers
            create   app/models
            create   app/views/layouts
            create   config/environments
      ...

    A Rails application needs at least two parts: a controller and a view. Our controller will get information about the system, and our view will display it.

    You can generate a controller and the corresponding view with the generate script. The following invocation defines a controller and view that implement a single action called index. This will be the main (and only) screen of our application.

      $ cd status
     
    $ ./script/generate controller status index
            exists  app/controllers/
            exists  app/helpers/
            create  app/views/status
            exists  test/functional/
            create  app/controllers/ status_controller.rb
            create  test/functional/ status_controller_test.rb
            create  app/helpers/ status_helper.rb
            create  app/views/status/ index.rhtml

    The generated controller is in the Ruby source file app/controllers/status_ controller.rb. That file defines a class StatusController that implements the index action as an empty method called index. Fill out the index method so that it exposes the objects you want to use in the view:

      class StatusController < ApplicationController
       
    def index
          # This variable won't be accessible to the view, since it is local
          # to this method
          time = Time.now

          # These variables will be accessible in the view, since they are
          # instance variables of the StatusController.
          @time = time
          @ps = `ps aux`
       
    end
      end

    The generated view is in app/views/status/index.rhtml. It starts out as a static HTML snippet. Change it to an ERb template that uses the instance variables set in StatusController#index :

      <h1>Processes running at <%= @time %
    ></h1>
      <pre><%= @ps %></pre>

    Now our application is complete. To run it, start up the Rails server with the following command:

      $ ./script/server
      => Booting WEBrick...
      => Rails application started on http://0.0.0.0:3000
      => Ctrl-C to shutdown server; call with --help for options
      ...

    You can see the application by visiting http://localhost:3000/status/.

    Of course, you wouldn't expose this application to the outside world because it might give an attacker information about your system.

    Discussion

    The first thing you should notice about a Rails application is that you do not create separate code files for every URL. Rails uses an architecture in which the controller (a Ruby source file) and a view (an ERb template in an .rhtml file) team up to serve a number of actions. Each action handles some of the URLs on your site.

    Consider a URL like http://www.example.com/hello/world. To serve that URL in your Rails application, you'd create a hello controller and give it an action called world.

      $ ./script/generate controller hello world

    Your controller class would have a world method, and your views/hello directory would have a world.rhtml file containing the view.

      class HelloController < ApplicationController
       
    def world
       
    end
     
    end

    Visiting http://www.example.com/hello/world would invoke the HelloController#world method, interpret the world.rhtml template to obtain some HTML output, and serve that output to the client.

    The default action for a controller is index, just as the default page in a directory of a static web server is index.html. So visiting http://www.example.com/hello/ is the same as visiting http://www.example.com/hello/index/.

    As mentioned above, a view file is only the main snippet of the final page served by Rails. It's not a full HTML page, and you should never put <html> or <body> tags inside it (see Recipe 15.3). Since a view file is an ERB template, you should also never call puts or print inside a view. ERB was introduced in Recipe 1.3, but it's worth exploring here within the context of a Rails application.

    To insert the value of a Ruby expression into an ERB template, use the <%= %> directive. Here's a possible world.rhtml view for our hello action:

      <p>Several increasingly silly ways of displaying "Hello world!":</p>

      <p><%= "Hello world!" %></p>
      <p><%= "Hello" + "world!" %></p>
      <p><%= w = "world"
            
    "Hello #{w}!" %></p>
      <p><%= 'H' + ?e.chr + ('l' * 2) %><%=('o word!').gsub('d', 'ld')%></p>

    The last example is excessive, but it proves a point. You shouldn't have to put so much Ruby code in your view template (it should probably go into your controller, or you'll end up with sloppy PHP-like code), but it's possible if you need to do it.

    The equals sign in the ERb directive means that the output is to be printed. If you want to execute a command without output, omit the equals sign and use the <% %> directive.

      <% hello = "Hello" %>
      <% world = "world!" %>
      <%= hello %> <%= world %>

    A view and a controller may be based on nothing more than some data obtained from within Ruby code (like the current time and the output of ps aux ). But most real-world views and controllers are based on a model: a set of database tables containing data that the view displays and the controller manipulates. This is the famous "Model-View-Controller" architecture, and it's by no means unique to Rails.

    See Also
    1. Recipe 1.3, "Substituting Variables into an Existing String," has more on ERB
    2. Recipe 15.3, "Creating a Layout for Your Header and Footer"

    More Ruby-on-Rails Articles
    More By O'Reilly Media


       · This article is an excerpt from the "Ruby Cookbook," published by O'Reilly. We hope...
     

    Buy this book now. This article is excerpted from chapter 15 of the Ruby Cookbook, written by Lucas Carlson and Leonard Richardson (O'Reilly, 2006; ISBN: 0596523696). Check it out today at your favorite bookstore. Buy this book now.

    RUBY-ON-RAILS ARTICLES

    - Iterating and Incrementing Strings in Ruby
    - Comparing and Manipulating Strings in Ruby
    - Strings in Ruby
    - Ruby On Rails: Making Your First Dynamic Site
    - Ruby on Rails: Beginning Rails
    - Ruby: Modules, Mixins, Fixins, and Rails
    - Controlling Information Access with the Rail...
    - URLs, Filters and the Rails Action Controller
    - Flash and the Rails Action Controller
    - Rails Action Controller
    - Dropping and Sorting with AJAX and script.ac...
    - Drag and Drop with script.aculo.us and Rails
    - Introducing script.aculo.us
    - Ruby Classes and Objects
    - Ruby Loops






    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway
    Stay green...Green IT