Class: Cyc::History

Inherits:
Configurable show all
Defined in:
lib/cyc/console.rb

Overview

Stolen (with permission from the author :) from Wirble history for IRB pablotron.org/software/wirble/

Constant Summary collapse

DEFAULTS =
{
  :path   => ENV['CYC_HISTORY_FILE'] || "~/.cyc_history",
  :size   => (ENV['CYC_HISTORY_SIZE'] || 1000).to_i,
  :perms  => File::WRONLY | File::CREAT | File::TRUNC,
}

Instance Attribute Summary

Attributes inherited from Configurable

#configuration, #verbose

Instance Method Summary collapse

Constructor Details

#initialize(opt = nil) ⇒ History

Returns a new instance of History.



69
70
71
72
73
74
75
# File 'lib/cyc/console.rb', line 69

def initialize(opt = nil)
  @opt = DEFAULTS.merge(opt || {})
  super()
  return unless defined? Readline::HISTORY
  Readline::HISTORY.push(*self.configuration)
  Kernel.at_exit { save_history }
end

Instance Method Details

#save_historyObject



54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/cyc/console.rb', line 54

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