有没有办法从 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
最佳答案
避免外部执行的方法:
对于 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
对于 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
关于ruby - 从 Ruby 内部使用 bundler 验证 gem 的版本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15520641/