Have you ever been hacking away at an idea in irb, only to have to dig through your history so you can transcribe it into your project? Or worse, you’ve quit and realized that you can’t remember some brilliant snippet of code? Some quick hacking on top of wirble’s history functionality is letting me retrieve previous sessions from irb.
my .irbrc
1 # load libraries
2 require 'rubygems'
3 require 'wirble'
4
5 class Wirble::History
6 #override original save_history
7 def save_history
8 path, max_size, perms = %w{path size perms}.map { |v| cfg(v) }
9
10 session_time = Time.now.to_i
11 # Get current history buffer
12 current_lines = Readline::HISTORY.to_a
13
14 # Get original history from file
15 real_path = File.expand_path(cfg('path'))
16 if File.exist?(real_path)
17 old_lines = File.readlines(real_path).map { |line| line.chomp }
18 else
19 old_lines = []
20 end
21
22 # tag our current session onto the end and truncate if necessary
23 lines = old_lines
24 lines << "##begin## #{session_time}"
25 lines << current_lines[old_lines.size - 1,current_lines.size]
26 lines << "##end## #{session_time}"
27 lines = lines[-max_size, -1] if lines.size > max_size
28
29 # write the history file
30 File.open(real_path, perms) { |fh| fh.puts lines }
31 say 'Saved %d lines to history file %s.' % [lines.size, path]
32 end
33 end
34
35
36 # start wirble
37 Wirble.init
That should write your irb sessions to your .irb_history file with ###begin### and ###end### delimiters. That alone is pretty handy, but if you want to take it a step further you can throw together a script to dump the sessions.
wirbstory
1 #!/usr/bin/env ruby
2 require 'optparse'
3
4 real_path = File.expand_path("~/.irb_history")
5
6 OptionParser.new do |opts|
7 opts.banner = "#{}: [options]"
8
9 opts.on("-l","--list", "List available history sessions") do
10 sessions = []
11 File.readlines(real_path).each do |line|
12 sessions << if line.match(/^##begin##\s(\d+)/)
13 end
14 puts sessions
15 end
16
17 opts.on("-s","--show SESSION", String, "Show session SESSION") do |s|
18 lines = File.readlines(real_path)
19
20 first = lines.index("##begin## #{s}\n")
21 length = lines.index("##end## #{s}\n") - first - 1
22
23 puts lines[first+1,length]
24 end
25
26 end.parse!
Check it out:
jro@fireant:~$
jro@fireant:~$ irb
>> class LOLcat
>> def self.url?
>> "http://icanhascheezeburger.com"
>> end
>> end
=> nil
>> LOLcat.url?
=> "http://icanhascheezeburger.com"
>> jro@fireant:~$
jro@fireant:~$ ./wirbstory -l
1189572695
1189572708
1189574852
1189575163
1189575590
1189658461
jro@fireant:~$ ./wirbstory -s 1189658461
class LOLcat
def self.url?
"http://icanhascheezeburger.com"
end
end
LOLcat.url?
