3.6. The Rails Console

The console in Rails is nothing more than an irb (see Section 2.3, “irb”) built around the Rails environment. The console is very useful both for developing and for administration purposes, because the whole Rails environment is represented and available.
For our working environment, we again use a variation of the ping pong scenario from Section 3.4, “Redirects”:
$ rails new pingpong
      [...]
$ cd pingpong 
$ rails generate controller Game ping pong
      [...]
$
Start the Rails console with the command rails console:
$ rails console
Loading development environment (Rails 4.0.0)
2.0.0-p247 :001 > 
And you can use exit to get back out:
2.0.0-p247 :001 > exit
$ 
Many readers use this document on mobile devises. For them I try to keep any code or terminal output width to a minimum. To save the real estate which is by default occupied by 2.0.0-p247 :001 > we can start rails console with the parameter -- --simple-prompt.
$ rails console -- --simple-prompt
Loading development environment (Rails 4.0.0)
>> exit
$
Alternativly you can change the IRB configuration in the file .irbrc which is located in your home directory. If you want to have the simple prompt you have to add the following line in that file.
IRB.conf[:PROMPT_MODE] = :SIMPLE
In the console, you have access to all variables that are also available later in the proper application:
$ rails console
Loading development environment (Rails 4.0.0)
>> Rails.env
=> "development"
>> Rails.root
=> #<Pathname:/Users/xyz/pingpong>
>> exit
$
Already in Chapter 4, ActiveRecord we are going to be working lots with the console and will soon begin to appreciate the possibilities it offers.

Buy the new Rails 5.1 version of this book.

One of my best buddies when developing Rails applications is the Tab key. Whenever you are looking for a method for a particular problem, recreate it in the Rails console and then press the Tab key twice to list all available methods. The names of the methods are usually self-exlanatory.

app

app is useful if you want to analyze things to do with routing:
$ rails console
Loading development environment (Rails 4.0.0)
>> app.url_for(:controller => 'game', :action => 'ping')
=> "http://www.example.com/game/ping"
>> app.get 'game/ping'


Started GET "/game/ping" for 127.0.0.1 at 2013-07-15 19:19:36 +0200
Processing by GameController#ping as HTML
Redirected to http://www.example.com/game/pong
Completed 302 Found in 16ms (ActiveRecord: 0.0ms)
=> 302
>> app.get 'game/pong'


Started GET "/game/pong" for 127.0.0.1 at 2013-07-15 19:19:39 +0200
Processing by GameController#pong as HTML
  Rendered game/pong.html.erb within layouts/application (0.9ms)
Completed 200 OK in 50ms (Views: 49.2ms | ActiveRecord: 0.0ms)
=> 200
>> exit
$

Thank you for your support and the visibility by linking to this website on Twitter and Facebook. That helps a lot!