class Brice::History

IRb history support.

Configure with config.history.opt = { ... }, where the following keys are recognized (see DEFAULTS):

:path

The path to your .irb_history file.

:size

The number of entries to keep in the history file.

:perms

The mode to open the history file with.

:uniq

Whether only unique history entries shall be saved. May also be :reverse to keep the most recent ones.

:merge

Whether to preserve, i.e. merge, the history across overlapping sessions.

Constants

DEFAULTS

Public Class Methods

init(opt = {}) click to toggle source
# File lib/brice/history.rb, line 53
def self.init(opt = {})
  new(opt)
end
new(opt = {}, history = defined?(Readline::HISTORY) && Readline::HISTORY) click to toggle source
# File lib/brice/history.rb, line 57
def initialize(opt = {}, history = defined?(Readline::HISTORY) && Readline::HISTORY)
  DEFAULTS.each { |key, val|
    instance_variable_set("@#{key}", Brice.opt(opt, key, val))
  }

  @path    = File.expand_path(@path)
  @reverse = @uniq.to_s == 'reverse'

  init_history(history) if history
end

Private Instance Methods

extend_history() click to toggle source
# File lib/brice/history.rb, line 101
def extend_history
  @history.extend(Tee) if @merge && class << @history; !include?(Tee); end
end
init_history(history) click to toggle source
# File lib/brice/history.rb, line 70
def init_history(history)
  @history = history

  @libedit = begin
    Readline.emacs_editing_mode
    true
  rescue NotImplementedError, NoMethodError
    false
  end

  load_history
  extend_history

  Kernel.at_exit { save_history }
end
load_history(history = @history) click to toggle source
# File lib/brice/history.rb, line 93
def load_history(history = @history)
  return unless File.readable?(@path)
  read_history { |line| history << line }

  return unless @libedit
  @first_line = read_history { |line| break line }
end
read_history() { |line| ... } click to toggle source
# File lib/brice/history.rb, line 86
def read_history
  File.foreach(@path) { |line|
    line.chomp!
    yield line
  }
end
save_history() click to toggle source
# File lib/brice/history.rb, line 105
def save_history
  if @merge
    load_history(lines = [])
    @history.tee! { |t| lines.concat(t) }
  else
    lines = @history.to_a
  end

  lines.unshift(@first_line) if @first_line

  lines.reverse! if @reverse
  lines.uniq!    if @uniq
  lines.reverse! if @reverse

  lines.slice!(0, lines.size - @size)

  File.open(@path, @perms) { |f| f.puts(lines) }
end