If you haven’t yet started using Ruby or Rails, this section will point you in the right direction. If you’re comfortable with Rails basics, feel free to skip ahead to Chapter 2, where we’ll start doing Ajax. It’s outside the scope of this book to provide a comprehensive guide to Ruby, or all of Rails. Fortunately, there are dozens of excellent resources available to fill that need. In this section, we’ll point you to the best.
Getting and installing Ruby is easy on almost every platform. The official web site is http://ruby-lang.org. From there, you’ll find downloads for the latest releases. Windows users can take advantage of the One-Click Ruby Installer (http://rubyinstaller.rubyforge.org), which bundles lots of great extensions. Mac users already have Ruby installed as part of OS X—however, it’s not configured correctly for Rails use. To fix that, follow this guide: http://hivelogic.com/articles/2005/12/01/ruby_rails_lighttpd_mysql_tiger.
Try Ruby (http://tryruby.hobix.com) is a hands-on Ruby tutorial that runs entirely in your browser, with no need to download Ruby first. It’s a great way to familiarize yourself with Ruby’s syntax and conventions.
Programming Ruby by Dave Thomas, et al. (Pragmatic Bookshelf), also known as the “Pickaxe book,” is the most popular book on Ruby, for good reason—it’s full of clear explanations and vital reference. Best of all, the first edition (which doesn’t cover the latest additions to Ruby but is still immensely useful) is available free online at http://www.rubycentral.com/book.
Why’s (Poignant) Guide to Ruby (http://poignantguide.net/ruby) is a great, free resource for learning Ruby. Self-described as “the pirate radio of technical manuals,” it also serves as an excellent introduction to the off-the-wall sense of humor often found in the Ruby community.
ruby-talk is the official Ruby mailing list. As you delve into Ruby, it’s invaluable to have access to a community of fellow developers, and ruby-talk
is just that. To subscribe, send a message to email@example.com with
Ruby Core and Standard Library documentation is available from the Rails web site: http://corelib.rubyonrails.org and http://stdlib.rubyonrails.org. It’s not organized linearly for beginners, but it’s fantastic for reference.
First you’ll need RubyGems, Ruby’s standard package-management system. You can download the latest version from http://docs.rubygems.org. Once you extract it, just run
setup.rb from your system’s command line to install it.
Install Rails and its dependencies by entering
-y. If you’re using a Unix-like system, you may need to run
gem as root, or by using
sudo. While you’re at it, run
-y as well—Mongrel is a speedier alternative to Ruby’s built-in web server.
Agile Web Development with Rails by Dave Thomas, et al. (Pragmatic Bookshelf) was the first Rails book; it was co-written by Dave Thomas and David Heinemeier Hansson. It’s chock-full of clear examples and helpful tips.
The Rails API Documentation is available at http://api.rubyonrails.org. It can be somewhat terse and hard to navigate until you understand how Rails is organized, but it’s an invaluable reference for how particular methods work. One of its best features is that it allows you to view the source for each method in the API—a fantastic way to learn about Rails internals and good Ruby style, as well.
When you install Rails, a copy of the Rails API Documentation is installed on your local computer along with it, which is handy for working offline. To access it, run
gem_server from the system command line, and a Ruby web server will be started on port 8808. Then browse to http://localhost:8808 and you’ll see a list of every package installed via RubyGems.
The Rails Wiki (http://wiki.rubyonrails.org/rails) is full of user-contributed hints and tutorials on everything from the basics to the very complex. Unfortunately, it also has a fair amount of outdated advice, but it’s still a great place to start looking for answers.
The Rails mailing list is one of the best places to find announcements of new Rails plug-ins and projects, discussion of new features, and troubleshooting of problems. You can browse the archives and subscribe at http://groups.google.com/group/rubyonrails-talk.
Rails works with a number of different databases, and the most common are free: MySQL, PostgreSQL, and SQLite. (There are also database adapters included for DB2, Oracle, Firebird, and SQL Server.) Each has its advantages and disadvantages, but if you’re just getting started, it won’t make much difference. MySQL installers for Windows, Mac, and Linux are available at http://dev.mysql.com/downloads/mysql/5.0.html. While you’re at it, you’ll also want a database client program to make it easier to create and modify database tables. For MySQL, the MySQL Query Browser is a good cross-platform option. Get it at http://dev.mysql.com/downloads/query-browser/1.1.html.
While any bare-bones text editor will work, developing with Rails involves lots of switching between files, so it’s worth finding a powerful editor. Rails developers on Mac OS X usually use TextMate, available from http://macromates.com. Windows developers often recommend TextPad (http://www.textpad.com) and UltraEdit (http://www.ultraedit.com).
If you’ve just installed Rails for the first time, let’s kick the tires. First, from the command line, navigate to where you want to create your first application (perhaps your home directory or your work area). Then, run
rails command-line program simply generates a skeleton app—all the standard directories and boilerplate files you’ll need for every project. Take a look in the ajaxonrails directory that you just created, and you’ll see the following:
|app/||As the name suggests, this is where your Rails-specific application code lives.|
|controllers/||Controllers orchestrate your application flow, taking in HTTP requests, interacting with the model, rendering a view, and returning an HTTP response.|
|helpers/||Helpers are Ruby methods that are called from the views, to help keep your code clean. Rails includes a lot of helpers, and you can define your own in this directory.|
|models/||Models generally correspond directly to database tables, and they encapsulate database functions from the rest of your application.|
|views/||We’ll be spending a lot of time in this directory—it’s where your view layer lives, which is responsible for generating HTML, among other things.|
|config/||Here you’ll configure your application for its environment, telling it how to connect to a database, how external URLs map to internal code, etc.|
|doc/||Rails can automatically generate API documentation for your application’s code; this is where it will go.|
|lib/||This directory is intended for custom Ruby libraries that your application requires.|
|log/||As your application runs, Rails generates helpful logs in this directory.|
|script/||Every Rails application comes with a default set of standard scripts for generating code, starting and stopping the app, etc. They belong here, along with any other scripts you create.|
|test/||Rails encourages the practice of automated testing and puts the boilerplate “stubs” for your test code in this directory.|
|tmp/||This directory holds temporary files used by the application—sessions, caches, and sockets.|
|vendor/||This directory holds third-party libraries for your application.|
|plugins/||This directory holds Rails plugins—packages of code that extend and modify the framework’s features.|
After you have created a skeleton application from the command line, change directories into your project directory (ajaxonrails). Then, run the application by entering
script/server. You will see a message indicating the application has started. To shut the server down, use Ctrl-C.
script/server command invokes Mongrel (or WEBrick, if Mongrel is not installed), a Ruby web server that’s perfect for development purposes. Opening your web browser to the address http://localhost:3000, you should see the Rails welcome screen (Figure 1-5
). Congratulations, you’re on Rails!
Now that you’ve had a little taste of the practice, here’s the theory. This section is just overview—for the full details on these things, refer to the Rails resources above.
Rails is divided into a handful of libraries:
ActionPack (the most important two for this book), as well as
object relational mapper (ORM). ORMs act as a bridge between relational databases and object-oriented languages. Relational databases inherently organize information differently than objects do—for instance, objects are able to encapsulate behavior (methods) as well as data. ORMs exist to address that problem. There are a number of different ways to accomplishORM, including a design pattern called Data Mapper. The Data Mapper approach allows a great deal of flexibility, by allowing you to explicitly define the mappings between your objects and your database tables.
ActiveRecord was named after an alternative pattern, Active Record. Compared with Data Mapper, it trades some flexibility (a layer of indirection between the database and the in-memory objects) to gain a lot of simplicity—it automatically creates an object attribute for every database column. Without that feature, you’d have to define your mapping explicitly, which leads to the verbose XML configuration files common in other frameworks.
Three other features of
ActiveRecord to note are
associations, callbacks, and validations. Associations allow you to define relationships between your ActiveRecord classes, like one-to-one, one-to-many, and many-to-many. Callbacks provide a robust set of hooks into the life cycle of your objects, where you can add behavior (e.g., after a record is updated, create an entry in an audit log). Validations are a special kind of callback that make standard data-validation routines a cinch. By keeping your associations, callbacks, and validation rules in the
ActiveRecord class definition, you’re making it easier to create reliable, maintainable code.
ActionPack has two subparts that work together closely,
ActionController classes define actions—public methods that are accessible from the Web. Actions always end in one of two ways: either with a redirect (an HTTP response header sent back, causing the client to be forwarded to another URL) or with a render (some content being sent back to the client, usually an HTML file). When an action renders an HTML file,
ActionView is invoked. To see how these major libraries work together, take a look at the life cycle of a typical Rails request in Figure 1-6.