Back to blog overview

October 3, 2023

How to Automatically Initialize Variables for Every Rails Console Session

Sunjay Armstead

&

&

UI/UX Designer and Engineer II
Louisburg, NC

When developing features for a Rails app, I find myself in the magical world of Rails console quite a bit. One headache I run into almost every day is that I have to declare the same variables every time I fire up the console. For example, many of my development tasks require fetching the same test admin user for every session, as well as several instances of its associated models.

Let’s do the math: if I open the console 5 times a day for 5 days a week, and declare at least 3 variables each time, that’s 75 variable declarations per week. YUCK! 🤢

What if I told you that there’s a way to have variables already set for you when you open up your Rails console? Oh yeah, let the magic begin. 🪄

## 1. Make an `rc` file

Some versions of Rails use `pry` to run the console, and others use `irb`. We’ll use `pry` for the examples in this post, but similar steps can be taken with `irb`.

So, first up, create a `.pryrc` file in your home directory (`touch ~/.pryrc`) and open it in your favorite editor. Essentially, every time we run Rails console we want to also run a script that initializes our variables. We’ll therefore `require` an initialize script in that file:

```ruby
# When a Rails pry console is started, find and load the console-init.rb file in the working directory
begin
 require Dir.pwd + "/bin/console-init.rb"
rescue LoadError
 nil
end
```

### In the weeds

Maybe you saw the code snippet above and are totally cool with pasting it into a file within your home directory. If that’s you, feel free to skip this section and move on to the next step.

