Skip to content

Instantly share code, notes, and snippets.

@ahoward
Created August 29, 2011 18:48
Show Gist options
  • Save ahoward/1179095 to your computer and use it in GitHub Desktop.
Save ahoward/1179095 to your computer and use it in GitHub Desktop.
require 'rubygems' unless defined?(Gem)
# load a gem/lib into irb in a way that is durable to bundler LOAD_PATH
# hackery
#
# inspired by
# https://github.com/aniero/dotfiles/blob/master/irbrc#L4-35
#
# IRB.gem('irbcp')
# IRB.gem('awesome_print', :lib => 'ap')
#
def IRB.gem(name, options = {})
name = name.to_s
lib = (options[:lib] || options['lib'] || name).to_s
require(lib)
rescue LoadError => e
candidates = []
glob = File.join(Config::CONFIG['libdir'], "ruby/gems/*")
system_gem_paths = Dir[glob]
gem_paths = Gem.path
paths = gem_paths + system_gem_paths
paths.each do |path|
glob = File.join(path, 'gems/*-[0-9].[0-9].[0-9]')
Dir.glob(glob) do |entry|
basename = File.basename(entry)
gemname, version = basename.split(/-/, 2)
if gemname == name
libdir = File.expand_path(File.join(entry, 'lib'))
class << libdir; attr_accessor(:gemname); attr_accessor(:version); end
libdir.gemname = gemname
libdir.version = version.scan(/\d+/).map{|digit| digit.to_i}
candidates.push(libdir)
end
end
end
raise if candidates.empty?
candidates.sort!{|a,b| a.version <=> b.version}
libdir = candidates.last
begin
$LOAD_PATH.unshift(libdir)
require(lib)
ensure
$LOAD_PATH.shift()
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment