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 <history path> | fzf --tac |  tr '\n' ' '` # see below for modifying this
end

# I added this line to let me know it kicked in.

To see where Pry stores your history, run:

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

Voila!

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