Bundler をシングルファイル Ruby スクリプトで使う方法
RubyGems の依存関係を管理してくれる Bundler をシングルファイル Ruby スクリプトで使う方法を紹介します.
Bundler を Gemfile なしで手軽に使ってみたいときに使えるテクニックです.
Bundler のバージョンは 1.16.1 になります.
そのためには, 次の一行を Ruby ファイルの一番上に加えます:
require 'bundler/inline'
そして gemfile
メソッドを定義して, そのプロック内に Gemfile のときのように source
や gem
といったメソッドを定義できます.
つまり 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 を読み込んで使えるようになった pluralize
と singularize
メソッドを使って, person
を people
と複数形に, people
を person
と単数形に変換し結果を表示します.
このように Bundler を Gemfile なしで使えるので, より簡易に Bundler を使って特定の gems を依存関係を考慮した上で軽く試してみたい, 使ってみたいという時に使えるテクニックです.
関連記事
Ruby のクラスはオープン2018.06.16
Ruby の正規表現を備忘録としてまとめてみた2018.08.30
Ruby で物理コアと論理コアの数を確認する方法2018.09.19
インライン rescue を使う時の注意点2018.07.16
Ruby のブロック, Proc, Lambda の違い2018.06.21