RailsでもGemの管理に使われてるbundlerはもはや必須のツールですが、基本的な使い方についてまとめてみます。
事前準備
rbenv と bundler のインストールをします。
【Mac】Ruby開発環境の準備+rbenvの使い方 - TASK NOTES
bundlerの使い方
Gemfileの作成と編集
bundle init
コマンドを使うとGemfileがカレントディレクトリに作成されます。
$ bundle init Writing new Gemfile to /Users/tasukujp/Documents/ruby/Gemfile
Gemfile を編集してインストールするGemを指定します。今回はsqlite3を例に説明します。バージョンを指定したい場合は rails の行を参考にして下さい。指定してなかった場合は最新バージョンがインストールされます。
$ vim Gemfile # A sample Gemfile source "https://rubygems.org" # gem "rails", "4.1.7" gem "sqlite3"
Gemをインストール
Gemfileを作成したディレクトリでbundle install
を実行してください。--path
を指定しないとRuby環境のGemディレクトリにインストールされてしまいますので気を付けましょう。ディレクトリ名はvender/bundle
が推奨されているようです。
$ bundle install --path vendor/bundle Fetching gem metadata from https://rubygems.org/............ Installing sqlite3 1.3.10 Using bundler 1.7.9 Your bundle is complete! It was installed into ./vendor/bundle
ディレクトリが作成されて sqlite3 がインストールされました。
$ ls vendor/bundle/ruby/2.1.0/gems/ sqlite3-1.3.10
--pathを省略する
毎回--path
を指定するのも面倒ですので初期値を設定しておきます。
$ bundle config --global path 'vendor/bundle' You are replacing the current global value of path, which is currently "vendor/bundle"
ホームディレクトリに config ファイルが作成されます。
$ cat ~/.bundle/config --- BUNDLE_PATH: vendor/bundle
bundle config
を引数なしで実行しても現在の設定が確認できます。
$ bundle config Settings are listed in order of priority. The top value will be used. path Set for the current user (/Users/tasukujp/.bundle/config): "vendor/bundle"
オプション
--without
以下のように production 用の Gem をグループ指定することがあります。
group :production do gem 'pg', '0.17.1' gem 'rails_12factor', '0.0.2' end
このような場合--without
オプションを使って指定されたグループはローカルにインストールしないことが可能です。よく production にデプロイする時に--without development test
が使われます。
$ bundle install --without production ... Bundle complete! 12 Gemfile dependencies, 59 gems now installed. Gems in the group production were not installed. Use `bundle show [gemname]` to see where a bundled gem is installed.
設定ファイルには次のように記述されます。
$ cat .bundle/config BUNDLE_WITHOUT: productio
--deployment
デプロイモードで実行します。Gemfile.lock が必須であり、Gemfile を変更して bundle install を再実行することができません。そのため開発環境で使用することは基本的にないでしょう。
また、Gem はvendor/bundle
配下に自動的にインストールされます。ただし--path
を指定した場合はそちらが優先されます。
.bundle/config
の内容は次のようになります。
BUNDLE_FROZEN: "1" BUNDLE_PATH: "vendor/bundle" BUNDLE_DISABLE_SHARED_GEMS: "true"
--system
Gem をシステムの Ruby へインストールします。 これを指定した場合はそれ以前に記憶されている.bundle/config
があっても path 情報を上書きます。
その他
bundle を実行するとディレクトリ内は以下のようになります。
drwxr-xr-x 3 tasukujp staff 102 12 24 14:40 .bundle -rw-r--r-- 1 tasukujp staff 87 12 24 14:22 Gemfile -rw-r--r-- 1 tasukujp staff 108 12 24 14:32 Gemfile.lock drwxr-xr-x 3 tasukujp staff 102 12 24 14:40 vendor
この config ファイルはローカルの設定ファイルです。
$ cat .bundle/config --- BUNDLE_PATH: vendor/bundle BUNDLE_DISABLE_SHARED_GEMS: '1'
Gemのバージョンと取得先が記載されます。
$ cat Gemfile.lock GEM remote: https://rubygems.org/ specs: sqlite3 (1.3.10) PLATFORMS ruby DEPENDENCIES sqlite3
Gemfile.lockについては以下が詳しい。
Ruby - gemspec と Gemfile と Gemfile.lock との違い. - Qiita
関連記事
【Mac】Ruby on Railsの環境構築とbundlerについて