Rails quick tips #2: Project-specific .pryrc
- ruby rails pry productivity
Like many Ruby and Rails developers I use Pry instead of IRB for almost all of my projects.
Recently I realized that many people are not aware of the fact that pry
supports project-specific .pryrc
files, which can come in very handy, for example when trying things out in a Rails console. Just add a .pryrc
file at the root of your application and add code you want to be available in each console session there. Here’s a modified example from one of our applications:
def admin
@admin ||= Admin.first
end
def user
@user ||= User.first
end
This way when I start a new rails console
session, I can always access admin
or user
and the caching will ensure the database only gets hit the first time the method is called:
[1] (rails_new) main: 0> user
User Load (2.1ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT $1 [["LIMIT", 1]]
#=> #<User id: 1, email: "test@example.com", created_at: "2018-06-26 07:22:18", updated_at: "2018-06-26 07:22:18">
[2] (rails_new) main: 0> user
#=> #<User id: 1, email: "test@example.com", created_at: "2018-06-26 07:22:18", updated_at: "2018-06-26 07:22:18">
I find using project specific .pryrc
files in this way to be a huge productivity boost when trying things out in a Rails console, since they do away with a lot of repetitive setup.