Skip to content

Instantly share code, notes, and snippets.

@mathie
Created March 15, 2010 18:26
Show Gist options
  • Save mathie/333141 to your computer and use it in GitHub Desktop.
Save mathie/333141 to your computer and use it in GitHub Desktop.
begin
require 'readline'
class PersistentHistory
attr_accessor :number_of_lines_of_history_to_save, :history_file
def initialize(options = {})
self.number_of_lines_of_history_to_save = options[:number_of_lines_of_history_to_save]
self.history_file = options[:history_file]
yield self if block_given?
at_exit do
save
end
load
end
def persistent_history_enabled?
!number_of_lines_of_history_to_save.nil? && number_of_lines_of_history_to_save.to_i > 0
end
private
def load
if File.exist?(history_file)
open(history_file) do |f|
f.each do |l|
Readline::HISTORY << l.chomp
end
end
end
end
def save
if persistent_history_enabled?
open(history_file, 'w') do |f|
f.puts limit(unique_history, :to => number_of_lines_of_history_to_save)
end
end
end
def limit(a, options = {})
if options[:to] && options[:to].to_i > 0 && a.size > options[:to]
a[-option[:to]..-1]
else
a
end
end
def history
Readline::HISTORY.to_a
end
def unique_history
history.reverse.uniq.reverse
end
end
PersistentHistory.new do |config|
config.number_of_lines_of_history_to_save = 1000
config.history_file = File.expand_path('~/.irb_history')
end
rescue LoadError => e
STDERR.puts "Warning, readline support is not available. Get a better Ruby installation..."
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment