At the Forge - Getting Started with Ruby

What's behind all the Ruby hype? Reuven walks us through a couple of examples to let the code speak for itself.

About ten years ago, back when I was working in New York, friends of mine showed me something that knocked my socks off—a program that actually ran inside of the Web browser, without any need for pressing submit. It was sleek, fun to use and seemed like a major paradigm shift. We all were excited about what this new “Java” language and its applets would mean for Web development. Although we didn't quite know where or how it would end, we talked about nothing else for some time.

In the decade since then, many different technologies have been hyped as “the next best thing” or “the tool you need to make better Web sites”. Indeed, we constantly are bombarded with claims of newer, better, faster and cheaper ways to develop software. Some of these promises have panned out, but a trade-off usually is associated with them. For example, developing Web applications in Zope is indeed quite easy—once you get over the learning curve. Web services are fine, until you start to deal with complex data structures across different platforms.

You can imagine my surprise, then, when I began to see another “best new method” coming over the horizon—but this one was touted by people I respect, who normally don't give in to hype so quickly. I'm speaking, of course, about “Ruby on Rails”, an object-oriented system for creating and deploying Web applications. For several months now, I have been reading about how wonderful Rails is and how it makes Web development utterly simple.

I had been meaning to try Ruby as a language for some time, and the growth of Rails has given me an opportunity to do so. This month, we take an initial look at Ruby, examining simple ways to create Web applications with the basic Ruby language and libraries. In my next article, we will look at Rails and see how it stacks up against other, more established frameworks.

What Is Ruby?

Ruby is an open-source programming language originally developed by Japanese programmer Yukihiro Matsumoto, also known as Matz. Ruby first was released in late 1995, making it older than many people might think. It took some time for people outside of Japan to discover and work with Ruby, in part because of the lack of documentation. The first edition of Dave Thomas' book, Programming Ruby (see the on-line Resources) provided a solid introduction to the language, as well as a reference guide to its class libraries, giving it a needed PR boost. The second version of the “Pickaxe book”, as it is known, now is available.

Ruby was designed to be an “object-oriented scripting language”, and it indeed feels like a cross between Perl and Smalltalk. It assumes that you understand object-oriented programming and probably is not a good first language for someone to learn. But if you are familiar with both objects and Perl, then you quickly can learn to do many things with Ruby.

Here is a simple “Hello, world” program in Ruby:


#!/usr/bin/env ruby

print "Hello, world\n"

The first line ensures that we run the Ruby interpreter, regardless of where it might be in our path. The second line, as you might expect, prints "Hello, world" followed by a newline character. Like Python and unlike Perl, no semicolon is required at the end of a line of Ruby code.

Now that we have created a simple command-line program, it's time to create an equivalent CGI program. CGI programs are portable across all types of Web servers. Although not particularly fast or smart, they are easy to write and a good way to dip our toes into the Web development side of a language.

In the case of Ruby, the easiest CGI program would be similar to the above code. After all, the CGI specification tells us that anything written to standard output is sent to the user's Web browser. So long as we send a Content-type header before our text, we can make it a CGI program with almost no effort:


#!/usr/bin/env ruby

# HTTP response headers, including double newline
print "Content-type: text/plain\n\n"

# Contents
print "Hello, world\n"

Sure enough, naming the above program hello.rb, putting it in my Web server's cgi-bin directory and pointing my Web browser to http://localhost/cgi-bin/hello.rb produces the "Hello, world" message in my browser.

Using the Ruby Library

The CGI object in the included Ruby library provides methods that understand Web functionality, from HTML formatting to cookies and parameters. For example, here is a new version of our “Hello, world” program written to use the built-in functionality:

#!/usr/bin/env ruby
# *-ruby-*-

require 'cgi'

# Create an instance of CGI, with HTML 4 output
cgi = CGI.new("html4")

# Send the following to the CGI object's output
cgi.out {
  cgi.html {

# Produce a header
cgi.head { cgi.title { "This is a title" }
} +

# Produce a body
cgi.body {
  cgi.h1 { "This is a headline" } +
    cgi.p { "Hello, world." }
}
  }
}

As you can see, the code now looks substantially different, even though the output largely is the same. What we have done is switched from explicit print statements to methods invoked on our CGI object, as well as added a title and a headline.

When we create our CGI object with CGI.new, we can pass an argument indicating the level of HTML compliance we want to have. Unless you have a good reason to do otherwise, aiming for the highest level of compliance, namely HTML4, is a good idea.

Notice how the output, beginning with cgi.out, functions as a set of code blocks, each of which is expected to return a text string. Thus, cgi.h1 and cgi.p are combined—using the + operator, as in Python or Java—and are fed to cgi.body. cgi.head and cgi.body are joined as well and fed to cgi.html. The fact that this hierarchy mimics the eventual document output format makes it easy to understand and use this functionality.

CGI programs are more interesting when they handle parameters from the user. We can get parameters with the CGI.params method:

#!/usr/bin/env ruby
# *-ruby-*-

require 'cgi'

# Create an instance of CGI
cgi = CGI.new("html4")

# Get our first name
firstname = cgi.params['firstname']
if (firstname.empty?)
  firstname = '(No firstname)'
end

# Get our last name
lastname = cgi.params['lastname']
if (lastname.empty?)
  lastname = '(No lastname)'
end

# Send some output to the end user
cgi.out {

  cgi.html {

# Produce a header
cgi.head { cgi.title { "This is a title" }
} +

# Produce a body
cgi.body {
  cgi.h1 { "This is a headline" } +
    cgi.p { "Hello, #{firstname} #{lastname}." }
}
  }
}

There are two basic differences between this code and its predecessor. To begin with, we now are defining two variables, firstname and lastname, which we then print for the user. The variables are defined based on the parameter values passed to the program, either by way of the URL in a GET request or in the body of the request for POST. We use the empty? method on both firstname and lastname to check whether they are empty and then assign a default value to them if that is the case. Finally, we use Ruby's #{expression} syntax within double-quoted strings to display the user's first and last names.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Setting up a Linux Rails Development Environment

Jim Rutherford's picture

If you looking to give Rails a try on linux, checkout my tutorial on Installing Ruby on Rails with Lighttpd and MySQL on Fedora Core 4

Cheers!

indention in CGI code

Robby Russell's picture

Is the weird indenting in the CGI example intentional?

A few python pals looked at that and immediately thought it might be some Ruby-ism. I showed them an example like this to clear up the confusion:

nevermind, linuxjournal doesn't allow a pre tag so my indenting doesn't stay in the comment. I'd prefer not confuse anyone else. :-)

indents in ruby are 2 spaces

Anonymous's picture

indents in ruby are 2 spaces...if you want the community to like you.

Thanks

Eric Anderson's picture

Thanks for the quick intro, it's a good starting point for server-side Java developers. I'm looking forward to the Rails article.

One thing though: how about a look into the Ruby debugging environment. What tools/approaches do I use to debug complex server-side Ruby applications? I hope the answer is not "use print statements" ... effectively taking us back to the Dark Ages of programming. I like the idea of object-oriented scripting, but do not like the idea of _not_ having tools as powerful as say, the Eclipse or Netbeans debuggers for my work.

You can use Eclipse, for sure :o)

mpathy's picture

There is a very nice plugin for eclipse I use.

Use the Eclipse Update Manager with this URL:
http://rubyeclipse.sf.net/updatesite

There is a Test::Unit included.
Thats what you need (if I understood you right).

Try Ruby on Rails

michael's picture

RoR has a console for debugging purposes which allows you to directly interact with your development model.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState