# # # # # # # # #
# /49/rails_history_irb.rb
#
# by               Jan Lelis
# e-mail:          mail@janlelis.de
# type/version:    ruby 
# snippet url:     http://rbJL.net/49/rails_history_irb.rb
# original post:   http://rbJL.net/49-railsrc-rails-console-snippets
# license:         CC-BY (DE)
#
# (c) 2011 Jan Lelis.

history_file = File.join Dir.pwd, '.console_history'
if !IRB.conf[:PROMPT][:RVM]
  IRB.conf[:HISTORY_FILE] = history_file
else # RVM workaround, code from ~/.rvm/scripts/irbrc.rb
  # NOTE: messes up your ~/.irb-history
  # consider editing the rvm script directly
  if File.exists?(history_file)
    lines = IO.readlines(history_file).collect { |line| line.chomp }
    Readline::HISTORY.clear
    Readline::HISTORY.push(*lines)
  end

  Kernel::at_exit do
    maxhistsize = IRB.conf[:SAVE_HISTORY] || 100
    history_file = File.join Dir.pwd, ".console_history"
    lines = Readline::HISTORY.to_a.reverse.uniq.reverse
    lines = lines[-maxhistsize, maxhistsize] if lines.compact.length > maxhistsize
    File::open(history_file, "w+") { |io| io.puts lines.join("\n") }
  end
end