Thursday, 9 August 2007

Textmate "Open Require" mod for gems

I discovered a TextMate bundle menu item for Ruby that got me excited at first.

If you have, for example,

require 'rexml/document'

in your file, select rexml/document and hit Command-Shift-D.

It can also be found under Bundles -> Ruby -> Open Require. This will open a project for that item. It's great for looking under the covers to see the source for a library you are using.

I had tried it before, but it didn't seem to work. That's because it failed for any require that used a gem name. The following modification causes Open Require to open any file or gem:

1. Go to Bundles -> Bundle Editor -> Show Bundle Editor
2. Select Ruby -> Open Require
3. Paste the following, and then click on another bundle item so that it saves the change.


#!/usr/bin/env ruby
gems_installed = require 'rubygems'

file = STDIN.read.sub(/\A(["']?)(.*)(\.rb|["'])?\1/, '\2.rb')
dir = $:.find { |d| File.exist?(File.join(d, file)) }

if dir && file
project_root = File.dirname(File.join(dir, file))
elsif gems_installed
gem_spec = Gem::GemPathSearcher.new.find(file)
if gem_spec
project_root = gem_spec.full_gem_path
end
else
project_root = nil
end
if project_root then
ENV['FILE'] = project_root
%x{ "$TM_SUPPORT_PATH/bin/mate" "$FILE" }
else
puts "Could not find include: ‘#{file}’"
end


This is now one of my favorite Textmate bundle items!