Hands on with Ruby on Rails

If the thought of diving into yet another hot new technology gives you a headache, I sympathize. I've stuck mainly to PHP and Perl for years, happily ignoring most other development fads.

However, I'm rethinking this as my projects get steadily more complex. After hearing a full-time developer talk about the limits he bumped into when using PHP for larger database-driven Web projects, and how useful a development framework turned out to be, I decided it was time to look seriously at some more robust tools.

There are several interesting options out there if you're looking for a framework -- something to give structure to your applications and help you do more with less code. Rails for the Ruby programming language is probably the most popular framework right now, and I was curious to find out why.

But can a part-time coding enthusiast really learn Ruby on Rails (RoR)?

SitePoint Pty.'s Build Your Own Ruby on Rails Web Applications by Patrick Lenz pledges that it's written for both hard-core programmers and the less experienced -- even those who know only HTML and CSS. "Web development has never been easier, or as much fun as it is using Ruby on Rails," Lenz says.

Fun? OK, I'm ready to see if RoR can indeed be faster, easier and more fun than some recent projects I've sweat through using PHP and Perl.

Over several weeks, I went through a portion of Lenz's book, as well as a few other resources. I was, in the end, able to create a simple application to pull items from a MySQL database. And I came to see why coding Ruby applications on Rails has become an important Web development trend.

Why use a framework like Rails?

Ruby on Rails is all about adding structure and built-in functionality to your projects, with the goal of limiting dull, repetitive and confusing coding. A caution, though: At the beginning, it seems to add complexity. It ends up paying major dividends down the road, but you have to hang onto the prospect of long-term benefits when you first dive in.

I liken it to doing your taxes. Say someone offered you a beautifully crafted, perfectly constructed file system for tracking your finances -- one that was intuitive and easy to use but had a bit of a learning curve. If you're single, fill out the short form and take the standard deduction, it would probably be easier to stick everything in a folder and deal with it in April. Likewise, for very simple scripts and applications, there's no need for a development framework like Rails.

But now imagine you have a family. And changed jobs. And have rental property income. And some self-employment income. Now that file system starts to look more appealing. So it is with Rails. As your application becomes more complicated and you want to keep adding features (or members of a programming team), a well-thought-out, preexisting structure can be mighty handy.

"For me, discovering and learning Rails had a similar effect to Google Maps; it seemed almost too good to be true," Rob Orsini writes in Rails Cookbook. "Rails handled all of the things that I found most unpleasant about Web development automatically or so elegantly that they were no longer painful. ... I've often said that the simple act of creating a Rails project felt like there was a room full of experienced software veterans imparting their knowledge about sound application design, ensuring that my project started off in the right direction."

I can see this even in a simple app I coded for myself in PHP. It started out as a few pages of PHP and a simple MySQL database. Then I wanted a mobile version to view on my cell phone. Then I needed a couple of new fields in the database. Then I changed Web hosts. You get the picture.

An external configure file and style sheet took care of some of those issues, but it turned out there were subtle differences in some SQL commands used to access my database. Suddenly, I needed to change SQL code sprinkled throughout numerous pages. Yes, I could have structured my code more modularly at the outset. But I didn't. That's one advantage of a framework -- it makes me write more modularly, counteracting my natural tendency to just go the quick-and-dirty route.

Ruby on Rails "lets you write beautiful code by favoring convention over configuration," the framework's official Web site promises. In other words, instead of having to come up with structures for your application, Rails does much of that work for you. That means first off, you don't have to create a separate file for functions you'll be using throughout your app; Rails generates files like that for you automatically. It's not all that much work to create such files, of course. But since every Rails project uses the same file structure, everyone on a team knows where to find them -- even programmers who join a project midstream. It also makes it easier to maintain your own code when you haven't looked at it in awhile.

Also, if you use the Rails naming conventions, as you create new "instances" of objects (see Object-oriented programming explained ... in English!), they automatically get mapped to an appropriate database row -- without having to write any SQL code. This is really handy if you're doing a lot of data storage and retrieval.

Rails even elegantly connects objects in different database tables with a few lines of easy-to-understand code. If I'm saving stories in a database and will be searching later to see which ones were published on a certain date, I can easily define at the outset that PublishDate has_many :stories and Story belongs_to :publishdate in the files that define PublishDate and Story. It looks like this:

Class Story < ActiveRecord::Base

belongs to :publishdate

end

Class PublishDate < ActiveRecord::Base

has_many :stories

end

(ActiveRecord is a predefined Rails class.) With those simple, human-readable lines of code, a relationship is set up allowing me to find what stories have been posted on a given date. How? If mydate is a variable representing a specific PublishDate, I find all the stories on that date just by

mydate.stories

That's it -- a lot less code than I've been using to do database queries from PHP.

Another RoR development principle, Lenz notes, is "don't repeat yourself." I've been violating that ever more egregiously, and will be glad to get help streamlining my code. Discovering after the fact what code snippets I should have made into repeatable functions is a serious time sink, and I haven't found the knack of sketching that out ahead of time.

Ruby basics

Ruby, the object-oriented programming language used by the Rails framework, was created by Yukihiro "Matz" Matsumoto in 1995. Everything in Ruby is an object -- every variable and even such literals as "Hello World."

