简体   繁体   English

使用bundler以编程方式确定gem的路径

[英]Programmatically determine gem's path using bundler

I know you can do 我知道你能做到

bundle show gem_name

to show the path of some gem. 展示一些宝石的路径。

How do you do that from within the code using the Bundler object? 你如何使用Bundler对象从代码中做到这一点?

Have a look at how they do it in cli.rb 看看他们是如何在cli.rb做到的

def locate_gem(name)
  spec = Bundler.load.specs.find{|s| s.name == name }
  raise GemNotFound, "Could not find gem '#{name}' in the current bundle." unless spec
  if spec.name == 'bundler'
    return File.expand_path('../../../', __FILE__)
  end
  spec.full_gem_path
end

Update : starting with Bundler v1.3.0, there is a public interface for obtaining a Gem's path: 更新 :从Bundler v1.3.0开始,有一个用于获取Gem路径的公共接口:

Bundler.rubygems.find_name('json').first.full_gem_path
# => "/opt/src/foo/my_app/vendor/bundle/ruby/2.0.0/gems/json-1.8.0"

Pre-v1.3.0, you may want to use the original solution shared (a private interface): 在v1.3.0之前,您可能希望使用原始解决方案共享( 私有接口):

Better yet, you can use Bundler::CLI#locate_gem directly: 更好的是,您可以直接使用Bundler::CLI#locate_gem

 require "bundler/cli" Bundler::CLI.new.send(:locate_gem, "json") # => "/opt/src/foo/my_app/vendor/bundle/ruby/1.9.1/gems/json-1.7.3" 

事实证明你实际上想要使用Gem ,而不是Bundler

path = Gem.loaded_specs[NAME_OF_GEM].full_gem_path

Yup, cli.rb is the best way to look at. 是的,cli.rb是最好的观察方式。 However you anyway have to find a spec's name. 但无论如何你必须找到一个规格的名称。

I can give you a starting point, but you have to come with some solution on how to optimize to your case: 我可以给你一个起点,但是你必须找到一些关于如何优化你的案例的解决方案:

GemSearcher = Gem::GemPathSearcher.new
    Init = GemSearcher.init_gemspecs()
    GemSearcher.lib_dirs_for(Init[0])

Unfortunately this solution provides nameless search as all Gems are in an array instead of hash, but if you want you can hack GemPathSearcher, I think that would be useful in the future. 不幸的是,这个解决方案提供了无名搜索,因为所有Gems都是数组而不是哈希,但是如果你想要你可以破解GemPathSearcher,我认为这将来会很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM