Ruby on Rails in 2,057 Words

Web Languages
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

If you've been following the latest technologies and trends at all lately, you have undoubtedly encountered the phrase "Ruby on Rails" (also often referred to as "RoR" or just "Rails") and discussion about why it's the best technology in the world or whether it's just another over-hyped buzzword. Rest assured, Ruby on Rails is the real deal, and it's here to stay. Rails has definitely gained a lot of merit since its inception, and while it may or may not be the best fit for your next Web-based application, it is important that all Web developers and Web architects have at least a fundamental understanding of the features that Rails brings to the table.

Brief History of Ruby on Rails

A common misconception is that Ruby on Rails is by itself a single technology. It's not. It is important to understand that Ruby on Rails actually consists of two major technologies. The first component is called Ruby. Ruby, by itself, is "just" a programming language. Ruby was released to the general public in 1995 by its creator, Yukihiro "Matz" Matsumoto. Ruby has syntax similar to Perl and object-oriented features similar to Alan Kay's Smalltalk. Ruby is a strongly-typed (i.e., expressions such as "4" + 5 are illegal), single-pass interpreted language.

The second major component (and the cornerstone of the hype) of Ruby on Rails is Rails. Rails is a Web application framework written completely in the Ruby programming language (and hence the derived name, Ruby on Rails). A Web application framework is a set of tools and libraries that make it "easy" to create Web-based applications. The sad reality is that within most development projects, a sizeable amount of time is spent not solely on the application logic itself, but rather on a foundation and a set of reusable components for use throughout. It's these reusable artifacts that are collectively referred to as the application's framework; this is precisely where Rails can lend a helping hand. The Rails framework debuted nearly three years ago, in July of 2004. David Heinemeier Hansson, Rails' creator, actually created the Rails framework while working at 37signals on a project called Basecamp. He immediately saw the value in making the framework available to the public and released it as an open-source project for the world to take advantage of all the great things Rails has to offer.

Reduce Your Development Time

Does Rails provide any new function with respect to other technologies? Not really. However, it does allow you to accomplish the same tasks in potentially a fraction of the time. Rails offers the potential for teams to build a wide range of complex Web sites in weeks instead of months, without sacrificing quality of code. Rails promotes good programming practices, which leads to intuitive and easy-to-maintain code. Continue reading to experience the benefits of Rails.

Features and Benefits of Rails

Rails has many features that provably make a reduced development schedule and an easy-to-maintain project a reality. Some of its key benefits include these:

  • MVC framework—The Rails framework is an instance of the ever-popular MVC (Model-View-Controller) framework; it offers components to easily model your data, elegantly present it to the user, and simplify the interaction between the user and the model(s).
  • Fewer lines of code—Rails removes much of the tedious work (e.g., writing a heavy-weight data access layer or a transaction manager layer) from an application's framework and instead allows you to spend more time on your actual application logic.
  • Ruby gems—Ruby packages additional libraries in what's called a gem (e.g., Active Record, whose description is forthcoming, is a Ruby gem); this packaging system makes it easy to obtain new libraries and resolve dependencies between libraries.
  • Easy code testing—Since Rails ships with its own Web server for most platforms, you can easily write your code and immediately test it without having to go through lengthy deployment processes; Ruby also has full support for application breakpoints to aid in debugging.

Introduction to Ruby Gems

As mentioned, a Ruby gem is an additional component to the Ruby programming language. In the general sense, understanding and knowing which gems are available is what will lead you to successful projects; let the gems do the work for you! The following list offers high-level explanations of a small subset of the available Ruby gems.

Active Record

To quote the official definition, "Active Record is a Ruby gem that connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It is an implementation of the object-relational mapping (ORM)." In essence, this means you no longer need to spend your valuable time creating the ORM layer. In the J2EE world, this is where you'd normally spend countless hours creating Java beans and data access objects (DAOs). Rails simply waves goodbye. Active Record shields the need for SQL constructs within your application code but does support it for times when absolutely necessary. Per the Active Record documentation, some of its major features include these:

  • Automated mapping between classes and tables, attributes and columns
    class Person < ActiveRecord::Base; end

    ...gets automatically mapped to the "person" table below...

    CREATE TABLE person (
          id int NOT NULL,
          first_name varchar(63),
          last_name varchar(63),
          PRIMARY KEY(id)
    );
  • Associations between objects controlled by simple meta-programming macros
    class Patient < ActiveRecord::Base
          has_many :medical_records
          has_one :primary_physician
    end
  • Inheritance hierarchies
    class Animal < ActiveRecord::Base; end
    class Pet < Animal; end
    class Cat < Pet; end
  • Transaction support on both a database and an object level
    # Database-only transaction
    Account.transaction do
          david.withdrawal(100)
          mary.deposit(100)
    end

    # Data and object transaction
    Account.transaction(david, mary) do
          david.withdrawal(100)
          mary.deposit(100)
    end
  • Logging support for Log4r and Logger,which allows you to take a step-by-step look at what the data access layer is doing
    ActiveRecord::Base.logger = Logger.new(STDOUT)
    ActiveRecord::Base.logger = Log4r::Logger.new("Application Log")

As you can see from just some of the examples above, Ruby on Rails abstracts a lot of the typical data access logic so that you never need to work with the raw SQL and database structures. Again, this allows you to spend more time on your business logic than on primitive (with respect to the application) components.

Action Pack

