Interactive Ruby Console Tip: Remember the last X commands

Posted by Enrique Delgado Wed, 25 Apr 2007 15:47:00 GMT

This is an excellent tip by Mike Clark to make IRB remember the last X number of commands even after you exit and restart IRB.

This is great when developing and after modifying a model, you don’t have to re-type everyting once again :)

“Simply add the code below to your ~/.irbrc file. Then you can use up-arrow to cycle through the history, even after restarting IRB. It relies on the built-in history of readline, so you’ll need readline installed. The code below also enables completion using the TAB key”

IRB.conf[:PROMPT_MODE] = :SIMPLE

require 'irb/completion'

IRB.conf[:AUTO_INDENT] = true

# Session History

HISTFILE = "~/.irb.hist" unless defined? HISTFILE
MAXHISTSIZE = 100 unless defined? MAXHISTSIZE

begin
if defined? Readline::HISTORY
histfile = File::expand_path(HISTFILE)
if File::exists?(histfile)
lines = IO::readlines(histfile).collect { |line| line.chomp }
Readline::HISTORY.push(*lines)
end

Kernel::at_exit {
lines = Readline::HISTORY.to_a.reverse.uniq.reverse
lines = lines[-MAXHISTSIZE, MAXHISTSIZE] if lines.nitems >
MAXHISTSIZE
File::open(histfile, File::WRONLY|File::CREAT|File::TRUNC) {|f|
lines.each {|line| f.puts line }
}
}
end
end

Posted in  | Tags , ,  | no comments