Skip to content

Instantly share code, notes, and snippets.

@cheald
Created November 27, 2012 02:35
Show Gist options
  • Save cheald/4152037 to your computer and use it in GitHub Desktop.
Save cheald/4152037 to your computer and use it in GitHub Desktop.
$__load_path_size = nil
$__cached_load_paths = {}
$__cache_scanned = {}
PATH_START_SLASH = "/"
PATH_START_PERIOD = "."
PATH_START_TILDE = "~"
::Kernel.class_eval do
alias __gem_original_require gem_original_require
def bundler_cached_require(requirement)
r0 = requirement[0]
# This seems to be the fastest construct I've found for testing if the path starts with any of those three characters.
r = if r0 == PATH_START_SLASH or r0 == PATH_START_PERIOD or r0 == PATH_START_TILDE
requirement
else
# If we have a cached lookup, use it. Otherwise, let Kernel#require do its thing.
(build_require_paths[requirement] || requirement)
end
__gem_original_require r
end
def build_require_paths
h = $:.length
if $__load_path_size != h
# If we've removed paths, we'll have to wipe and rebuild the cache
# This isn't foolproof; you could remove paths but then add more between requires to get you back
# into a positive difference. It's much faster than array diffs, though.
if $__load_path_size and h < $__load_path_size
$__cached_load_paths = {}
$__cache_scanned = {}
end
$__load_path_size = h
$:.each do |path|
next if $__cache_scanned[path] # No need to reglob a path we've already scanned.
$__cache_scanned[path] = true
cache_load_paths Dir.glob(File.join(path, '**', '*.{rb,so}')), path # require 'foo' can load foo.so or foo.rb
end
end
$__cached_load_paths
end
def cache_load_paths(files, chomp)
files.each do |file|
# for /path/to/foo.rb with a load prefix of /path, cache to/foo and to/foo.rb
key = file[chomp.length + 1, file.length - chomp.length - 4]
key_ext = file[chomp.length + 1, file.length - chomp.length - 1]
$__cached_load_paths[key] ||= file
$__cached_load_paths[key_ext] ||= file
end
end
alias require bundler_cached_require
# Undef gem_original_require as bundler tries to restore it if it finds it.
undef gem_original_require
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment