What Gems Does Ruby on Rails Offer?

Article ID: 21076

Look at nearly any trade press magazine these days, and chances are that you'll see some mention of Ruby or Ruby on Rails. Based on the popular object-oriented (OO) language Ruby, Rails provides a Model-View-Controller (MVC)-style web application framework. Rails also sports a built-in database, web server, and application generator, which makes it a convenient all-in-one development environment.

But web development environments abound these days. What makes Rails different, and why should we care? Examining the Ruby on Rails philosophy will help you determine whether the hype is warranted — and how you might employ Rails in your own application development efforts.

For System i developers, native Ruby on Rails is on the horizon. Rails for AIX and DB2 adapters are available, and websites are popping up announcing the availability of Rails installation instructions for Portable Application Solutions Environment (PASE). (Find Out More, below, lists many resources for Ruby on Rails, as well as related tools and information.) You can easily get started on Rails by developing right on your desktop machine. You can also run Rails on an i5/OS Linux partition. This article offers an overview of Rails and gives you some hands-on experience with the desktop Rails development environment, which should let you better evaluate Ruby as a web programming alternative.

What's Unique About Ruby and Ruby on Rails?

"A breakthrough in lowering the barriers of entry to programming." "Web Development that doesn't hurt." "Reduce mundane and repetitive tasks." "Produce code ten times faster." "Build an application in 15 minutes." These are just some of the claims that promoters of Ruby on Rails make. What is the basis for these claims? Is it all hype? Let's dig in to find out.

Ruby is a free OO programming language created by Japanese programmer Yukihiro "Matz" Matsumoto in 1995. His goal was to create a scripting language as powerful as Perl but more OO than Python. This is a good short description of Ruby as it exists now. The name Ruby was chosen simply because it was the birthstone of a co-worker who tried to convince Matz that Perl is a handy programming language. The original concept of Ruby on Rails came from David Heinemeier Hansson as he designed and redesigned Basecamp, a web-based project management application, for a company called 37signals. Heinemeier Hansson is now a partner at 37signals. The first public release of Rails was in July 2004.

As with other OO programming languages, Ruby programmers think in terms of which objects should be in a system and what operations these objects perform. Like Smalltalk, Ruby aids iterative development by dint of its dynamic, interactive programming environment that requires no compilation step. Unlike Smalltalk, however, Ruby has no persistent runtime environment. Each time you launch a Ruby program, it starts with a clean slate. This behavior turns out not to be a limitation in web application development, where Ruby runs exclusively on the server side.

Ruby on Rails is an open-source application development environment that generates web applications using Ruby for server-resident code. Ajax, JavaScript, and CSS are used to customize the browser experience, and asynchronous HTTP is used to encapsulate the application as a single web page. Rails is the reason behind many of the productivity claims that I mentioned earlier. Rails standardizes many steps in web-based application development. It generates scaffold code for each application rather than requiring developers to build basically the same things over and over for each website application that they create.

Webcast demos of Ruby on Rails promote the productivity of Rails, demonstrating the creation of a working Ruby and MySQL application in less than 15 minutes. I can't promise that level of productivity, but in this article, I include a step-by-step tutorial that lets you "ride the rails" by building an application.

Fostering Pretty Good Practices

Ruby on Rails encourages good programming practices by automating several battle-proven programming paradigms:

Reuse. Rails is a framework that enables the reuse of web application code and design patterns, reducing programmer workload and the opportunities for errors.

MVC architecture. Rails has an MVC architecture, encouraging applications to keep data (the model) separate from operations on that data (the controllers) as well as the presentation of that data (the view). In other words, the business logic is separate from data and presentation. When you run Rails, you'll notice that the scaffolding code that Rails generates creates a folder structure that includes models, views, and controllers folders.

Data modeling. Rails uses the Active Record design pattern to define the relationship between the database and Ruby objects. It reads the skeleton database tables that the developer maps out in Ruby syntax to create database tables and the appropriate default actions. These actions are playfully called CRUD (Create, Retrieve, Update, Destroy). By defining objects through Ruby syntax, maintainers understand the data and how objects relate, developers are not tied to a specific database type, and the code generation can speed up application creation. The demonstration herein exemplifies this modeling when we declare that MyUrl belongs_to_many :mygroups.

