Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

1.2 Up and Running

It's time now to get going with a Ruby on Rails development environment and our first application. There is quite a bit of overhead here, especially if you don't have extensive programming experience, so don't get discouraged if it takes a while to get started. It's not just you; every developer goes through it (often more than once), but rest assured that the effort will be richly rewarded.

1.2.1 Development Environments

Considering various idiosyncratic customizations, there are probably as many development environments as there are Rails programmers, but there are at least two broad themes: text editor/command line environments, and integrated development environments (IDEs). Let's consider the latter first.

IDEs

There is no shortage of Rails IDEs; indeed, the main Ruby on Rails site names four: RadRails, RubyMine, 3rd Rail, and NetBeans. All are cross-platform, and I've heard good things about several of them. I encourage you to try them and see if they work for you, but I have a confession to make: I have never found an IDE that met all my Rails development needs—and for some projects I haven't even been able to get them to work at all.

Text Editors and Command Lines

What are we to use to develop Rails apps, if not some awesome all-in-one IDE? I'd guess the majority of Rails developers opt for the same solution I've chosen: use a text editor to edit text, and a command line to issue commands (Figure 1.1). Which combination you use depends on your tastes and your platform:

Figure 1.1

Figure 1.1 A text editor/command line development environment (TextMate/iTerm).

  • Macintosh OS X: Like many Rails developers, I prefer TextMate. Other options include Emacs and MacVim (launched with the command macvim ), the excellent Macintosh version of Vim.7 I use iTerm for my command line terminal; others prefer the native Terminal app.
  • Linux: Your editor options are basically the same as OS X, minus TextMate. I'd recommend graphical Vim (gVim), gedit (with the GMate plugins), or Kate. As far as command lines go, you're totally set: every Linux distribution comes with at least one command line terminal application (and often several).
  • Windows: Unfortunately, I can't make any personal recommendations here, but you can do what I did: drop "rails windows" into Google to see what the latest thinking is on setting up a Rails development environment on Windows. Two combinations look especially promising: Vim for Windows with Console (recommended by Akita On Rails) or the E Text Editor with Console and Cygwin (recommended by Ben Kittrell). Rails Tutorial readers have suggested looking at Komodo Edit (cross-platform) and the Sublime Text editor (Windows only) as well. No matter which editor you choose, I recommend trying Cygwin, which provides the equivalent of a Unix terminal under Windows; see, for example, this video on Ruby on Rails + Cygwin + Windows Vista. (In addition to installing the packages in the video, I recommend installing git, curl, and vim. Don't install Rails as in the video, though; use the instructions below instead.) With Cygwin, most of the command-line examples in the book should work with minimum modification.

If you go with some flavor of Vim, be sure to tap into the thriving community of Vim-using Rails hackers. See especially the rails.vim enhancements and the NERD tree project drawer.

Browsers

Although there are many web browsers to choose from, the vast majority of Rails programmers use Firefox, Safari, or Chrome when developing. The screenshots in Rails Tutorial will generally be of a Firefox browser. If you use Firefox, I suggest using the Firebug add-on, which lets you perform all sorts of magic, such as dynamically inspecting (and even editing) the HTML structure and CSS rules on any page. For those not using Firefox, Firebug Lite works with most other browsers, and both Safari and Chrome have a built-in "Inspect element" feature available by right-clicking on any part of the page. Regardless of which browser you use, experience shows that the time spent learning such a web inspector tool will be richly rewarded.

A Note About Tools

In the process of getting your development environment up and running, you may find that you spend a lot of time getting everything just right. The learning process for editors and IDEs is particularly long; you can spend weeks on TextMate or Vim tutorials alone. If you're new to this game, I want to assure you that spending time learning tools is normal. Everyone goes through it. Sometimes it is frustrating, and it's easy to get impatient when you have an awesome web app in your head and you just want to learn Rails already, but have to spend a week learning some weird ancient Unix editor just to get started. But a craftsman has to know his tools; in the end the reward is worth the effort.

1.2.2 Ruby, RubyGems, Rails, and Git

