Hackernoon logoYou Can Do More With Rails Console by Configuring ~/.irbrc 🎉 by@rishipithadiya

You Can Do More With Rails Console by Configuring ~/.irbrc 🎉

Author profile picture

@rishipithadiyaRishi Pithadiya

Finding happiness in words, food, places & untold stories ✌🏼

It´s better to wait for a productive programmer to become available than it is to wait for the first available programmer to become productive. — Steve McConnell
What is ~/.irbrc file? 🔖
  • After work with multiple Rails apps, you might have some methods and preferred ways of working with them. 
  • i.e. you're using few generalized methods or configuration your IRB session(rails console) in a single project and want to have the same methods & configuration on other projects you’re working on, you can add those methods & configuration in your ~/.irbrc file.
  • You can create ~/.irbrc file in your root directory if it’s not present.
Things you can include in your ~/.irbrc file 🗄
  • Configurations which need to be used in all Rails Apps
  • Methods which need to be used in all Rails Apps
  • Require/load specific file(s) or Gem(s)
  • Hacky convenience methods that help you play with your objects
My .irbrc file 🧮
require 'irb/completion'
require 'rubygems'

ActiveRecord::Base.logger.level = 1 if defined?(ActiveRecord)
IRB.conf[:SAVE_HISTORY] = 1000

# Overriding Object class
class Object
  # Easily print methods local to an object's class
  def lm
    (methods - Object.instance_methods).sort

  # look up source location of a method
  def sl(method_name)
    self.method(method_name).source_location rescue "#{method_name} not found"

  # open particular method in vs code
  def ocode(method_name)
    file, line = self.sl(method_name)
    if file && line
      `code -g '#{file}:#{line}'`
      "'#{method_name}' not found :(Try #{self.name}.lm to see available methods"

  # display method source in rails console
  def ds(method_name)

  # open json object in VS Code Editor
  def oo
    tempfile = File.join(Rails.root.join('tmp'), SecureRandom.hex)
    File.open(tempfile,'w') {|f| f << self.as_json}
    system("#{'code'||'nano'} #{tempfile}")
    File.delete( tempfile )

# history command
def hist(count = 0)
  # Get history into an array
  history_array = Readline::HISTORY.to_a

  # if count is > 0 we'll use it.
  # otherwise set it to 0
  count = count > 0 ? count : 0

  if count > 0
    from = history_array.length - count
    history_array = history_array[from..-1]

  print history_array.join("\n")

# copy a string to the clipboard
def cp(string)
  `echo "#{string}" | pbcopy`
  puts "copied in clipboard"

# reloads the irb console can be useful for debugging .irbrc
def reload_irb
  load File.expand_path("~/.irbrc")
  # will reload rails env if you are running ./script/console
  reload! if @script_console_running
  puts "Console Reloaded!"

# opens irbrc in vscode
def edit_irb
  `code ~/.irbrc` if system("code")

def bm
  # From http://blog.evanweaver.com/articles/2006/12/13/benchmark/
  # Call benchmark { } with any block and you get the wallclock runtime
  # as well as a percent change + or - from the last run
  cur = Time.now
  result = yield
  print "#{cur = Time.now - cur} seconds"
  puts " (#{(cur / $last_benchmark * 100).to_i - 100}% change)" rescue puts ""
  $last_benchmark = cur

# exit using `q`
alias q exit

# all available methods explaination
def ll
  puts '============================================================================================================='
  puts 'Welcome to rails console. Here are few list of pre-defined methods you can use.'
  puts '============================================================================================================='
  puts 'obj.sl(:method) ------> source location e.g lead.sl(:name)'
  puts 'obj.ocode(:method) ---> open method in vs code e.g lead.ocode(:name)'
  puts 'obj.dispsoc(:method) -> display method source in rails console e.g lead.dispsoc(:name)'
  puts 'obj.oo ---------------> open object json in vs code e.g lead.oo'
  puts 'hist(n) --------------> command history e.g hist(10)'
  puts 'cp(str) --------------> copy string in clipboard e.g cp(lead.name)'
  puts 'bm(block) ------------> benchmarking for block passed as an argument e.g bm { Lead.all.pluck(:stage);0 }'
  puts '============================================================================================================='
How to search awesome .irbrc file created by other devs 📭
Just click on the following URL and it’ll list all ~/.irbrc files created by other GitHub developers, you can create your file and add everything you need if you find anything useful -
References 📌
Found this post useful? please share to help others find it! Feel free to leave a comment below.


The Noonification banner

Subscribe to get your daily round-up of top tech stories!