At Agira, Technology Simplified, Innovation Delivered, and Empowering Business is what we are passionate about. We always strive to build solutions that boost your productivity.

,

Listing 10 Rails Console Tips & Shortcuts To Boost The Productivity

  • By Arjunan Subramani
  • August 6, 2019
  • 2254 Views

Rails console is the back door of the Rails application.
In this blog, you are going to learn the tips and shortcuts on the Rails console that can boost productivity.
I want to share with you, all the commands to interact with the Rails app. I’ve have been using Rails console parallelly when writing an application. I’ve to say that these commands below are a breakthrough in productivity. As a Rails developer, Rails console was an immense help of my prolificacy.
Why use Rails console?
With Rails console you can interact with the Rails application from the command line, without using the web browser. It is a powerful IRB shell loaded with Rails environment.
You can also use Rails console for query database, test or debug our rails application without using browser interaction.
A plentiful of developers at the beginner level are not aware of this fact. Rails console is an effective time-saver. You can test the command within the backend application. These methods here can make it easy peasy for you.
You no longer have to wait in front of the browser to test your output.
Turn the tides!

Starting Console

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

$ rails console

or in shorthand

$ rails c

Changing Environment

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

$ rails console
Loading development environment (Rails 5.2.3)

 
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.

$ rails console -e production
Loading production environment (Rails 5.2.3)

 

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. Clear bash command is not working in the Rails console. It will return the following error.

> clear
NameError (undefined local variable or method `clear' for main:Object)

 
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

In the development environment, the application code will reload for every new request automatically. Sometimes when you change or add new things, you need to reload the browser to see those changes in rails application
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.
 

> reload!
Reloading...
 => true

 

Autocomplete

Rails console has default built-in autocomplete functionality. When start typing class name and press TAB, 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.

> Hash TAB
Hash  HashWithIndifferentAccess

 
 
we can also use autocomplete for method names of any class or object.

> Hash.TAB
Display all 179 possibilities? (y or n)

 
Suppose you want to auto-complete model and controller available in /app directory, which is not possible for the first time. If you have already used Rails console, then it is possible for the second time. For example, we have ‘Product’ model. We have already used in rails console and now we want to use it to run query. Now, We can Type ‘Pro’ it will return the available options.

 > Pro TAB
Proc     Process Product

 
 
Suppose you type ‘Prod’ it will auto-complete the Product model.

> Prod TAB
> Product

 
 
suppose you want to autocomplete user-defined methods available within the model, we get it from product object
 

> product.ge
product.gem                product.get_discount_amt product.get_product_name   product.get_selling_price

 
 

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.

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.
For example, we have Product model and we get all products have MRP less the 100;
 

Product.where('mrp < 100')

 
 
Now, Hit the Enter, it will return the result. You can assign those results back in some variable. _ value is continuously changing based on the last expression we have run.
 

> products = _
> products.count 
=> 12

 
 
Now we check with _ variable. It has a value of 12 because it stored the last expression value only.
 

> _
=> 12

 
 

Disable CSRF Token

 
For Example, you want to check the product create method via console, Here, I have used the following line to call the product to create a method
 

> app.post "/products", params: {name: "pen"}

 
 
It will return the following response,
 

Started POST "/products" for 127.0.0.1 at 2019-08-03 22:00:09 +0530
Processing by ProductsController#create as HTML
  Parameters: {"name"=>"pen"}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 2ms (ActiveRecord: 0.0ms)
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
(irb):22:in `irb_binding'
 => 422

 
 
Using the following command you can disable the CSRF token authenticity.
 

ApplicationController.allow_forgery_protection = false

 
 
Now you can call the product to create a method, it will work as expected.

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.
For example, we will test some code in console without changing data, which can invoke rails console with –sandbox option
 

$ rails console -e production --sandbox 
Loading production environment in sandbox (Rails 5.2.3)
Any modifications you make will be rolled back on exit

 
 
Let’s we try to delete product to test –sandbox option
 

> Product.destroy(1)
Product Destroy (0.7ms)  DELETE FROM "products" WHERE "products"."id" = $1  [["id", 1]]
> 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.

$ rails console -e production --sandbox 
> Product.find(1)
=> #<Product id: 1, name: "Apple", ….>

 
If we really need to change data, we can remove –sandbox option
 

Source Location

While working in rails console using source_location method we can see where the method is defined and implementation details of the method. For example, our Product model has discount_amount instance method, we can get the location of discount_amount method like following
 

> Product.instance_method(:discount_amount).source_location
 => ["/home/arjun/Sampl_work/rr/app/models/product.rb", 7]

 
 
We can’t call source_location directly. First, we need to call instance_method on the Product model by passing the method name as an argument, this will return the object, It represents the discount_amount method. From this object, we can call the source location of the method.
Source location returns output as an array of two values. The first value represents the location of the file and the second value represents the line number where the method is defined.

Helper methods

We want to check out view helpers before we are using in the view template. Run all view helpers method directly from console using helper variable, we can also test our custom helper methods.
 

 > helper.pluralize(5, 'person')
 => "5 people"
> helper.number_to_currency(100)
 => "$100.00"
 > helper.number_to_human(1000)
 => "1 Thousand"

 
 
If you want to know all the available helper methods, use the following command in rails console it will return available method lists
 

 > helper.methods

 
 

Listing tables

Suppose you want to know how many tables we have used in our database, you can use the following command to list all the table names
 

> ActiveRecord::Base.connection.tables
 => ["schema_migrations", "ar_internal_metadata", "products", "articles"]

 

Read more on :

Testing Rails applications – Complete Ruby On Rails Testing Guide

Final Thoughts…

Every time you experiment a logic there is no need to start a new console over and over again. If there’s a need for change or adding new codes, you can save loads of time by using the methods I’ve talked about throughout the blog.
If you are familiar with the basis of Listing Rails Console, you would have recognized the mistakes that you were making in the console. Start trying these tips and shortcuts of Rails console that will not only boost your productivity but also can make you a thriving developer.
I believe that this listing would make your flickering lights shine bright!
For any further clarification and doubts, please use the comment box below. If you need more trending updates on technology, follow Agira blog. You can also use the free Subscription below and get all the updates handy.
Which one of the Rail Console commands you’re going to try right now?

Arjunan Subramani

Senior Software Engineer | Around 4 Years of experience in Web development and Testing arena. Plus, hands on expertise in Ruby, Ruby on Rails, Watir, Ruby Cucumber.