Question

irb can write command history to a file, but it only does this when your irb session ends.

I would like to write out my command history more frequently: as often as on every command (like shell history), but it doesn't have to be so often.

Is there a .irbrc setting for this? Or will I have to hack the irb source...

Was it helpful?

Solution

Having hacked on irb many a time, good luck with a clean solution. Instead I'd recommend ripl, an irb alternative. By default it saves history more intelligently (i.e. even when you abruptly exit out with Control-D).

If you want to write history after every command, it's easy with ripl since it's built to be extended with plugins:

# add to your ~/.riplrc
module Ripl::ImmediateHistory
  # write to history after every eval
  def eval_input(input)
    super
    File.open(history_file, 'a') {|f| f.puts input }
  end

  # disable writing to history when ripl exits
  def write_history; end
end
Ripl::Shell.send :include, Ripl::ImmediateHistory

OTHER TIPS

From here: http://blog.nicksieger.com/articles/2006/04/23/tweaking-irb

module Readline
  module History
    LOG = "#{ENV['HOME']}/.irb-history"

    def self.write_log(line)
      File.open(LOG, 'ab') {|f| f << "#{line}
"}
    end

    def self.start_session_log
      write_log("
# session start: #{Time.now}

")
      at_exit { write_log("
# session stop: #{Time.now}
") }
    end
  end

  alias :old_readline :readline
  def readline(*args)
    ln = old_readline(*args)
    begin
      History.write_log(ln)
    rescue
    end
    ln
  end
end

Readline::History.start_session_log
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top