1# save-history.rb - 2# $Release Version: 0.9.6$ 3# $Revision: 39049 $ 4# by Keiju ISHITSUKA(keiju@ruby-lang.org) 5# 6# -- 7# 8# 9# 10 11require "readline" 12 13module IRB 14 module HistorySavingAbility # :nodoc: 15 @RCS_ID='-$Id: save-history.rb 39049 2013-02-04 23:04:09Z zzak $-' 16 end 17 18 class Context 19 def init_save_history# :nodoc: 20 unless (class<<@io;self;end).include?(HistorySavingAbility) 21 @io.extend(HistorySavingAbility) 22 end 23 end 24 25 # A copy of the default <code>IRB.conf[:SAVE_HISTORY]</code> 26 def save_history 27 IRB.conf[:SAVE_HISTORY] 28 end 29 30 # Sets <code>IRB.conf[:SAVE_HISTORY]</code> to the given +val+ and calls 31 # #init_save_history with this context. 32 # 33 # Will store the number of +val+ entries of history in the #history_file 34 # 35 # Add the following to your +.irbrc+ to change the number of history 36 # entries stored to 1000: 37 # 38 # IRB.conf[:SAVE_HISTORY] = 1000 39 def save_history=(val) 40 IRB.conf[:SAVE_HISTORY] = val 41 if val 42 main_context = IRB.conf[:MAIN_CONTEXT] 43 main_context = self unless main_context 44 main_context.init_save_history 45 end 46 end 47 48 # A copy of the default <code>IRB.conf[:HISTORY_FILE]</code> 49 def history_file 50 IRB.conf[:HISTORY_FILE] 51 end 52 53 # Set <code>IRB.conf[:HISTORY_FILE]</code> to the given +hist+. 54 def history_file=(hist) 55 IRB.conf[:HISTORY_FILE] = hist 56 end 57 end 58 59 module HistorySavingAbility # :nodoc: 60 include Readline 61 62# def HistorySavingAbility.create_finalizer 63# proc do 64# if num = IRB.conf[:SAVE_HISTORY] and (num = num.to_i) > 0 65# if hf = IRB.conf[:HISTORY_FILE] 66# file = File.expand_path(hf) 67# end 68# file = IRB.rc_file("_history") unless file 69# open(file, 'w' ) do |f| 70# hist = HISTORY.to_a 71# f.puts(hist[-num..-1] || hist) 72# end 73# end 74# end 75# end 76 77 def HistorySavingAbility.extended(obj) 78# ObjectSpace.define_finalizer(obj, HistorySavingAbility.create_finalizer) 79 IRB.conf[:AT_EXIT].push proc{obj.save_history} 80 obj.load_history 81 obj 82 end 83 84 def load_history 85 if history_file = IRB.conf[:HISTORY_FILE] 86 history_file = File.expand_path(history_file) 87 end 88 history_file = IRB.rc_file("_history") unless history_file 89 if File.exist?(history_file) 90 open(history_file) do |f| 91 f.each {|l| HISTORY << l.chomp} 92 end 93 end 94 end 95 96 def save_history 97 if num = IRB.conf[:SAVE_HISTORY] and (num = num.to_i) > 0 98 if history_file = IRB.conf[:HISTORY_FILE] 99 history_file = File.expand_path(history_file) 100 end 101 history_file = IRB.rc_file("_history") unless history_file 102 103 # Change the permission of a file that already exists[BUG #7694] 104 begin 105 if File.stat(history_file).mode & 066 != 0 106 File.chmod(0600, history_file) 107 end 108 rescue Errno::ENOENT 109 rescue 110 raise 111 end 112 113 open(history_file, 'w', 0600 ) do |f| 114 hist = HISTORY.to_a 115 f.puts(hist[-num..-1] || hist) 116 end 117 end 118 end 119 end 120end 121