Quick Tip - Boost Your Productivity with Ruby on Rails Console Aliases

 
Keyboard represents IRB console aliases. Photo by Hitarth Jadhav from Pexels

Recently I’ve started using a productivity technique which saves me a lot of unnecessary typing when working with Rails apps. In might seem trivial but I still wanted to share it because it makes my everyday work easier.

Aliases FTW

I am a huge fan of using aliases. Whenever I find myself typing the same characters string more than few times I make an alias out of it. Until recently I was only aliasyfying my bash commands. I even created a tool which helps me track bash commands which are good candidates for an alias.

Currently, I have over 100 bash aliases on my local machine:

aliases | wc -l => 126

Recently I found out that I can also aliasify my workflow in a Rails console. Read on if you are interested how to do it.


Aliases in Rails apps

Well structured Rails apps usually use namespaces to arrange code. While this is great for the app’s architecture it forces you to type stuff like:

Organization::User.find_by(email: '[email protected]')

That’s whopping 60 characters you have to write in order to access an instance of this user in Rails IRB console.

A trick I’ve recently started using was adding the following lines to the .irbrc in the root folder of my Rails project:

def me
  @me ||= Organization::User.find_by(email: "[email protected]")
end

[Update] after the reddit comment post was updated to use method instead of a constant to avoid eager loading of instances on startup.

Another good idea could be to create aliases for all those nicely namespaced classes if you regularly need to use them in the console:

User  = Organization::User
Group = Organization::Group

...

Code added to .irbrc executes only when you run a new interactive Rails console session, whether it is on a local computer or on a remote server. It is not loaded for a web server or background worker processes so you minimize a risk of accidentally overwriting something.

Track stuff worth aliasifying

There is a simple trick to check which of the commands you type in a Rails console should be turned into aliases. Just add the following lines to your .irbrc file in a home folder:

require 'irb/ext/save-history'

IRB.conf[:SAVE_HISTORY] = 10000
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-history"

After a while you can use my gem to analyze a local IRB sessions history:

gem install lazyme
lazyme ~/.irb-history

Summary

Maybe I am too lazy to be a programmer. I just don’t like typing too much. Hope you’ve liked the tip and will save yourself some unnecessary keystrokes.



Back to index