At the Forge - Getting Started with Ruby
The above are what we might expect from simple CGI programs—easy to write, easy to work with and slow to execute. If our programs get any more complicated, we have to deal with new issues that we might prefer to ignore, such as personalization.
Luckily, Ruby comes with its own HTTP server, known as WEBrick, that is similar in some ways to AOLserver or mod_perl. There is also mod_ruby, if you are interested in a more direct equivalent to mod_perl, that runs under Apache. To start a basic HTTP server on port 8000, looking at the same static documents as Apache, use the following code:
#!/usr/bin/env ruby
# *-ruby-*-
require 'webrick'
include WEBrick
# Create an HTTP server
s = HTTPServer.new(
:Port => 8000,
:DocumentRoot => "/usr/local/apache/htdocs/"
)
# When the server gets a control-C, kill it
trap("INT"){ s.shutdown }
# Start the server
s.start
There are several things to note here. First, there isn't much code. You indicate what port WEBrick should listen to, tell it where files are located and then start it up.
Before we start the server, we have to make sure it is possible to stop it easily. To do that, we invoke trap, indicating that we want to trap SIGINT (that is, Ctrl-C) and that s.shutdown should be invoked upon receiving that signal.
If you put the above program in a file named server.rb and execute it, you should have a fully functional HTTP server running on your system. Creating a Web server has never been simpler.
Of course, no one runs WEBrick instead of Apache for its speed or to serve static documents. Rather, WEBrick shines when you want to create custom behaviors. In spirit and terminology, there is a fair amount of overlap between WEBrick servlets and Java servlets. The basic idea is the same: define a new class and then attach an instance of that class to a particular URL. For example, if we want to create a servlet that prints the time of day, we can create the following:
#!/sw/bin/ruby
require 'webrick'
include WEBrick
# ---------------------------------------------
# Define a new class
class CurrentTimeServlet
< WEBrick::HTTPServlet::AbstractServlet
def do_GET(request, response)
response['Content-Type'] = 'text/plain'
response.status = 200
response.body = Time.now.to_s + "\n"
end
end
# ----------------------------------------------
# Create an HTTP server
s = HTTPServer.new(
:Port => 8000,
:DocumentRoot => "/usr/local/apache/htdocs/"
)
s.mount("/time", CurrentTimeServlet)
# When the server gets a control-C, kill it
trap("INT"){ s.shutdown }
# Start the server
s.start
Our one file contains both the class definition for CurrentTimeServlet and the commands for starting WEBrick. This is not the most elegant style for creating a servlet, and you typically want to put each servlet in its own file. That said, Ruby makes it easy and convenient to define or redefine classes and methods wherever it might be best to do so. This is one of those features in Ruby that reminds me of Perl: the language gives you a great deal of flexibility when writing your code but expects you to be responsible enough to avoid making a mess of it.
We define our servlet, CurrentTimeServlet, to be a subclass of WEBrick::HTTPServlet::AbstractServlet, making it a simple servlet indeed. We then define the do_GET method along with the do_POST method, if you so desire, which gets both a request and a response object. If you have written Java servlets, this should look familiar to you. We set the content type of the response, the status code (200) for the response and even the body of the response with a few simple lines of code. And that's it; our servlet has been defined and is ready to go. All that is left to do is connect the servlet to a URL:
s.mount("/time", CurrentTimeServlet)
If we want, we can pass parameters to the servlet when we initialize it. Anything beyond the first two parameters to s.mount is sent:
s.mount("/time", CurrentTimeServlet, 'a parameter')
Is it amazing that we can do this much in so few lines of code? Perhaps—although similar functionality certainly exists in other languages. For example, Perl programmers can download HTTP::Server::Simple from CPAN and do many of the same things. And if I really was interested in modifying the behavior of an HTTP server to do interesting things, I probably would think of using mod_perl or AOLserver first, for reasons of performance and flexibility.
That said, WEBrick is extremely easy to get running and for creating custom HTTP-based behaviors. I can imagine using it to handle Web services, for example, because of the flexibility that Ruby brings to the table, or to test applications written in Rails.
And, although people are using Ruby and WEBrick for plain-vanilla Web development, most of the excitement seems to be over the specific Rails framework, rather than Ruby or WEBrick themselves. In my next article, we will start to explore Rails—how to install it, how to develop applications with it and how it stacks up against other open-source application frameworks.
Resources for this article: /article/8397.
Reuven M. Lerner, a longtime Web/database consultant and developer, now is a graduate student in the Learning Sciences program at Northwestern University. His Weblog is at altneuland.lerner.co.il, and you can reach him at reuven@lerner.co.il.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- RSS Feeds
- Trying to Tame the Tablet
- New Products
- What's the tweeting protocol?
- Dart: a New Web Programming Experience
- Reply to comment | Linux Journal
2 hours 4 min ago - Drupal is an Awesome CMS and a Crappy development framework
6 hours 43 min ago - IT industry leaders
9 hours 5 min ago - Reply to comment | Linux Journal
1 day 1 hour ago - Reply to comment | Linux Journal
1 day 4 hours ago - Reply to comment | Linux Journal
1 day 5 hours ago - great post
1 day 6 hours ago - Google Docs
1 day 6 hours ago - Reply to comment | Linux Journal
1 day 11 hours ago - Reply to comment | Linux Journal
1 day 12 hours ago
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.




Comments
Setting up a Linux Rails Development Environment
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
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
indents in ruby are 2 spaces...if you want the community to like you.
Thanks
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)
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
RoR has a console for debugging purposes which allows you to directly interact with your development model.