Ruby + irb + utility-belt + gedit = :)

Systems Development

In September 2008, Akita wrote an interesting post about utility-belt, a gem that adds several features to irb (it’s a bit like giving irb a Red Bull). Some of its features include:

  • Launching Vi or TextMate from irb, letting you quickly write or paste some code, save it, close the editor, and test it in irb without creating a file and saving it in a directory.
  • Viewing a command history by typing “h”.
  • Opening the history in TextMate or Vi using hvi or hmate.
  • Watch Akita’s screencast to see how it works.

So far, so good. But the big problem is that I use Ubuntu with gedit to write Ruby code, and utility-belt doesn’t have specific methods for launching gedit. The utility-belt help offers edit_interactively(:gedit), but of course I couldn’t settle for that method; I wanted it to work the same way as it does with Vi or TextMate.

After doing some research, I found an article showing how to open the Linux nano editor through irb by extending utility-belt. Based on it, I made some changes to the .irbrc file, which you’ll see below.

The first step is to install utility-belt:

git clone git://github.com/akitaonrails/utility-belt.git
cd utility-belt
gem build utility_belt.gemspec
sudo gem install utility_belt-1.0.12.gem

Now edit the .irbrc file in your home directory and add these lines:

   require 'rubygems'
   require 'utility_belt'

   module InteractiveEditing
      def gedit
         edit_interactively(:gedit)
      end
   end

   class Object
      def history_to_gedit
         handling_jruby_bug do
            file = Tempfile.new("gedit_tempfile")
            get_lines(0..(Readline::HISTORY.size - 1)).each do |line|
               file << "#{line}\n"
            end
            file.close
            system("gedit #{file.path}")
         end
      end
      alias :hgedit :history_to_gedit
   end
    UtilityBelt.equip(:all)

After that, just save and run it!

Now you can use the gedit command directly from irb, and open the history in gedit with hgedit or history_to_gedit. If you want to understand the code a bit better, read the interactive_editor.rb and command_history.rb files in the utility-belt/lib/utility_belt folder.

If you don’t use gedit, Vi, or TextMate, just modify this code to work with your favorite editor!

That’s all for now.

Note: My first test didn't work because a dependency was missing from my system: xsel, which is responsible for copying text from the shell to the clipboard. I solved this problem with: `sudo apt-get install xsel`

To learn more about xsel, click here.