Now it's time to install Ruby and Rails. The canonical up-to-date source for this step is the Ruby on Rails download page. I'll assume you can go there now; parts of this book can be read profitably offline, but not this part. I'll just inject some of my own comments on the steps.

Install Git

Much of the Rails ecosystem depends in one way or another on a version control system called Git (covered in more detail in Section 1.3). Because its use is ubiquitous, you should install Git even at this early stage; I suggest following the installation instructions for your platform at the Installing Git section of Pro Git.

Install Ruby

The next step is to install Ruby. It's possible that your system already has it; try running

$ ruby -v
ruby 1.9.2

to see the version number. Rails 3 requires Ruby 1.8.7 or later and works best with Ruby 1.9.2. This tutorial assumes that you are using the latest development version of Ruby 1.9.2, known as Ruby 1.9.2-head, but Ruby 1.8.7 should work as well.

The Ruby 1.9 branch is under heavy development, so unfortunately installing the latest Ruby can be quite a challenge. You will likely have to rely on the web for the most up-to-date instructions. What follows is a series of steps that I've gotten to work on my system (Macintosh OS X), but you may have to search around for steps that work on your system.

As part of installing Ruby, if you are using OS X or Linux I strongly recommend installing Ruby using Ruby Version Manager (RVM), which allows you to install and manage multiple versions of Ruby on the same machine. (The Pik project accomplishes a similar feat on Windows.) This is particularly important if you want to run Rails 3 and Rails 2.3 on the same machine. If you want to go this route, I suggest using RVM to install two Ruby/Rails combinations: Ruby 1.8.7/Rails 2.3.10 and Ruby 1.9.2/Rails 3.0.1. If you run into any problems with RVM, you can often find its creator, Wayne E. Seguin, on the RVM IRC channel (#rvm on freenode.net).8

After installing RVM, you can install Ruby as follows:9

$ rvm update --head
$ rvm reload
$ rvm install 1.8.7
$ rvm install 1.9.2
<wait a while>

Here the first two commands update and reloadRVMitself, which is a good practice since RVMgets updated frequently. The final two commands do the actual Ruby installations; depending on your system, they might take a while to download and compile, so don't worry if it seems to be taking forever. (Also beware that lots of little things can go wrong. For example, on my system the latest version of Ruby 1.8.7 won't compile; instead, after much searching and hand-wringing, I discovered that I needed "patchlevel" number 174:

$ rvm install 1.8.7-p174

When things like this happen to you, it's always frustrating, but at least you know that it happens to everyone. . . )

Ruby programs are typically distributed via gems, which are self-contained packages of Ruby code. Since gems with different version numbers sometimes conflict, it is often convenient to create separate gemsets, which are self-contained bundles of gems. In particular, Rails is distributed as a gem, and there are conflicts between Rails 2 and Rails 3, so if you want to run multiple versions of Rails on the same system you need to create a separate gemset for each:

$ rvm --create 1.8.7-p174@rails2tutorial
$ rvm --create use 1.9.2@rails3tutorial

Here the first command creates the gemset rails2tutorial associated with Ruby 1.8.7-p174, while the second command creates the gemset rails3tutorial associated with Ruby 1.9.2 and uses it (via the use command) at the same time. RVM supports a large variety of commands for manipulating gemsets; see the documentation at http://rvm.beginrescueend.com/gemsets/.

In this tutorial, we want our system to use Ruby 1.9.2 and Rails 3.0 by default, which we can arrange as follows:

$ rvm --default use 1.9.2@rails3tutorial

This simultaneously sets the default Ruby to 1.9.2 and the default gemset to rails3-tutorial .

By the way, if you ever get stuck with RVM, running commands like these should help you get your bearings:


$ rvm --help
$ rvm gemset --help

Install RubyGems

RubyGems is a package manager for Ruby projects, and there are tons of great libraries (including Rails) available as Ruby packages, or gems. Installing RubyGems should be easy once you install Ruby. In fact, if you have installed RVM, you already have RubyGems, since RVM includes it automatically:

$ which gem
/Users/mhartl/.rvm/rubies/ruby-head/bin/gem

If you don't already have it, you should download RubyGems, extract it, and then go to the rubygems directory and run the setup program:

$ [sudo] ruby setup.rb

Here sudo executes the command ruby setup.rb as an administrative user, which has access to files and directories that normal users can't touch; I have put it in brackets to indicate that using sudo may or may not be necessary for your particular system. Most Unix/Linux/OS X systems require sudo by default, unless you are using RVM as suggested in Section 1.2.2. Note that you should not actually type any brackets; you should run either

$ sudo ruby setup.rb

or

$ ruby setup.rb

depending on your system.

If you already have RubyGems installed, you might want to update your system to the latest version:

$ [sudo] gem update --system

Finally, if you're using Ubuntu Linux, you might want to take a look at the Ubuntu/Rails 3.0 blog post by Toran Billups for full installation instructions.

Install Rails

Once you've installed RubyGems, installing Rails 3.0 should be easy:

$ [sudo] gem install rails --version 3.0.1

To verify that this worked, run the following command:

$ rails -v
Rails 3.0.1

1.2.3 The First Application

Virtually all Rails applications start the same way, with the rails command. This handy program creates a skeleton Rails application in a directory of your choice. To get started, make a directory for your Rails projects and then run the rails command to make the first application:

Listing 1.1. Running the rails script to generate a new application.

   $ mkdir rails_projects
$ cd rails_projects
$ rails new first_app
      create
      create  README
      create  .gitignore
      create  Rakefile
      create  config.ru
      create  Gemfile
      create  app
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/views/layouts/application.html.erb
      create  app/models
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      .
      .
      .

Notice how many files and directories the rails command creates. This standard directory and file structure (Figure 1.2) is one of the many advantages of Rails; it immediately gets you from zero to a functional (if minimal) application. Moreover, since the structure is common to all Rails apps, you can immediately get your bearings when looking at someone else's code. A summary of the default Rails files appears in Table 1.1; we'll learn about most of these files and directories throughout the rest of this book.

Figure 1.2

Figure 1.2 The directory structure for a newly hatched Rails app.

Table 1.1. A summary of the default Rails directory structure

File/Directory

Purpose

app/

Core application (app) code, including models, views, controllers, and helpers

config/

Application configuration

db/

Files to manipulate the database

doc/

Documentation for the application

lib/

Library modules

log/

Application log files

public/

Data accessible to the public (e.g., web browsers), such as images and cascading style sheets (CSS)

script/rails

A script provided by Rails for generating code, opening console sessions, or starting a local web server

test/

Application tests (made obsolete by the spec/ directory in Section 3.1.2)

tmp/

Temporary files

vendor/

Third-party code such as plugins and gems

README

A brief description of the application

Rakefile

Utility tasks available via the rake command

Gemfile

Gem requirements for this app

config.ru

A configuration file for Rack middleware

.gitignore

Patterns for files that should be ignored by Git

1.2.4 Bundler

After creating a new Rails application, the next step is to use Bundler to install and include the gems needed by the app. This involves opening the Gemfile with your favorite text editor:

$ cd first_app/
$ mate Gemfile

The result should look something like Listing 1.2.

Listing 1.2. The default Gemfile in the first_app directory.

source 'http://rubygems.org'

gem 'rails', '3.0.1'

# Bundle edge Rails instead:

   # gem 'rails', :git => 'git://github.com/rails/rails.git'

gem 'sqlite3-ruby', :require => 'sqlite3'

# Use unicorn as the web server

   # gem 'unicorn'

   # Deploy with Capistrano

   # gem 'capistrano'


   # To use debugger

   # gem 'ruby-debug'


   # Bundle the extra gems:

   # gem 'bj'

   # gem 'nokogiri', '1.4.1'

   # gem 'sqlite3-ruby', :require => 'sqlite3'

   # gem 'aws-s3', :require => 'aws/s3'


   # Bundle gems for certain environments:

   # gem 'rspec', :group => :test

   # group :test do

   #   gem 'webrat'

   # end

Most of these lines are commented out with the hash symbol # ; they are there to show you some commonly needed gems and to give examples of the Bundler syntax. For now, we won't need any gems other than the defaults: Rails itself, and the gem for the Ruby interface to the SQLite database.

Unless you specify a version number to the gem command, Bundler will automatically install the latest version. Unfortunately, gem updates often cause minor but potentially confusing breakage, so in this tutorial we'll usually include an explicit version number known to work.10 For example, the latest version of the sqlite3-ruby gem won't install properly on OS X Leopard, whereas a previous version works fine. Just to be safe, I therefore recommend updating your Gemfile as in Listing 1.3.

Listing 1.3. A Gemfile with an explicit version of the sqlite3-ruby gem.

source 'http://rubygems.org'

gem 'rails', '3.0.1'
gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'

This changes the line

gem 'sqlite3-ruby', :require => 'sqlite3'

from Listing 1.2 to

gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'

which forces Bundler to install version 1.2.5 of the sqlite3-ruby gem. (I've also taken the liberty of omitting the commented-out lines.) Note that I need version 1.2.5 of the sqlite3-ruby gem on my system, but you should try version 1.3.1 if 1.2.5 doesn't work on your system.

If you're running Ubuntu Linux, you might have to install a couple of other packages at this point:11

$ sudo apt-get install libxslt-dev libxml2-dev      # Linux only

Once you've assembled the proper Gemfile, install the gems using bundle install:

$ bundle install
Fetching source index for http://rubygems.org/
.
.
.

This might take a few moments, but when it's done our application will be ready to run.

1.2.5 rails server

Thanks to running rails new in Section 1.2.3 and bundle install in Section 1.2.4, we already have an application we can run—but how? Happily, Rails comes with a command-line program, or script, that runs a local web server,12 visible only from your development machine:13

$ rails server
=> Booting WEBrick
=> Rails 3.0.1 application starting on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server

This tells us that the application is running on port number 300014 at the address 0.0.0.0. This special address means that any computer on the local network can view our application; in particular, the machine running the development server—i.e., the local development machine—can view the application using the address localhost:3000.15 We can see the result of visiting http://localhost:3000/ in Figure 1.3.

Figure 1.3

Figure 1.3 The default Rails page (http://localhost:3000/.)

To see information about our first application, click on the link "About your application's environment". The result is shown in Figure 1.4.16

Figure 1.4

Figure 1.4 The default page (http://localhost:3000/) with the app environment.

Of course, we don't need the default Rails page in the long run, but it's nice to see it working for now. We'll remove the default page (and replace it with a custom home page) in Section 5.2.2.

1.2.6 Model-View-Controller (MVC)

Even at this early stage, it's helpful to get a high-level overview of how Rails applications work (Figure 1.5). You might have noticed that the standard Rails application structure (Figure 1.2) has an application directory called app/ with three subdirectories: models , views , and controllers . This is a hint that Rails follows the model-view-controller (MVC) architectural pattern, which enforces a separation between "domain logic" (also called "business logic") from the input and presentation logic associated with a graphical user interface (GUI). In the case of web applications, the "domain logic" typically consists of data models for things like users, articles, and products, and the GUI is just a web page in a web browser.

Figure 1.5

Figure 1.5 A schematic representation of the model-view-controller (MVC) architecture.

When interacting with a Rails application, a browser sends a request, which is received by a web server and passed on to a Rails controller, which is in charge of what to do next. In some cases, the controller will immediately render a view, which is a template that gets converted to HTML and sent back to the browser. More commonly for dynamic sites, the controller interacts with a model, which is a Ruby object that represents an element of the site (such as a user) and is in charge of communicating with the database. After invoking the model, the controller then renders the view and returns the complete web page to the browser as HTML.

If this discussion seems a bit abstract right now, worry not; we'll refer back to this section frequently. In addition, Section 2.2.2 has a more detailed discussion of MVC in the context of the demo app. Finally, the sample app will use all aspects of MVC; we'll cover controllers and views starting in Section 3.1.2, models starting in Section 6.1, and we'll see all three working together in Section 6.3.2.

  • + Share This
  • 🔖 Save To Your Account