6 min read

In this article, authors Elliot Smith and Rob Nichols explain the setup of a new Rails application and how to integrate it with other data sources. Specifically, this article focuses on turning the abstract data structure for Intranet into a Rails application. This requires a variety of concepts and tools, namely:

  • The structure of a Rails application.
  • Initializing an application using the rails command.
  • Associating Rails with a database.
  • The built-in utility scripts included with each application.
  • Using migrations to maintain a database.
  • Building models and validating them.
  • Using the Rails console to manually test models.
  • Automated testing of models using Test::Unit.
  • Hosting a project in a Subversion repository.
  • Importing data into the application using scripts.

In this article, we’ll focus on the first 3 concepts.

The World According to Rails

To understand how Rails applications work, it helps to get under its skin: find out what motivated its development, and the philosophy behind it.

The first thing to grasp is that Rails is often referred to as opinionated software (see http://www.oreillynet.com/pub/a/network/2005/08/30/ruby-rails-davidheinemeier-hansson.html). It encapsulates an approach to web application development centered on good practice, emphasizing automation of common tasks and minimization of effort. Rails helps developers make good choices, and even removes the need to make choices where they are just distractions.

How is this possible? It boils down to a couple of things:

  1. Use of a default design for applications-
    By making it easy to build applications using the Model-View-Controller (MVC) architecture, Rails encourages separation of an application’s database layer, its control logic, and the user interface. Rails’ implementation of the MVC pattern is the key to understanding the framework as a whole.
  2. Use of conventions instead of explicit configuration-
    By encouraging use of a standard directory layout and file naming conventions, Rails reduces the need to configure relationships between the elements of the MVC pattern. Code generators are used to great effect in Rails, making it easy to follow the conventions.

We’ll see each of these features in more detail in the next two sections.

Model-View-Controller Architecture

The original aim of the MVC pattern was to provide architecture to bridge the gap between human and computer models of data. Over time, MVC has evolved into an architecture which decouples components of an application, so that one component (e.g. the control logic) can be changed with minimal impact on the other components (e.g. the interface).

Explaining MVC makes more sense in the context of “traditional” web applications. When using languages such as PHP or ASP, it is tempting to mix application logic with database-access code and HTML generation. (Ruby, itself, can also be used in this way to write CGI scripts.) To highlight how a traditional web application works, here’s a pseudo-code example:

    # define a file to save email addresses into
    email_addresses_file = 'emails.txt'
    # get the email_address variable from the querystring
    email_address = querystring['email_address']
    # CONTROLLER: switch action of the script based on whether
    # email address has been supplied
    if '' == email_address
        # VIEW: generate HTML form to accept user input which
        # posts back to this script
        content = "<form method='post' action='" + self + "'>
        <p>Email address: <input type='text' name='email_address'/></p>
        <p><input type='submit' value='Save'/></p>
        </form>"
    else
        # VIEW: generate HTML to confirm data submission
        content = "<p>Your email address is " + email_address + "</p>"
        # MODEL: persist data
        if not file_exists(email_addresses_file)
            create_file(email_addresses_file)
        end if
        write_to_file(email_addresses_file, email_address)
    end if
    print "<html><head><title>Email manager</title></head>
    <body>" + content + "</body></html>"

The highlighted comments indicate how the code can be mapped to elements of the MVC architecture:

  • Model components handle an application’s state. Typically, the model does this by putting data into some kind of a long-term storage (e.g. database, filesystem). Models also encapsulate business logic, such as data validation rules. Rails uses ActiveRecord as its model layer, enabling data handling in a variety of relational database back-ends.
    In the example script, the model role is performed by the section of code which saves the email address into a text file.

  • View components generate the user interface (e.g. HTML, XML). Rails uses ActionView (part of the ActionPack library) to manage generation of views.
    The example script has sections of code to create an appropriate view, generating either an HTML form for the user to enter their email address, or a confirmation message acknowledging their input.

  • The Controller orchestrates between the user and the model, retrieving data from the user’s request and manipulating the model in response (e.g. creating objects, populating them with data, saving them to a database). In the case of Rails, ActionController (another part of the ActionPack library) is used to implement controllers. These controllers handle all requests from the user, talk to the model, and generate appropriate views.
    In the example script, the code which retrieves the submitted email address, is performing the controller role. A conditional statement is used to generate an appropriate response, dependent on whether an email address was supplied or not.

In a traditional web application, the three broad classes of behavior described above are frequently mixed together. In a Rails application, these behaviors are separated out, so that a single layer of the application (the model, view, or controller) can be altered with minimal impact on the other layers. This gives a Rails application the right mix of modularity, fl exibility, and power.

Next, we’ll see another piece of what makes Rails so powerful: the idea of using conventions to create associations between models, views, and controllers. Once you can see how this works, the Rails implementation of MVC makes more sense: we’ll return to that topic in the section Rails and MVC.

LEAVE A REPLY

Please enter your comment!
Please enter your name here