bentomas.com

Fixing irb history with Wirble and 1 small edit

By default the command line utility for testing Ruby code, called irb, doesn’t remember any history from previous sessions. This means if you type some commands into irb and then close it, the next time you launch irb you have to completely retype all those commands. Which is a pain in the ass.

I installed a project called Wirble which adds a lot of things to irb, most specifically better history management. And it worked great! I thought all my problems were solved!

Except for 1 small thing. If we look at the Wirble code we find this method (function? what’s the correct word here?) which writes your history to a file:

def save_history
	path, max_size, perms = %w{path size perms}.map { |v| cfg(v) }

	# read lines from history, and truncate the list (if necessary)
	lines = Readline::HISTORY.to_a.uniq
	lines = lines[-max_size, -1] if lines.size > max_size

	# write the history file
	real_path = File.expand_path(path)
	File.open(real_path, perms) { |fh| fh.puts lines }
	say 'Saved %d lines to history file %s.' % [lines.size, path]
end

The line to notice is the one that reads lines = Readline::HISTORY.to_a.uniq. It uses the uniq method to get rid of all duplicate commands you have typed. Now this is all well and good, I don’t need every instance of every command I have typed. But this command removes duplicates from the end of the list! Which is not what I wanted. So, I modified the line so it now reads lines = Readline::HISTORY.to_a.reverse.uniq.reverse. The net effect of this change is that it removes duplicates from the beginning of the history as opposed to the end.

Perfect!