To begin coding a Ruby on Rails application, I first need RoR on my system. On Windows, Lenz recommends using Curt Hibbs' simple-to-run Instant Rails. Good idea. After a couple of minutes unzipping 18,000 or so files, Instant Rails quickly appears on my Windows laptop. Updating Rails is quick and painless with the command

gem install rails

--include-dependencies

Installing RoR on a Linux machine is a bit more manual. Without the complete Instant Rails package, you need to first install the Ruby programming language on your system, and then the Rails framework (which was written in Ruby by David Heinemeier Hansson as part of a project-management Web application called Basecamp). There are some links explaining how to install RoR on various Linux distros on the project wiki.

First impressions

I'm impressed by the elegance of some simple Ruby commands. Want to find the length of a string? Just apply the length method to the string, with a period to separate the object from its method:

"Sharon Machlis".length

Type that into an interactive Ruby console and you get back 14. (An interactive Ruby console will run commands as you type them in. Open a Ruby window and type the command irb to get to interactive mode.)

Ruby commands don't require a semicolon at the end, which is appealing considering all the PHP and MySQL semicolons I've left off over the years. And if you use a method that doesn't need a value passed to it, you don't have to add empty parentheses like you do in a lot of other languages.

Ruby is more intuitive than other languages, developer Jay Powers at Vermonster LLC told me recently -- the code is easier to read and understand. He says it takes him less time to code major projects with Ruby on Rails than PHP or Perl because there are more methods built in.

That's the good news. The more daunting discovery is that it's initially more complex to set up classes than I'm used to in PHP.

When you define a class, you typically need some "instance methods" and some "instance variables" to store data. These variables always start with an @ symbol, as in @name or @ssnum.

Here's how Lenz does it for the class Car (everything after each # mark is an explanation I've added).

class Car # creates a new class named "Car"

@mileage = 0 # sets the initial mileage for each car to 0

def set_mileage(x) # begins a method to alter the mileage

@mileage = x # sets a new value for the mileage

end # ends the method

def get_mileage # begins "instance method" that lets us read the mileage data out of the car object

@mileage # the method will return the value of this variable

end # ends the method

end # ends the class

@kitt = Car.new # now we've got a car, the Car object named kitt

@kitt.set_mileage(5667) # stores the mileage data of 5667 for kitt the car

@kitt.get_mileage # reads the mileage information for kitt the car

At the outset, my old way of doing things, not using objects in PHP, seems a lot simpler:

$kitt_mileage = 5667; # creates a PHP variable $kitt_mileage and sets it to 5667

echo $kitt_mileage; # prints out the value of the variable $kitt_mileage

However, manipulating those variables down the road would end up being more complicated. My colleague and fellow programmer Joyce Carpenter assures me that the front-end investment in object structuring will pay dividends. I forge ahead.

Ruby has many typical features I expect in a programming language, such as arrays, associative arrays (often called hashes), strings, conditionals, loops and so on.

One point Lenz makes early: To loop through data in an array, Ruby programmers are more likely to use "blocks" than things like for/else/while/until loops. "However, they're also one of those things that take a while to 'click' for Ruby newcomers," he notes. He's right on that. I don't see how a construct like

[ kitt, herbie, batmobile, larry ].each do |car_name|

puts car_name.mileage #

end

is vastly superior to something like

$car_array = array("kitt", "herbie", "batmobile", "larry");

foreach ($car_array as $key => $value){

echo "$value\n";

}

in PHP. I need to keep reading.

Hands-on Rails: Come code along

Now that I've gotten a small taste of Ruby, it's on to the Rails development framework. To start a new project in Rails, you type

rails yourprojectname

in a Rails console.

If you'd like, follow along and create your own project. If you're using InstantRails on Windows, click on the I at the upper left and select Rails Applications --> Manage Rails Applications. That gives you the option of creating a new Rails app, which opens a shell in the correct rails_app directory.

I type

rails myfavorites

This creates a bunch of new directories -- a dozen at the top level plus even more subdirectories.

If you're used to starting small with a couple of unstructured files, "this wealth of subdirectories can be overwhelming at first," Lenz says.

Yup.

But, he explains, "a lot of thought has gone into establishing and naming the folders, and the result is an application whose file system is well structured." This makes possible a lot of automatic associations between variables, objects, folders, databases and the like. The upside? You have a lot less work to do.

Architecture fundamentals

Rails follows the Model-View-Controller (MVC) architectural principles. Basically, Lenz explains, models handle data and business logic; controllers deal with application logic and information being passed to the user interface; and views handle GUI and presentation HTML that displays in a browser.

In Rails, the model, view and controller files are created in their own automatically generated subdirectories, one of the dozen-plus that live under the auto-generated main project directory, app/project.

If you're used to merging everything together in a single file, as I am, it takes some getting used to. Initially, the concept seems downright silly: Create one file in my app/models directory to set up the data structure; create another file in my app/controllers directory to set up calculations, database queries and other logic; create yet a third file in my app/views directory with the HTML code. All this just to accomplish the simple task of displaying something. Good grief, I can do all that with a few lines of code in a single PHP or Perl file and be done.

However, what looks like a lot of initial complexity and constraints is actually the foundation for less repetitive, more maintainable code. Follow the rules, and I'll know where each part of my application lives; I won't have to make changes by hunting for code scattered through a bazillion separate .php files.

1 2 3 Page 1
Page 1 of 3
The 10 most powerful companies in enterprise networking 2022