- 1.1. Introduction
- 1.2. Up and Running
- 1.3. Version Control with Git
- 1.4. Deploying
- 1.5. Conclusion
1.2. Up and Running
- I think of Chapter 1 as the “weeding out phase” in law school—if you can get your dev environment set up, the rest is easy to get through.
- —Bob Cavezza, Rails Tutorial reader
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 types: text editor/command line environments, and integrated development environments (IDEs). Let’s consider the latter first.
IDEs
There is no shortage of Rails IDEs, including RadRails, RubyMine, and 3rd Rail. I’ve heard especially good things about RubyMine, and one reader (David Loeffler) has assembled notes on how to use RubyMine with this tutorial.7 If you’re comfortable using an IDE, I suggest taking a look at the options mentioned to see what fits with the way you work.
Text Editors and Command Lines
Instead of using an IDE, I prefer to 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.
- Text editor: I recommend Sublime Text 2, an outstanding cross-platform text editor that is in beta as of this writing but has already proven to be exceptionally powerful. Sublime Text is heavily influenced by TextMate, and in fact is compatible with most TextMate customizations, such as snippets and color schemes. (TextMate, which is available only on OS X, is still a good choice if you use a Mac.) A second excellent choice is Vim,8 versions of which are available for all major platforms. Sublime Text is a commercial product, whereas Vim is free and open-source; both are industrial-strength editors, but Sublime Text is much more accessible to beginners.
- Terminal: On OS X, I recommend either use iTerm or the native Terminal app. On Linux, the default terminal is fine. On Windows, many users prefer to develop Rails applications in a virtual machine running Linux, in which case your command-line options reduce to the previous case. If developing within Windows itself, I recommend using the command prompt that comes with Rails Installer (Section 1.2.2).
Figure 1.1. A text editor/command line development environment (TextMate/iTerm).
If you decide to use Sublime Text, you might want to follow the setup instructions for Rails Tutorial Sublime Text.9 Note: Such configuration settings are fiddly and error-prone, so this step should only be attempted by advanced users.
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, both Safari and Chrome have a built-in “Inspect element” feature available by right-clicking on any part of the page.
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 Sublime Text 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, and in the end the reward is worth the effort.
1.2.2. Ruby, RubyGems, Rails, and Git
- Practically all the software in the world is either broken or very difficult to use. So users dread software. They’ve been trained that whenever they try to install something, or even fill out a form online, it’s not going to work. I dread installing stuff, and I have a Ph.D. in computer science.
- —Paul Graham, Founders at Work
Now it’s time to install Ruby and Rails. I’ve done my best to cover as many bases as possible, but systems vary, and many things can go wrong during these steps. Be sure to Google the error message or consult the Rails Tutorial help page if you run into trouble.
Unless otherwise noted, you should use the exact versions of all software used in the tutorial, including Rails itself, if you want the same results. Sometimes minor version differences will yield identical results, but you shouldn’t count on this, especially with respect to Rails versions. The main exception is Ruby itself: 1.9.2 and 1.9.3 are virtually identical for the purposes of this tutorial, so feel free to use either one.
Rails Installer (Windows)
Installing Rails on Windows used to be a real pain, but thanks to the efforts of the good people at Engine Yard—especially Dr. Nic Williams and Wayne E. Seguin—installing Rails and related software on Windows is now easy. If you are using Windows, go to Rails Installer and download the Rails Installer executable and view the excellent installation video. Double-click the executable and follow the instructions to install Git (so you can skip Section 1.2.2), Ruby (skip Section 1.2.2), RubyGems (skip Section 1.2.2), and Rails itself (skip Section 1.2.2). Once the installation has finished, you can skip right to the creation of the first application in Section 1.2.3.
Bear in mind that the Rails Installer might use a slightly different version of Rails from the one installed in Section 1.2.2, which might cause incompatibilities. To fix this, I am currently working with Nic and Wayne to create a list of Rails Installers ordered by Rails version number.
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.3
to see the version number. Rails 3 requires Ruby 1.8.7 or later and works best with Ruby 1.9.x. This tutorial assumes that most readers are using Ruby 1.9.2 or 1.9.3, but Ruby 1.8.7 should work as well (although there is one syntax difference, covered in Chapter 4, and assorted minor differences in output).
As part of installing Ruby, if you are using OS X or Linux, I strongly recommend 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 different versions of Ruby or Rails on the same machine. 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).10 If you are running Linux, I particularly recommend the installation tutorial for Linux Ubuntu and Linux Mint by Mircea Goia.
After installing RVM, you can install Ruby as follows:11
$ rvm get head && rvm reload
$ rvm install 1.9.3
<wait a while>
Here the first command updates and reloads RVM itself, which is a good practice since RVM gets updated frequently. The second installs the 1.9.3 version of Ruby; depending on your system, it might take a while to download and compile, so don’t worry if it seems to be taking forever.
Some Linux users report having to include the path to a library called OpenSSL:
$ rvm install 1.9.3 --with-openssl-dir=$HOME/.rvm.usr
On some older OS X systems, you might have to include the path to the readline library:
$ rvm install 1.9.3 --with-readline-dir=/opt/local
(Like I said, lots of things can go wrong. The only solution is web searches and determination.)
After installing Ruby, you should configure your system for the other software needed to run Rails applications. This typically involves installing 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. For the purposes of this tutorial, I suggest creating a gemset called rails3tutorial2ndEd:
$ rvm use 1.9.3@rails3tutorial2ndEd --create --default
Using /Users/mhartl/.rvm/gems/ruby-1.9.3 with gemset rails3tutorial2ndEd
This command creates (--create) the gemset rails3tutorial2ndEd associated with Ruby 1.9.3 while arranging to start using it immediately (use) and setting it as the default (--default) gemset, so that any time we open a new terminal window the 1.9.3@rails3tutorial2ndEd Ruby/gemset combination is automatically selected. RVM supports a large variety of commands for manipulating gemsets; see the documentation at http://rvm.beginrescueend.com/gemsets. 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 many useful 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-1.9.3-p0/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:
$ ruby setup.rb
(If you get a permissions error here, recall from Section 1.1.3 that you may have to use sudo.)
If you already have RubyGems installed, you should make sure your system uses the version used in this tutorial:
$ gem update --system 1.8.24
Freezing your system to this particular version will help prevent conflicts as RubyGems changes in the future.
When installing gems, by default RubyGems generates two different kinds of documentation (called ri and rdoc), but many Ruby and Rails developers find that the time to build them isn’t worth the benefit. (Many programmers rely on online documentation instead of the native ri and rdoc documents.) To prevent the automatic generation of the documentation, I recommend making a gem configuration file called .gemrc in your home directory as in Listing 1.1 with the line in Listing 1.2. (The tilde “~” means “home directory,” while the dot . in .gemrc makes the file hidden, which is a common convention for configuration files.)
Listing 1.1. Creating a gem configuration file.
$
subl ~/.gemrc
Here subl is the command-line command to launch Sublime Text on OS X, which you can set up using the Sublime Text 2 documentation for the OS X command line. If you’re on a different platform, or if you’re using a different editor, you should replace this command as necessary (i.e., by double-clicking the application icon or by using an alternate command such as mate, vim, gvim, or mvim). For brevity, throughout the rest of this tutorial I’ll use subl as a shorthand for “open with your favorite text editor.”
Listing 1.2. Suppressing the ri and rdoc documentation in .gemrc.
install: --no-rdoc --no-ri
update: --no-rdoc --no-ri
Install Rails
Once you’ve installed RubyGems, installing Rails should be easy. This tutorial standardizes on Rails 3.2, which we can install as follows:
$ gem install rails -v 3.2.3
To check your Rails installation, run the following command to print out the version number:
$ rails -v
Rails 3.2.3
Note: If you installed Rails using the Rails Installer in Section 1.2.2, there might be slight version differences. As of this writing, those differences are not relevant, but in the future, as the current Rails version diverges from the one used in this tutorial, these differences may become significant. I am currently working with Engine Yard to create links to specific versions of the Rails Installer.
If you’re running Linux, you might have to install a couple of other packages at this point:
$ sudo apt-get install libxslt-dev libxml2-dev libsqlite3-dev # Linux only
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.3):
Listing 1.3. Running rails to generate a new application.
$
mkdir rails_projects$
cd
rails_projects$
rails new first_appcreate create README.rdoc create Rakefile create config.ru create .gitignore create Gemfile create app create app/assets/images/rails.png create app/assets/javascripts/application.js create app/assets/stylesheets/application.css create app/controllers/application_controller.rb create app/helpers/application_helper.rb create app/mailers create app/models create app/views/layouts/application.html.erb create app/mailers/.gitkeep create app/models/.gitkeep create config create config/routes.rb create config/application.rb create config/environment.rb . . . create vendor/plugins create vendor/plugins/.gitkeep run bundle install Fetching source index for https://rubygems.org/ . . . Your bundle is complete! Use 'bundle show [gemname]' to see where a bundled gem is installed.
As seen at the end of Listing 1.3, running rails automatically runs the bundle install command after the file creation is done. If that step doesn’t work right now, don’t worry; follow the steps in Section 1.2.4 and you should be able to get it to work.
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. In particular, starting in Section 5.2.1 we’ll discuss the app/assets directory, part of the asset pipeline (new as of Rails 3.1) that makes it easier than ever to organize and deploy assets such as cascading style sheets and JavaScript files.
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 |
app/assets |
Applications assets such as cascading style sheets (CSS), JavaScript files, and images |
config/ |
Application configuration |
db/ |
Database files |
doc/ |
Documentation for the application |
lib/ |
Library modules |
lib/assets |
Library assets such as cascading style sheets (CSS), JavaScript files, and images |
log/ |
Application log files |
public/ |
Data accessible to the public (e.g., web browsers), such as error pages |
script/rails |
A script for generating code, opening console sessions, or starting a local 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 |
vendor/assets |
Third-party assets such as cascading style sheets (CSS), JavaScript files, and images |
README.rdoc |
A brief description of the application |
Rakefile |
Utility tasks available via the rake command |
Gemfile |
Gem requirements for this app |
Gemfile.lock |
A list of gems used to ensure that all copies of the app use the same gem versions |
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. As noted briefly in Section 1.2.3, Bundler is run automatically (via bundle install) by the rails command, but in this section we’ll make some changes to the default application gems and run Bundler again. This involves opening the Gemfile with your favorite text editor:
$ cd first_app/
$ subl Gemfile
The result should look something like Listing 1.4. The code in this file is Ruby, but don’t worry at this point about the syntax; Chapter 4 will cover Ruby in more depth.
Listing 1.4. The default Gemfile in the first_app directory.
source'https://rubygems.org'
gem'rails'
,'3.2.3'
# Bundle edge Rails instead: # gem 'rails', :git => 'git://github.com/rails/rails.git' gem'sqlite3'
# Gems used only for assets and not required # in production environments by default. group:assets do
gem'sass-rails'
,'~> 3.2.3'
gem'coffee-rails'
,'~> 3.2.2'
gem'uglifier'
,'>= 1.2.3'
end
gem'jquery-rails'
# To use ActiveModel has_secure_password # gem 'bcrypt-ruby', '~> 3.0.0' # To use Jbuilder templates for JSON # gem 'jbuilder' # Use unicorn as the web server # gem 'unicorn' # Deploy with Capistrano # gem 'capistrano' # To use debugger # gem 'ruby-debug19', :require => 'ruby-debug'
Many 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, some gems related to the asset pipeline (Section 5.2.1), the gem for the jQuery JavaScript library, 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 of the gem. Unfortunately, gem updates often cause minor but potentially confusing breakage, so in this tutorial we’ll include explicit version numbers known to work, as seen in Listing 1.5 (which also omits the commented-out lines from Listing 1.4).
Listing 1.5. A Gemfile with an explicit version of each Ruby gem.
source'https://rubygems.org'
gem'rails'
,'3.2.3'
group:development
do
gem'sqlite3'
,'1.3.5'
end
# Gems used only for assets and not required # in production environments by default. group:assets
do
gem'sass-rails'
,'3.2.4'
gem'coffee-rails'
,'3.2.2'
gem'uglifier'
,'1.2.3'
end
gem'jquery-rails'
,'2.0.0'
Listing 1.5 changes the line for jQuery, the default JavaScript library used by Rails, from
gem 'jquery-rails'
to
gem 'jquery-rails', '2.0.0'
We’ve also changed
gem 'sqlite3'
to
group :development do
gem 'sqlite3', '1.3.5'
end
which forces Bundler to install version 1.3.5 of the sqlite3 gem. Note that we’ve also taken this opportunity to arrange for SQLite to be included only in a development environment (Section 7.1.1), which prevents potential conflicts with the database used by Heroku (Section 1.4).
Listing 1.5 also changes a few other lines, converting
group :assets do
gem 'sass-rails', '~> 3.2.3'
gem 'coffee-rails', '~> 3.2.2'
gem 'uglifier', '>= 1.2.3'
end
to
group :assets do
gem 'sass-rails', '3.2.4'
gem 'coffee-rails', '3.2.2'
gem 'uglifier', '1.2.3'
end
The syntax
gem 'uglifier', '>= 1.2.3'
installs the latest version of the uglifier gem (which handles file compression for the asset pipeline) as long as it’s greater than version 1.2.3—even if it’s, say, version 7.2. Meanwhile, the code
gem 'coffee-rails', '~> 3.2.2'
installs the gem coffee-rails (also needed by the asset pipeline) as long as it’s lower than version 3.3. In other words, the >= notation always performs upgrades, whereas the ~> 3.2.2 notation only performs upgrades to minor point releases (e.g., from 3.1.1 to 3.1.2), but not to major point releases (e.g., from 3.1 to 3.2). Unfortunately, experience shows that even minor point releases often break things, so for the Rails Tutorial we’ll err on the side of caution by including exact version numbers for virtually all gems. (The only exception is gems that are in release candidate or beta stage as of this writing; for those gems, we’ll use ~> so that the final versions will be loaded once they’re done.)
Once you’ve assembled the proper Gemfile, install the gems using bundle install:
$ bundle install
Fetching source index for https://rubygems.org/
.
.
.
(If you’re running OS X and you get an error about missing Ruby header files (e.g., ruby.h) at this point, you may need to install Xcode. These are developer tools that came with your OS X installation disk, but to avoid the full installation I recommend the much smaller Command Line Tools for Xcode.12) The bundle install command might take a few moments, but when it’s done our application will be ready to run. Note: This setup is fine for the first app, but it isn’t ideal. Chapter 3 covers a more powerful (and slightly more advanced) method for installing Ruby gems with Bundler.
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, visible only from your development machine:13
$ rails server
=> Booting WEBrick
=> Rails application starting on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
(If your system complains about the lack of a JavaScript runtime, visit the execjs page at GitHub for a list of possibilities. I particularly recommend installing Node.js.) This tells us that the application is running on port number 300014 at the address 0.0.0.0. This address tells the computer to listen on every available IP address configured on that specific machine; in particular, we can view the application using the special address 127.0.0.1, which is also known as localhost. We can see the result of visiting http://localhost:3000/ in Figure 1.3.
Figure 1.3. The default Rails page.
To see information about our first application, click on the link “About your application’s environment.” The result is shown in Figure 1.4. (Figure 1.4 represents the environment on my machine when I made the screenshot; your results may differ.)
Figure 1.4. The default page 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.3.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. 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 7.1.2.