Amir Sharif
Engineer.
Weekend hacker.
Self improvement enthusiast.

Upgrade Ctrl-R to search with fzf

Pry is a great alternative to irb. Here’s how I use it.

The default history search for pry is not great. You can override it with more modern tools. (source)

Run gem install rb-readline and add it to your Gemfile in your Rails project.

Modify ~/.pryrc

require 'rb-readline'

def RbReadline.rl_reverse_search_history(sign, key)
  rl_insert_text  `cat #{Pry.config.history_file} | fzf --tac |  tr '\n' ' '` # see below for modifying this
end

To see where Pry stores your history, run:

pry(main)> Pry.config.history_file
=> "/Users/amirsharif/.local/share/pry/pry_history"

Voila!

Performance measure any method

def pmeasure(&block)
  now = Time.now.to_f
  yield
  duration = Time.now.to_f - now
  puts "Finished in #{duration.round(6)}s"
end

pmeasure { YourMethod.call } # You'll get a log of how long it took

# [1] pry(main)> pmeasure { sleep 1 }
# Finished in 1.001213s

Copying a variable from the console

Add these methods to your Pry console. (source)

def pbcopy(input)
 str = input.to_s
 IO.popen('pbcopy', 'w') { |f| f << str }
 str
end

def pbpaste
 `pbpaste`
end

Let’s say you have a giant string blob in a local variable like html

In the console you can run:

pbcopy(html) # The string content is now on your clipboard!

You can use this to evaluate quick lines as well. Copy a multiline snippet of code and then type peval in Pry instead of pasting. It will run the code much faster since it won’t have to parse and highlight it inside of the console.

Pry::Commands.block_command 'peval', "Pastes from the clipboard then evals it in the context of Pry" do
  _pry_.input = StringIO.new("(\n#{pbpaste}\n)")
end

Troubleshooting

Often when working with emoji’s I got this error: Encoding::UndefinedConversionError This is because of the rb-readline we added earlier.

You can reproduce this error by just copying and pasting this:

'’ this will break pry!'

I opened this issue on GitHub. https://github.com/ConnorAtherton/rb-readline/issues/163



Date
November 3, 2022