从Ruby内部使用bundler验证gem的版本

pup*_*eno 10 ruby bundler

有没有办法在Ruby程序中验证我是否拥有最新版本的gem?也就是说,有没有办法以bundle outdated #{gemname}编程方式进行?

我试着查看bundler的源代码,但我找不到直截了当的方法.目前我正在这样做,这是脆弱,缓慢和如此不优雅:

IO.popen(%w{/usr/bin/env bundle outdated gemname}) do |proc|
  output = proc.readlines.join("\n")
  return output.include?("Your bundle is up to date!")
end
Run Code Online (Sandbox Code Playgroud)

Ale*_*nko 6

一种避免外部执行的方法:

对于bundler 1.2.x

require 'bundler/cli'

# intercepting $stdout into a StringIO
old_stdout, $stdout = $stdout, StringIO.new 

# running the same code run in the 'bundler outdated' utility
Bundler::CLI.new.outdated('rails')

# storing the output
output = $stdout.string 

# restoring $stdout
$stdout = old_stdout 
Run Code Online (Sandbox Code Playgroud)

对于bundler 1.3.x

require 'bundler/cli'
require 'bundler/friendly_errors'

# let's cheat the CLI class with fake exit method
module Bundler
  class CLI 
    desc 'exit', 'fake exit' # this is required by Thor
    def exit(*); end         # simply do nothing
  end 
end

# intercepting $stdout into a StringIO
old_stdout, $stdout = $stdout, StringIO.new 

# running the same code run in the 'bundler outdated' utility
Bundler.with_friendly_errors { Bundler::CLI.start(['outdated', 'rails']) }

# storing the output
output = $stdout.string 

# restoring $stdout
$stdout = old_stdout     
Run Code Online (Sandbox Code Playgroud)