So, what’s going on here? First, what is all this business about `rc` files? [Hiks Gerganov notes](https://www.baeldung.com/linux/rc-files) that an `rc` file “consists of commands that are meant to run when a program is executed”. There’s a whole history behind `rc` files in Unix systems, as well as a quandary of possibilities for what “rc” could stand for. Suffice to say: we use an `rc` file to run additional (custom) code when a particular program is executed. You may have also seen `.zshrc` and `.bashrc` files that work in a similar way.

Next, did you see that `rescue` block? Since this `rc` file is in my home directory, it will load in every Rails project I have locally. There may be some cases where I am not using an initialize script for the console, so returning `nil` allows me to suppress any `LoadError`'s that are returned.

Finally, notice that the file our script requires lives in a `bin` directory of the current working directory. Most Rails apps have this folder, so you’d place the `console-init.rb` file (discussed in a future step) in that directory.

Now, alarm bells may be blaring in your mind at this point and you may have just smashed the caps lock on your keyboard to chew me out about not committing the `console-init.rb` file in your Git history. I know, I know. We’re going to take care of that next.

## 2. Add your init file path to (global) `gitignore`

If you don’t want to check in the `console-init.rb` file that we’ll build here soon, you could add the filename to your application’s `.gitignore` file. This may not always be ideal if the script you are running is not shared across your team. Instead, I like to add one-off scripts like this to a *******global******* Git config that will always ignore this file across projects. Here’s how to do that:

- Create a `.gitignore_global` file in your home directory (`touch ~/.gitignore_global`).
- Add the init file path into your `.gitignore_global` file:
   
   ```text
   bin/console-init.rb
   ```
   
- Add the `.gitignore_global` file as a core exclusion file in your Git config. You can either run `git config --global core.excludesfile "~/.gitignore_global"` or add the following to the `.gitconfig` file in your home directory:
   
   ```text
   [core]
     excludesfile = ~/.gitignore_global
   ```
   

Now every Git repository on your computer will exclude whatever is listed in your global ignore file, in this case `bin/console-init.rb`.

## 3. Create your variables!

At this point, you can go into any Rails project locally and add your init file to the `bin` directory. Below is an example of how to initialize a few constants for every Rails console session:

```ruby
puts "\nRunning console init file...\n"

# Temporarily turn off SQL logging
standard_sql_logger = ActiveRecord::Base.logger
ActiveRecord::Base.logger = nil

# Define constants
U = User.find_by(role: 'admin')
C = U.car
T = C.type

constants_hash = {
 U: [U.id, U.email],
 C: [C.id, C.name],
 T: [T.id, T.name],
}

teal_color = "[1;36;1m"
magenta_color = "[1;35;1m"
reset_color = "[0m"

puts "\n\e#{teal_color}Initialized Constants:\e#{reset_color}\n"

constants_hash.each do |constant|
 print "\e#{magenta_color}#{constant[0]}: #{constant[1]}\e#{reset_color}\n"
end

puts "\n"

# Turn SQL logging back on
ActiveRecord::Base.logger = standard_sql_logger
```

### A few important notes

- You’ll notice that I temporarily turned off SQL logging during the initialization process. That’s because the SQL output of this file is far too messy and overwhelming for simply opening a console. *Just make sure you turn logging back on* (see end of code block above) for proper debugging the rest of your console session.
- Your variables must be defined as constants if you want Rails console to include them in the session. Any regular variable is not accessible once you start your console session.
- I set certain lines to be either teal or magenta colors. You can follow the example above if you’d like to do the same, or simply jump down to the Resources section to see more colors that you can use.

## 4. Run Rails console

All of your set up is now complete. Go ahead and run `bin/rails c`!

Here’s an example of the output you may get:

```ruby
$ bin/rails c

Loading development environment (Rails 6.1.7.3)

Running console init file...

Initialized Constants:
U: ["158162a4-5d74-11ee-8c99-0242ac120002", "sunjaymunjay@dev.int"]
C: ["547e2712-5d74-11ee-8c99-0242ac120002", "Mazada"]
T: ["75576822-5d74-11ee-8c99-0242ac120002", "Hybrid"]

[1] pry(main)>
```

Anytime you run Rails console, you now have access to three constants: `U` for the user, `C` for the user’s car, and `T` for the user’s car type. No more repetitive set up!

This means that you can do all of your regular development tasks as normal:

```ruby
U.username # Returns "@notsofunjay"
U.update(username: "@munjayfunjay")
U.username # Returns "@munjayfunjay"
```

### One important “gotcha”

Your constants are stored in memory. That means that if you change the database *outside of your session*, you will need to reload your constants to reflect those changes.

For example: if I update my username in my web app (which ultimately changes a row in the database), calling `U.username` in a Rails console that’s already opened will not return the correct value. Instead, you’ll need to call `reload`:

```ruby
U.username # Returns the old value, "@notsofunjay"
U.reload # Basically goes back and makes a fresh SQL query
U.username # Now returns the updated value, "@munjayfunjay"
```

## That’s a wrap

Rails console is a great tool for building robust Ruby on Rails apps. If you’ve been working on a project for a while, however, there may come a day when you’ve had enough of declaring the same session variables every single time. I hope that the steps and commentary in this post will help save you some frustration. Enjoy!

## Resources

- [https://guides.rubyonrails.org/command_line.html#bin-rails-console](https://guides.rubyonrails.org/command_line.html#bin-rails-console)
- [https://stackoverflow.com/questions/18553944/init-some-variables-when-opening-rails-console/18559485#18559485](https://stackoverflow.com/questions/18553944/init-some-variables-when-opening-rails-console/18559485#18559485)
- [https://www.oreilly.com/library/view/linux-shell-scripting/9781785881985/b0ddd805-aa79-441d-b5a7-380c66c7712d.xhtml](https://www.oreilly.com/library/view/linux-shell-scripting/9781785881985/b0ddd805-aa79-441d-b5a7-380c66c7712d.xhtml)
- [https://gist.github.com/swanson/3ca98caff43d52f62b4b99f6f2c7444c](https://gist.github.com/swanson/3ca98caff43d52f62b4b99f6f2c7444c)

Photo by Will Porada on Unsplash

Let's Chat

Are you ready to build something brilliant? We're ready to help.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.
RedwoodJS Logo
RedwoodJS
Conference

conference
for builders

Grants Pass, Oregon • September 26 - 29, 2023
View All