Rails will set you up with what seems like a huge amount of stuff for such a tiny command! You’ve got the entire Rails directory structure now with all the code you need to run our simple application right out of the box.

This output will seem very familiar when we get to the generate command. Creepy foreshadowing!

1.2 server

Let’s try it! The server command launches a small web server named WEBrick which comes bundled with Ruby. You’ll use this any time you want to view your work through a web browser.

WEBrick isn’t your only option for serving Rails. We’ll get to that in a later section.

Without any prodding of any kind, server will run our new shiny Rails app:

You can install more generators through generator gems, portions of plugins you’ll undoubtedly install, and you can even create your own!

Using generators will save you a large amount of time by writing boilerplate code for you — necessary for the darn thing to work, but not necessary for you to spend time writing. That’s what we have computers for, right?

Let’s make our own controller with the controller generator. But what command should we use? Let’s ask the generator:

All Rails console utilities have help text. As with most *NIX utilities, you can try adding --help or -h to the end, for example ./script/server --help.

Ah, the controller generator is expecting parameters in the form of generate controller ControllerName action1 action2. Let’s make a Greetings controller with an action of hello, which will say something nice to us.

Look there! Now what all did this generate? It looks like it made sure a bunch of directories were in our application, and created a controller file, a functional test file, a helper for the view, and a view file.

Let’s check out the controller and modify it a little (in app/controllers/greetings_controller.rb):

class GreetingsController < ApplicationController
def hello
@message = "Hello, how are you today? I am exuberant!"
end
end

Then the view, to display our nice message (in app/views/greetings/hello.html.erb):

<h1>A Greeting for You!</h1>
<p><%= @message %></p>

Deal. Go check it out in your browser. Fire up your server. Remember? ./script/server at the root of your Rails application should do it.

$ ./script/server
=> Booting WEBrick...

Make sure that you do not have any “tilde backup” files in app/views/(controller), or else WEBrick will not show the expected output. This seems to be a bug in Rails 2.3.0.

The URL will be http://localhost:3000/greetings/hello. I’ll wait for you to be suitably impressed.

With a normal, plain-old Rails application, your URLs will generally follow the pattern of http://(host)/(controller)/(action), and a URL like http://(host)/(controller) will hit the index action of that controller.

“What about data, though?”, you ask over a cup of coffee. Rails comes with a generator for data models too. Can you guess its generator name?

But instead of generating a model directly (which we’ll be doing later), let’s set up a scaffold. A scaffold in Rails is a full set of model, database migration for that model, controller to manipulate it, views to view and manipulate the data, and a test suite for each of the above.

Let’s set up a simple resource called “HighScore” that will keep track of our highest score on video games we play.

Taking it from the top – the generator checks that there exist the directories for models, controllers, helpers, layouts, functional and unit tests, stylesheets, creates the views, controller, model and database migration for HighScore (creating the high_scores table and fields), takes care of the route for the resource, and new tests for everything.

The migration requires that we migrate, that is, run some Ruby code (living in that 20081217071914_create_high_scores.rb) to modify the schema of our database. Which database? The sqlite3 database that Rails will create for you when we run the rake db:migrate command. We’ll talk more about Rake in-depth in a little while.

Let’s talk about unit tests. Unit tests are code that tests and makes assertions about code. In unit testing, we take a little part of code, say a method of a model, and test its inputs and outputs. Unit tests are your friend. The sooner you make peace with the fact that your quality of life will drastically increase when you unit test your code, the better. Seriously. We’ll make one in a moment.

Let’s see the interface Rails created for us. ./script/server; http://localhost:3000/high_scores

We can create new high scores (55,160 on Space Invaders!)

1.4 console

The console command lets you interact with your Rails application from the command line. On the underside, script/console uses IRB, so if you’ve ever used it, you’ll be right at home. This is useful for testing out quick ideas with code and changing data server-side without touching the website.

1.5 dbconsole

dbconsole figures out which database you’re using and drops you into whichever command line interface you would use with it (and figures out the command line parameters to give to it, too!). It supports MySQL, PostgreSQL, SQLite and SQLite3.

1.6 plugin

The plugin command simplifies plugin management; think a miniature version of the Gem utility. Let’s walk through installing a plugin. You can call the sub-command discover, which sifts through repositories looking for plugins, or call source to add a specific repository of plugins, or you can specify the plugin location directly.

Let’s say you’re creating a website for a client who wants a small accounting system. Every event having to do with money must be logged, and must never be deleted. Wouldn’t it be great if we could override the behavior of a model to never actually take its record out of the database, but instead, just set a field?

There is such a thing! The plugin we’re installing is called “acts_as_paranoid”, and it lets models implement a “deleted_at” column that gets set when you call destroy. Later, when calling find, the plugin will tack on a database check to filter out “deleted” things.

1.9 about

