Bundler をシングルファイル Ruby スクリプトで使う方法


RubyGems の依存関係を管理してくれる Bundler をシングルファイル Ruby スクリプトで使う方法を紹介します.

Bundler を Gemfile なしで手軽に使ってみたいときに使えるテクニックです.

Bundler のバージョンは 1.16.1 になります.

そのためには, 次の一行を Ruby ファイルの一番上に加えます:

require 'bundler/inline'

そして gemfile メソッドを定義して, そのプロック内に Gemfile のときのように sourcegem といったメソッドを定義できます.

つまり Gemfile と同じ DSL を使うことができます.

次はその一例です:

# bundler_inline_example.rb

require 'bundler/inline'

gemfile do
  source 'https://rubygems.org'

  gem 'activesupport', '~> 5.1.0', require: ['active_support',
                                             'active_support/core_ext/string/inflections']
end

# puts 'people'
puts 'person'.pluralize

# puts 'person'
puts 'people'.singularize

そして, 次のコマンドを実行すると,

ruby ./bundler_inline_example.rb

Gemfile のように gemfile のブロック内に定義されている 'activesupport', '~> 5.1.0' をインストールされていなければインストールし, require キーの値の'active_support''active_support/core_ext/inflections' を require します.

そして ActiveSupport の Inflector を読み込んで使えるようになった pluralizesingularize メソッドを使って, personpeople と複数形に, peopleperson と単数形に変換し結果を表示します.

このように Bundler を Gemfile なしで使えるので, より簡易に Bundler を使って特定の gems を依存関係を考慮した上で軽く試してみたい, 使ってみたいという時に使えるテクニックです.