一種避免外部執行:
對於捆綁的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
對於捆綁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
謝謝大家,很多答案證實了我的發現:沒有API來做到這一點。我選擇了一個基於,它提供了一個工作的代碼來完成這項任務。 – Pablo 2013-04-08 12:57:56
我認爲你選擇的答案有一些問題。有一個'exit 1'會終止你的程序執行。你是否能夠獲得該代碼的工作?嘗試時發生錯誤。 – Emil 2013-04-09 20:49:35
他們剛剛在版本1.2.x和1.3.x之間引入了'exit 1',所以現在需要一些猴子補丁來解決問題。 – 2013-04-09 21:50:40