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

gyl*_*laz 15 ruby bundler

我知道你能做到

bundle show gem_name
Run Code Online (Sandbox Code Playgroud)

展示一些宝石的路径.

你如何使用Bundler对象从代码中做到这一点?

ben*_*hor 17

看看他们是如何在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
Run Code Online (Sandbox Code Playgroud)


Tod*_*ski 14

更新:从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"
Run Code Online (Sandbox Code Playgroud)

在v1.3.0之前,您可能希望使用原始解决方案共享(私有接口):

更好的是,您可以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"
Run Code Online (Sandbox Code Playgroud)


Vox*_*Vox 6

事实证明,您实际上是想使用Gem它,而不是Bundler

path = Gem.loaded_specs[NAME_OF_GEM].full_gem_path