Testing. Rails also encourages testing in two ways. First Rails uses the convention of having development, test, and production environments and makes promoting code from one environment to another easy. Second, Ruby has a concept of test-first programming, a convention in which a structure exists such that test cases can be written as code is iteratively developed (I'll save test-first programming as a topic for a future article).

MyURLs: A Ruby on Rails Application Demonstration

To show how easy Rails can be to use, I've created a demonstration application with which you can experiment. You create a Rails application called MyURLs, which lets you retrieve a URL saved in one browser — at your office, for example — from another browser at a remote location, such as an Internet café. The demo is quick and easy to run and yet results in a useful product.

MyURLs creates a simple database that lets you add your favorite URLs, save some information about those URLs and, because it is a web-based application, access this database from other systems. (I'm not going to take credit for the idea of MyURLs. There are similar useful websites out there, such as del.icio.us, but MyURLs shows how Rails can make you productive quickly and lets you save that data to your own server.)

Let's begin by creating a model of the objects involved in the MyURLs system. We'd like a MyUrl object that has a few attributes:

  • URL
  • Ranking (so we can adjust the display order)
  • Notes (e.g., to remember why we like this URL)
  • Grouping (so we can view URLs on a specific subject)
  • Date-Added (another sorting/memory-jogger possibility)

We also want to group similar URLs for convenient retrieval, so we need a MyGroup object with a single attribute:

  • Name (word or phrase to group like URLs)

To provide a feel for Ruby on Rails in the least amount of magazine space, this demo is based on Instant Rails (instantrails.rubyforge.org) running on Windows XP. Instant Rails simplifies the installation process of Ruby and Ruby on Rails because it also includes Apache, MySQL, and phpMyAdmin. If you decide that you are done with Rails, you can uninstall Instant Rails, and all these applications get removed in one step.

Here is the process for creating the MyURLs demo:

  1. Install Instant Rails in c:\rails (you'll have to create the directory c:\rails).


  2. In a DOS window, change directory (cd) to c:\rails\instantrails and run the command instantrails.exe. The Instant Rails GUI appears (Figure 1).


  3. Click the I button and choose Rails|Manage Rails Apps, then click the Create New Rails App button.


  4. A DOS prompt appears and is set to the directory c:\rails\instantrails\rails_apps. Type "rails MyURLsProject" and press Enter. At this point, Rails creates directories that hold the conventional Rails application code (Figure 2).


  5. Create a MySQL database called myurlsdb_dev by running these commands from the DOS prompt (i.e., the prompt started from Instant Rails earlier):
  6. mysql -u root
    create database myurlsdb_dev;
    
    grant all on myurlsdb_dev.* to user4rails;
    quit
    (Rails assumes that you have development, test, and production databases, but this demo uses only the _dev database.)

  7. Configure Rails so it can access the database. Using your favorite text editor (e.g., Notepad), edit the file myurlsproject\config\database.yml. Insert the database name and the user user4rails (the demo uses no password). Add the red text to the lines as indicated:
    development:
       adapter: mysql
       database: myurlsdb_dev  
       username: user4rails  
       password:
       host: localhost 
  8. Start the rails server. Click the Instant Rails I button, then choose Rails Applications|Manage Rails Application. Select our application, MyURLsProject, and choose Start with Mongrel (I haven't mentioned Mongrel — it is a web server included with Instant Rails).


  9. Point your browser to http://localhost:3000. You should see the Rails Welcome screen (Figure 3).


  10. From the DOS window, cd to the MyURLsProject directory.


  11. Next, define the model files for the group and url objects. I had conflicts with reserved words in Rails, so I decided to include a prefix of "my" on the objects. Create the model files by running these commands:
    ruby .\script\generate model mygroup
    ruby .\script\generate model myurl
  12. Rails has a feature called Migration, which lets Rails users define Rails databases in Ruby syntax. Rails does the database table creation. Migration lets you back out changes to your database. To fill in the skeleton model files, first update the db\migrate\001_create_mygroups.rb file. Our group objects are simple — all we need to do is include the group name. Do this by adding the following red line to the file where indicated:
  13. create_table :mygroups do |t|
           t.column :name, :string
       end
    To "unmigrate" a database and revert back to a previous version, run this command:
    rake migrate version=0
  14. Next, fill in the actual model file that defines the relationship between objects. Specify this in the following in the app\models\mygroup.rb file:
    has_many :myurls
  15. Edit the migration file for the MyUrls table (db\migrate\002_create_myurls.rb). Thus far, we have been describing our database files with Ruby syntax, but in this step, we add actual SQL statements because Rails cannot automatically generate foreign keys. In the code that Figure 4 shows, add the red lines where noted.


  16. Define the relationship between the MyUrl and MyGroup objects. Specify this in the app\models \myurl.rb file:
    belongs_to :mygroup
  17. Use the rake statement to update the database based on the migration and model file changes that we just made. This step creates tables in the MySQL database (Figure 5).
    rake migrate
  18. Generate the scaffold code for the CRUD operations for our system. Run the commands that Figure 6 shows.


  19. 17. Now, the basics of our website exist. Point the browser to http://localhost:3000/Myurl. You should be able to view and add URLs.


  20. 18. Rails makes its changes dynamically. For example, make a change to the notes section. Edit the views\myurl\_form.html and add the red text as indicated in Figure 7. Refresh the web browser and notice that the notes section is now a more reasonable size.


  21. 19. Go to the URL http://localhost:3000/Mygroup and add some URL grouping strings


  22. (Figure 8). Suggested examples to add include ruby, system i, db2, Vista, Linux, and so forth.


  23. This rudimentary panel is a working application. It can Create, Retrieve, Update, and Delete from the MySQL database. You can iteratively refine the Rails application to tweak and improve it. Let's do that now.


  24. Add some Ruby code to views\myurl\_form.html to display the groupings. Add the code that Figure 9 shows to the end of the page after the <!—[eoform:myurl]—> line.


  25. Change the table in the generated scaffold code in app\views\myurl\list.rhtml. Figure 10 shows the code. This change should improve the look of the table and include the mygroup column.


  26. 23. Now we see the mygroup column in the table that lists the favorite URLs (Figure 11).


  27. 24. You can customize the styles for the MyURLs pages by editing public\stylesheets\scaffold.css. For example, add the following to give our table header a background color (Figure 12):
    th {
               background-color: lightblue;
               }

Where Will the Rails Take Us?

As you see now, Rails aids rapid web application development by automating much of the tedious work of application coding. The Rails application generator creates code in a standardized form that you can customize. The demonstration application only scratches the surface of the power of Rails. It doesn't illustrate Rails' integrated unit testing facilities, relational database tools, or built-in debugging, and it only lightly touches on the syntax of the rich Ruby language.

Rails has its limitations too, as does any application framework. Perhaps the most significant is that regenerating a Rails application destroys any customization that you've done to generated code. Rails' integrated database development tools don't readily work with existing external databases, complicating the process of merging Rails into your current web application environment. And as you see by all the text editing in the demonstration application, Rails lacks an IDE, although add-on IDEs for Rails, such as RadRails and RoRED have begun to appear. (Find Out More lists resources for getting more information about these and other aspects of Ruby and Rails.)

Rails is still evolving and thus lacks the history or library of code that some other frameworks, such as cakePHP, Java Struts, JRuby, Python Turbogears, and Zend Framework, enjoy. Also, Ruby is fighting to prove that it can run as fast as PHP or J2EE.

Still, Ruby on Rails is clearly a serious addition to the web development landscape. In summer 2006, O'Reilly Media reported that sales of Ruby and Ruby on Rails books outpaced sales of Perl and Python books. Currently, many large production websites are built on Rails, such as Basecamp (project management), Shopify (e-commerce), Typo (blogs), Odeo (music sharing), and Campfire (group chat). However, to some extent, Rails is not yet a mainstay. Ruby is a clean language to learn, and with Rails it works well for the creation of database-driven web-based apps.

When is Rails coming to i5/OS? Although no official distribution of Rails is available, the effort to enable Rails on i5/OS is certainly no more than that required for the vast PHP environment and might even be less. Rails by default works with MySQL, and System i users might be interested in the DB2 adapter for Rails (refer to Find Out More), which lets Rails applications access even System i DB2 databases. With all these things aligning, it seems inevitable that IBM will provide a way for Rails fans to run on System i.

Success!

As relative newbies on the programming landscape, Ruby and Ruby on Rails are climbing fast in popularity and surely have some valid claims on ease of use and productivity. Having a good selection of tools in the toolbox is always great. Ruby and Ruby on Rails not only come in handy for the right job, but they've also had a positive affect on practices in other languages.

Tim Massaro is an advisory programmer for IBM in Rochester, Minnesota. His career includes stints on several S/38 and System i teams, including Work Management, and Team Leader of Message Handler. He is currently on the Application Development Solutions Team. You can e-mail Tim at tmassaro@us.ibm.com.

Find Out More

DB2 on Rails blog
db2onrails.com
This blog is by IBMers Leon Katsnelson and Antonio Cangiano.

DB2 on Rails Starter Toolkit
alphaworks.ibm.com/tech/db2onrails

Demos, including a screencast in which a Rails web application is created in less than 15 minutes
rubyonrails.org/screencasts

Documentation and help for Ruby
ruby-doc.org

DrySQL
allyourdatabase.blogspot.com/2007_02_01_archive.html
DrySQL is a Ruby plug-in that supports DB2.

RadRails
wiki.radrails.org/download_radrails.php
RadRails is a free, Eclipse-based IDE that supplies syntax-directed editors for Ruby, RHTML, RB, YML, and JavaScript files. RadRails can simplify Rails development tasks.

RDT — Ruby Development Tools
rubyeclipse.sourceforge.net
RDT is an open-source Ruby IDE for the Eclipse platform.

RoRED
plasmacode.com
RoRED is a free IDE for Ruby on Rails, currently only for Windows.

RubyForge
rubyforge.org/projects/rubyibm
RubyForge is a home for open-source Ruby projects.

Ruby on Rails home page
rubyonrails.org

Sample Rails site
www.tadalist.com
The site is written by 37signals.

Books

Black, David. Ruby for Rails: Ruby Techniques for Rails Developers. Greenwich, CT: Manning Publications, 2006.

Thomas, Dave, Chad Fowler, and Andy Hunt. 2nd ed. Programming Ruby: The Pragmatic Programmers' Guide. Raleigh, NC: Pragmatic Bookshelf, 2004.

ProVIP Sponsors

ProVIP Sponsors