How To: Persist Rails or IRB Console Command History After Exit
If you’ve ever been frustrated by losing your command history after exiting the Rails or IRB console, you’re not alone. Fortunately, there’s a simple solution to ensure your command history is saved and available in future sessions. This guide will show you how to set it up.
Step-by-Step Guide
Step 1: Create or Edit Your .irbrc
File
The .irbrc
file is a configuration file for IRB (Interactive Ruby). If it doesn’t already exist, create it in your home directory:
touch ~/.irbrc
Step 2: Add Configuration to Persist History
Open the .irbrc
file in your favorite text editor and add the following lines:
require 'irb/ext/save-history'
IRB.conf[:SAVE_HISTORY] = 200
IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-history"
Here’s what each line does:
require 'irb/ext/save-history'
: Loads the IRB extension for saving history.IRB.conf[:SAVE_HISTORY] = 200
: Sets the number of commands to save in the history file.IRB.conf[:HISTORY_FILE] = "#{ENV['HOME']}/.irb-history"
: Specifies the file where the history will be saved.
Step 3: Save and Close the File
After adding the configuration, save the .irbrc
file and close your text editor.
Using the Configuration
Now, when you start a new Rails or IRB console session, your command history will be saved to ~/.irb-history
. You can navigate through your command history using the UP and DOWN arrow keys, just like in a regular shell.
Additional Tips
- Increase History Size: If you want to save more than 200 commands, simply increase the number in the
IRB.conf[:SAVE_HISTORY]
line. For example, to save 500 commands:
IRB.conf[:SAVE_HISTORY] = 500
- Custom History File Location: You can change the location of the history file by modifying the
IRB.conf[:HISTORY_FILE]
line. For example:
IRB.conf[:HISTORY_FILE] = "/path/to/your/custom/history/file"
- Rails Console: This configuration works for both IRB and the Rails console, as the Rails console is an IRB session with additional Rails-specific features loaded.
Persisting your Rails or IRB console command history is a small but significant enhancement to your development workflow. By following the steps above, you can ensure that your command history is saved and easily accessible in future sessions, saving you time and effort.
We hope this guide helps you streamline your development process. If you have any questions or additional tips, feel free to share them in the comments below!
Happy coding!