Action Pack handles both the View and Controller parts of Rails. It splits a response to a Web request into a Controller part (performing the logic) and a View part (rendering a template). This is known as an "action," which will normally create, read, update, or delete (CRUD) a Model part before choosing to either render a template or redirect to another action. Action Pack implements these actions as methods on Action Controllers and uses Action Views to implement the template rendering. Action Controllers are then responsible for handling all the actions relating to a certain part of an application. Per the Action Pack documentation, these are some of its major features:

  • Simple URL routing—Incoming URL requests get mapped to an action within an Action Controller, which is a Ruby class that has a set of public methods that handle the particular action. As an example, if Rails received a request for http://yourco.com/statement/display/54, Rails would hand this request to StatementController::display(54) for processing.
  • View templates—View templates are essentially the HTML to give back to browser requests (think JSP files) and are stored with the rhtml filename extension. Text within <% %> is executable Ruby code, similar to that found in Java Server Pages (JSPs).
  • Helpers for forms, dates, action links, and text
    <% text_field "post", "title", "size" => 30 %>
    <% html_date_select(Date.today) %>
    <% truncate(post.title, 25) %>
  • Javascript and AJAX integration
    link_to_function "Greeting", "alert('Hello World!')"
    link_to_remote "Delete this post", :update => "posts",
                      :url => { :action => "destroy", :id => post.id
    }

Action Web Service

Action Web Service implements server-side support for SOAP and XML-RPC Web service protocols. It integrates with Action Pack so that you can easily publish APIs via the Web Service Definition Language (WSDL). For more information, please visit the official Rails Action Web Service page.

Action Mailer

Almost all of today's Web applications need to communicate with its users in some fashion, so it should be easy to achieve, right? Of course! Ruby's Action Mailer allows you to either send or receive email from within your application. Here's an example snippet of how to send an email message:

def send_message(user)
  recipients user.email_address
  subject "Greetings from Rails!"
  from This email address is being protected from spambots. You need JavaScript enabled to view it.
  body "Your first Rails email message."
end

No more writing 50 to 100 lines of code to simply send an email, as is necessary in some other languages! Although it's not covered here, Action Mailer makes it easy to send file attachments as well.

That's Great, But What Are Its Weaknesses?

As always, it's important to understand both a technology's strengths and its weaknesses. Rails, like any other technology, certainly has its weaknesses. I'd have to say Rails' biggest weaknesses is its relative (to competing technologies) immaturity. While it debuted nearly three years ago, it hasn't been deployed nearly to the extent of some of its competitors (J2EE, PHP, ASP, .NET, etc.) such that the technologies can be accurately compared. Depending on the type of project in which you're involved, its relative "immaturity" may or may not be a show-stopper; that's a decision you'll have to make. It's noteworthy that the number of business-class Web sites using Rails is constantly growing. In the future, we can surely expect to see a wealth of technological comparisons (backed by documented results) as well as a rich set of texts explaining how to deploy Rails applications in those "advanced" scenarios. The best piece of advice I can offer here is to simply study, download, install, and work with Rails to get a feel for how it will work for you.

Supported Environments

Ruby on Rails ships in either source or binary form and is supported on most major *nix platforms, OS X, and Windows. As noted directly on the official Ruby on Rails Web site, Rails works with a wealth of Web servers and databases. Recommended Web servers include Apache or lighttpd running FastCGI, SCGI, or Mongrel. To make things even easier, Rails ships with WEBrick, its own pure-Ruby Web server. This means you can simply download Ruby and immediately start creating your first Rails Web site without the hassle and overhead of configuring a Web server. Potential databases include MySQL, PostgreSQL, SQLite, Oracle, SQL Server, DB2, or Firebird.

In terms of development environments to work with Ruby code, surely any text editor will suffice, but there is also an excellent Eclipse-based plug-in available called RadRails that makes developing Rails applications even easier. Whether or not you're already an Eclipse user, if you're going to work with Rails, RadRails is definitely worth an evaluation.

The Rails Community

Since its inception, Ruby on Rails has been increasingly gaining notoriety, so a lot of public communities have spawned into existence. There are a variety of resources out there for Rails developers, including mailing lists for help, wikis containing a breadth of Rails information, IRC chat rooms for real-time discussion, and much more! While you can find these resources just about anywhere, an excellent starting point is the official Ruby on Rails community Web site. All of these resources and communities help foster the maturity of the Rails framework; developers from all over the world can share their ideas and experiences to help lead you to successful projects.

Try Ruby on Rails for Yourself

In no way have I come remotely close to touching on all that Rails has to offer, but hopefully I have convinced you that Rails is worth spending a few hours of your time to investigate. If writing less code with less room for mistakes on Web-related projects is what you're seeking, Rails is definitely worth giving a try. Where do you go from here? Well, the wealth of simple tutorials on the Web can introduce you to Rails development and allow you to experience the niceties and benefits firsthand. Who knows, the next time your boss asks you to throw together a Web site, you might be able to put something together in no time! Don't take my word for it, though; give Ruby on Rails a try for yourself.

Joe Cropper is a Software Engineer at IBM in Rochester, Minnesota. Joe works as part of the System i Software Final System Test team, and his areas of expertise include database, multi-tiered client-server technologies, and a variety of object-oriented programming languages. Joe can be reached via email at This email address is being protected from spambots. You need JavaScript enabled to view it..

BLOG COMMENTS POWERED BY DISQUS