home blog about

Your own convenience methods with .pryrc/.irbrc

Context

.pryrc (or .irbrc if you are using that) is a file that is loaded every time you start a pry (irb) session.

This can be used in development to store methods you regularly use, scripts you often run or humanize object names.

Example

# ~/.pryrc or ~/.irbrc

puts <<~TEXT
    Your convenience methods:
    - rev                            # Select 2 random reviewers for your PR
    - kevin                          # User
    - dunder_mifflin                 # Company
    - scranton_branch                # Property
    - give_properties_access(user)   # Grand access to all properties to a user
    - give_full_access(user)         # Grand access to all companies to a user
TEXT

def rev
  puts %w[@michael @jim @dwight @oscar @meredith].sample(2).join(', ')
end

def kevin
  User.find("c1d1f20a-2185-4d96-8152-32f12783c9fd")
end

def dunder_mifflin
  Company.find("362db3af-eac1-4c04-89c3-eb6fe6ca8f4e")
end

def scranton_branch
  Property.find("dc33e292-385a-4237-bd98-ea61510c4c1a")
end

# E.g.: give_properties_access(kevin)
def give_properties_access(user)
  Property.all.each do |property|
    Properties::Permission.find_or_create_by!(user:, property: )
  end
end

def give_full_access(user)
  Company.all.each do |company|
    permission = Companies::Permission.find_or_create_by!(user:, company:)
    can_attributes = permission.attributes.keys.select { |attr_name| attr_name.start_with?('can_') }
    permission.update!(can_attributes.index_with { |_attr_name| true })
  end
end

You can store this file in your home directory, or in the root of your project, and it will be picked up automatically.

If you store them in your project root, make sure to .gitignore these files,
unless you want to share them with your team and make them available outside your local environment.