This post originated from an RSS feed registered with Ruby Buzz
by Gabriel Horner.
Original Post: Mini Irb and Mini Script/Console
Feed Title: Tagaholic
Feed URL: http://feeds2.feedburner.com/tagaholic
Feed Description: My ruby/rails/knowledge management thoughts
In my last post, I introduced Bond‘s own version of irb’s completion. What I didn’t emphasize is that it doesn’t need irb. To prove it, I’ll show you a mini irb which has persistent readline history, error handling and Bond’s autocompletion … in 7 lines.
It’s got the very basics of a repl: take a user’s input, eval it and print the result. Being as basic as it is, there’s no autocompletion, persistent readline history, etc.
But who says that needs to be much larger to get those features?:
1%w{readline rubygems bond bond/completion}.each{|e|requiree}2history_file=File.join(ENV["HOME"],'.mini_irb_history')3IO.readlines(history_file).each{|e|Readline::HISTORY<<e.chomp}ifFile.exists?(history_file)4while(input=Readline.readline('>> ',true))!='exit'5beginputs"=> #{eval(input).inspect}";rescueException;puts"Error: #{$!}"end6end7File.open(history_file,'w'){|f|f.writeReadline::HISTORY.to_a.join("\n")}
Line 2-3: Read in previous history from a history file.
Line 4: Get the users input and start a loop that only ends with exit.
Line 5: Evaluate the input and print an exception if it occurs.
Line 7: Write all of the loaded history back to the history file.
If you’re not familiar with readline, you may be wondering where is the autocompletion being handled? Well, all of readline’s goodness is channeled through Readline.readline. Bond simply sets Readline.completion_proc and readline handles the rest. If you’d like to play with this, fork away!
To be fair this is a stripped down version of script/console i.e. it doesn’t offer the debugger or sandbox. But those could be easily added. If you want to improve on this, fork away! If you want to see what this looks like, just give it a try. :)
Comparing Apples to Oranges
So how does mini-irb compare to irb? Well, it’s like comparing apples to oranges. Irb weighs in at 5000+ loc while mini-irb is 7 + 540 loc with Bond. Irb sports a number of features which I’ve documentedextensively. But I’m finding less need for them every day. The only feature I’d keep is the ruby lexer to handle multiple lines of code. But even then I’d rather prototype multiple lines in an editor.
What are your two cents? What features from irb would you add to mini-irb?