Check it: Version numbers for Ruby, RubyGems, Rails, the Rails subcomponents, your application’s folder, the current Rails environment name, your app’s database adapter, and schema version! about is useful when you need to ask for help, check if a security patch might affect you, or when you need some stats for an existing Rails installation.

2 The Rails Advanced Command Line

The more advanced uses of the command line are focused around finding useful (even surprising at times) options in the utilities, and fitting utilities to your needs and specific work flow. Listed here are some tricks up Rails’ sleeve.

2.1 Rails with Databases and SCM

When creating a new Rails application, you have the option to specify what kind of database and what kind of source code management system your application is going to use. This will save you a few minutes, and certainly many keystrokes.

Let’s see what a --git option and a --database=postgresql option will do for us:

It also generated some lines in our database.yml configuration corresponding to our choice of PostgreSQL for database. The only catch with using the SCM options is that you have to make your application’s directory first, then initialize your SCM, then you can run the rails command to generate the basis of your app.

2.2 server with Different Backends

Many people have created a large number different web servers in Ruby, and many of them can be used to run Rails. Since version 2.3, Rails uses Rack to serve its webpages, which means that any webserver that implements a Rack handler can be used. This includes WEBrick, Mongrel, Thin, and Phusion Passenger (to name a few!).

2.4 Rake is Ruby Make

Rake is a standalone Ruby utility that replaces the Unix utility ‘make’, and uses a ‘Rakefile’ and .rake files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.

You can get a list of Rake tasks available to you, which will often depend on your current directory, by typing rake --tasks. Each task has a description, and should help you find the thing you need.

rake --tasks
(in /home/developer/commandsapp)
rake db:abort_if_pending_migrations # Raises an error if there are pending migrations
rake db:charset # Retrieves the charset for the current environment's database
rake db:collation # Retrieves the collation for the current environment's database
rake db:create # Create the database defined in config/database.yml for the current RAILS_ENV
...
...
rake tmp:pids:clear # Clears all files in tmp/pids
rake tmp:sessions:clear # Clears all files in tmp/sessions
rake tmp:sockets:clear # Clears all files in tmp/sockets

Let’s take a look at some of these 80 or so rake tasks.

2.4.1 db: Database

The most common tasks of the db: Rake namespace are migrate and create, and it will pay off to try out all of the migration rake tasks (up, down, redo, reset). rake db:version is useful when troubleshooting, telling you the current version of the database.

2.4.2 doc: Documentation

If you want to strip out or rebuild any of the Rails documentation (including this guide!), the doc: namespace has the tools. Stripping documentation is mainly useful for slimming your codebase, like if you’re writing a Rails application for an embedded platform.

2.4.3 gems: Ruby gems

You can specify which gems your application uses, and rake gems:install will install them for you. Look at your environment.rb to learn how with the config.gem directive.

gems:unpack will unpack, that is internalize your application’s Gem dependencies by copying the Gem code into your vendor/gems directory. By doing this you increase your codebase size, but simplify installation on new hosts by eliminating the need to run rake gems:install, or finding and installing the gems your application uses.

2.4.4 notes: Code note enumeration

These tasks will search through your code for commented lines beginning with “FIXME”, “OPTIMIZE”, “TODO”, or any custom annotation (like XXX) and show you them.

2.4.5 rails: Rails-specific tasks

In addition to the gems:unpack task above, you can also unpack the Rails backend specific gems into vendor/rails by calling rake rails:freeze:gems, to unpack the version of Rails you are currently using, or rake rails:freeze:edge to unpack the most recent (cutting, bleeding edge) version.

When you have frozen the Rails gems, Rails will prefer to use the code in vendor/rails instead of the system Rails gems. You can “thaw” by running rake rails:unfreeze.

After upgrading Rails, it is useful to run rails:update, which will update your config and scripts directories, and upgrade your Rails-specific javascript (like Scriptaculous).

2.4.6 test: Rails tests

Rails comes with a test suite called Test::Unit. It is through the use of tests that Rails itself is so stable, and the slew of people working on Rails can prove that everything works as it should.

The test: namespace helps in running the different tests you will (hopefully!) write.

2.4.7 time: Timezones

You can list all the timezones Rails knows about with rake time:zones:all, which is useful just in day-to-day life.

2.4.8 tmp: Temporary files

The tmp directory is, like in the *nix /tmp directory, the holding place for temporary files like sessions (if you’re using a file store for files), process id files, and cached actions. The tmp: namespace tasks will help you clear them if you need to if they’ve become overgrown, or create them in case of an rm -rf * gone awry.

2.4.9 Miscellaneous Tasks

rake stats is great for looking at statistics on your code, displaying things like KLOCs (thousands of lines of code) and your code to test ratio.
rake secret will give you a psuedo-random key to use for your session secret.
rake routes will list all of your defined routes, which is useful for tracking down routing problems in your app, or giving you a good overview of the URLs in an app you’re trying to get familiar with.