Last active
January 21, 2019 19:53
-
-
Save siman-man/d0b32841d3d9b5a45b9b874af8ae65ee to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'pathname' | |
class PathFinder | |
SUFFIXES = ['', | |
'.rb', | |
*%w(DLEXT DLEXT2).map { |key| | |
val = RbConfig::CONFIG[key] | |
next unless val and not val.empty? | |
".#{val}" | |
} | |
].compact.uniq | |
using Module.new { | |
refine Gem::Specification do | |
def find_path(file, suffixes) | |
raw_require_paths.find do |path| | |
base = File.join(gems_dir, full_name, path.untaint, file).untaint | |
suffixes.each do |suf| | |
return base + suf if File.file?(base + suf) | |
end | |
end | |
if have_extensions? | |
base = File.join(extension_dir, file) | |
suffixes.find { |suf| File.file?(base + suf) } | |
else | |
nil | |
end | |
end | |
end | |
} | |
def self.find(feature) | |
new.path_finder(feature) | |
end | |
def search_from_load_path(feature) | |
pathname = Pathname.new(feature) | |
ext = File.extname(feature) | |
suffixes = ([ext] + SUFFIXES).uniq | |
if pathname.absolute? | |
suffixes.each do |suf| | |
path = pathname.sub_ext(suf).to_path | |
return path if File.file?(path) | |
end | |
else | |
$LOAD_PATH.each do |load_path| | |
base = Pathname.new(load_path) + feature | |
suffixes.each do |suf| | |
path = base.sub_ext(suf).to_path | |
return path if File.file?(path) | |
end | |
end | |
end | |
nil | |
end | |
def search_from_gems(feature) | |
spec = Gem::Specification.find_by_path(feature) | |
spec&.add_self_to_load_path | |
spec&.find_path(feature, Gem.suffixes) | |
end | |
def path_finder(feature) | |
search_from_load_path(feature) || search_from_gems(feature) | |
end | |
end | |
pp PathFinder.find('ripper') | |
pp PathFinder.find('ruby_parser') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment