[Ruby on Rails (RoR)] Best practices about Rails Console

Best practices about Rails Console

The rails console command lets you interact with your Rails application from the command line. On the underside, rails console uses IRB deault, 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.

You can also use the alias “c” to invoke the console: rails c.

How to use

Starting Console

Now, we can start rails console using the following command,

1
2
3
4
$ rails console

# or in shorthand
$ rails c

Changing Environment

By default when you run the rails console it fires up in development mode.

1
2
3
$ rails c
Running via Spring preloader in process 72785
Loading development environment (Rails 6.0.0)

If you want to open Rails console in a specific environment, you can use -e option with the environment name.

For example, we want to open Rails console in production mode, Look below.

1
2
3
4
# production mode
$ rails c -e production
Running via Spring preloader in process 72924
Loading production environment (Rails 6.0.0)

Loading production environment.

Sandbox

Sandbox is a very good option for interacting rails application, especially in a production environment. It will roll back or revert all the changes we made in the database once we exit the console session.

If you wish to test out some code without changing any data, you can do that by invoking rails console --sandbox.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ rails c --sandbox
Running via Spring preloader in process 79973
Loading development environment in sandbox (Rails 6.0.0)
Any modifications you make will be rolled back on exit
2.6.1 :001 > Product.destroy(1)

Product Destroy (0.7ms) DELETE FROM "products" WHERE "products"."id" = $1 [["id", 1]]

2.6.1 :002 > Product.find(1)

ActiveRecord::RecordNotFound (Couldn't find Product with 'id'=1)

> exit

ROLLBACK

For the above example, I have deleted a product, when you exit from console session all the database transactions are rollbacked. To start a new session and check it if the database transactions are actually rollbacked or not.

1
2
3
4
5
6
$ rails c
Running via Spring preloader in process 72785
Loading development environment (Rails 6.0.0)
2.6.1 :001 >
2.6.1 :001 > Product.find(1)
=> #<Product id: 1, name: "Apple", ….>

Clearing Console

Sometimes I loathe working at the bottom of the window or when having a huge output data above the space I am working. If you want to clear rails console you can use ctrl + l in a Linux environment or command + k to clear in mac.

Reloading Console

Rails console is running default in the development environment, but it does not reload the new change. At the time of starting rails console, all the files are loaded and stored in a cache up to the end of Rails console. If you need new changes in rails console you can exit from the console and starting a new console session. But it is not a good idea when we frequently changing the code. Instead of this, we can use the following command to refresh new changes.

1
2
3
2.6.1 :002 > reload!
Reloading...
true

Tab Autocomplete

Rails console has default built-in autocomplete functionality. When start typing class name and press TAB once or two, it will autocomplete it or it will display the list of available options. It will work only for default Ruby and Rails built-in class.

1
2
3
4
5
6
7
# Ra with TAB
2.6.1 :001 > Ra
Raabro Rack RailsSemanticLogger RakeFileUtils Range RangesIO Rational
Racc Rails Rake Random RangeError RangesIONonResizeable Raven

# Rail with TAB
2.6.1 :002 > Rails

Searching Command History

Suppose we want to return the already used query or to modify the query and run, the console provides two options.

  1. We can use the up and down arrow, you should recall the previously used commands. Using up arrow ↑ we can to go previously used code by using down arrow ↓ to go back.

  2. suppose you have used a lot of queries in console, using up arrow to finding the query is taking more time. We can use Unix bash shell search command here. By using Ctrl + r we can search the previously used query in backward and return the first query matched on our search string.

  3. in order to enable commands history on rails console or irb you can just add the following to your ~/.irbrc file:

Create, or edit your ~/.irbrc file to include:

1
2
3
4
5
6
require 'irb/ext/save-history'
IRB.conf[:SAVE_HISTORY] = 200
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-history"

IRB.conf[:SAVE_HISTORY] = 200
IRB.conf[:HISTORY_FILE] = '~/.irb-history'

So if you close your rails console or irb the history is persisted. So next time just use the arrows UP ↑ /DOWN ↓ to get your history back.

Last Expression

Sometimes, having typed the query and press enter, it will return the result. Based on this result you can perform some operation. Let’s say, you forgot to assign the result in a variable. If this situation arises, just press the Up arrow and assign to variable and return it.

Rails console provides amazing functionality for this. It stores the last expression in _(underscore) variable.

1
2
3
4
5
6
2.6.1 :001 > 'Ruby On Rails'
"Ruby On Rails"
2.6.1 :002 > _
"Ruby On Rails"
2.6.1 :003 > str = _
"Ruby On Rails"

Extracting frequent statements into class method

When you often need to execute multiple statements in the Rails Console to complete tasks, it is recommended to extract these statements into service or model class methods.

Then, call service or model class methods in the Rails Console.

References

[1] Rails Console Shortcuts, Tips, and Tricks - https://pragmaticstudio.com/tutorials/rails-console-shortcuts-tips-tricks

[2] 10 Rails Console Tips & Shortcuts To Boost The Productivity | ROR Guide - https://www.agiratech.com/blog/rails-console-shortcuts-to-boost-productivity-ruby-on-rails-guide

[3] The Rails Command Line — Ruby on Rails Guides - https://guides.rubyonrails.org/command_line.html#rails-console

[4] Enable commands history on rails console and irb - Today I Learned - https://til.hashrocket.com/posts/09139e5206-enable-commands-history-on-rails-console-and-irb