在单文件的Ruby脚本中定义gem的依赖性的方法

187 阅读1分钟

有时我遇到需要写一个使用gem的简单脚本的情况。 最简单的方法是在你的脚本中gem install gem-name,然后再require 'gem-name' 。然而,这意味着你需要记住在运行脚本之前安装gem。

捆绑程序有一个内联gemfile定义功能,可以让你在一个单文件的Ruby脚本中定义gem的依赖关系。 要使用这个功能,需要'bundler/inline' ,并提供一个gemfile 块,其中有你通常放在Gemfile 中的代码。

require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'
  gem 'benchmark-ips', require: 'benchmark/ips'
end

Benchmark.ips do |x|
  x.report('original') { naive_implementation() }
  x.report('optimized') { fast_implementation() }

  x.compare!
end

现在运行ruby myfile.rb会自动安装 gem 并运行脚本。

我总是随身带着像上面这样的脚本。 当审查一些代码时建议进行性能优化,能够分享这样的脚本是非常有用的。 这让PR作者能够轻松地复制和调整它,而不必担心安装必要的宝石。