Secrets of Rails Console and Tricks

Reloading the console

When you make some changes your models and need to see those changes reflected in your Rails application in a web browser you just hit Reload Or refresh the whole page. In development  mode, the Rails application loads all the files anew every single time a page is requested. The same is true for the console—but it loads the files anew every time you start the console, instead of per page request.

To avoid having to quit and reopen the console every time you change your application’s code, simply type the follow command:


>> Dispatcher.reset_application!
 
Or, better yet:


>> reload!
 
This is what you’ll see:


>> reload!
Reloading...
 

Rollback all database changes on exit

How to run the console in a sandbox—meaning that all your database changes are completely reverted when you exit the console.
Basically, it looks like this:


$ script/console --sandbox
Loading development environment in sandbox. Any modifications you make will be rolled back on exit.
>>
 

Including things

You can require libraries in the console just like you can in a file containing Ruby code:


require 'mylib'
 
You may have to provide a file path if the file is not in one of the places that the console looks.
 

Examining objects

There are a couple ways to check out objects in the console. The first, of course, is to just make use of the way it shows the inspect method on everything:


>> @user => #<User:0x2645874 @new_record=true, @attributes={"name"=>"john", "job"=>"software developer"}> 
 
But there’s a much more readable alternative:


>> puts @user.to_yaml 
--- !ruby/object:
User attributes: name: john
job: software developer
new_record:true 
=> nil
 
But wait! There’s more! Or, less, really, because there’s a much shorter way:


>> y @user

Specifying console environment

By default, script/console will load itself using your development production environment—unless your environment variables specify otherwise.
You can also tell the console at run-time which environment to start in, simply by tacking the environment name onto your command:


$ script/console production
$ script/console test 
$ script/console development

Entering code

You can enter code into the console just like you would in a file, or another terminal-based application:


>> ['foo','bar','bat'].each { |word| puts word }
foo
bar
bat
=> ["foo", "bar", "bat"]

Or you can enter code involving multiple lines:


>> ['foo','bar','bat'].each do |word|
?>   puts word
>> end
foo
bar
bat
=> ["foo", "bar", "bat"]


Comments

Popular posts from this blog

Inserting and Moving elements inside Ruby Array

Interview Question on Ruby on Rails