bundle installとupdateの使い方について

railsでGemの管理を行ってくれるbundlerですが、bundle installとbundle updateの違いがよくわからないまま、「とりあえず両方実行しちゃおう」ってなることが多いので、自分のためにも違いをまとめておきます。

■bundle install

以下、引用

「bundle install」を行なうと、「Gemfile」に書かれたGemパッケージと、そのGemパッケージが依存しているGemパッケージを自動的に調べて全てインストールしてくれます。「Gemfile.lock」はインストールされたGemパッケージの名前とバージョンが記録されたものです。

他の環境で同じアプリケーションの開発を行なう場合は、プログラムファイルに加えてこの「Gemfile.lock」ファイルを配布します。そして他の環境で「bundle install」を実行すると、今度は「Gemfile.lock」ファイルが参照され、指定されたバージョンのGemパッケージがインストールされます。

参照 : Bundlerを使ったGemパッケージの管理 - Ruby on Rails入門

■bundle update

bundle updateはGemfile.lockの記述を無視して、GemfileでのGemの指定やそのバージョン指定などに基づいて、gemを更新する。
更新時にGemfile.lockを更新する。

参照: bundlerでの運用方法 - Qiita

■補足

英語ですが、bundlerマニュアルの内容もまとめておきます。

bundle install

DESCRIPTION
Install the gems specified in your Gemfile. If this is the first time you run bundle install (and a Gemfile.lock does not exist), bundler will fetch all remote sources, resolve dependencies and install all needed gems.

If a Gemfile.lock does exist, and you have not updated your Gemfile, bundler will fetch all remote sources, but use the dependencies specified in the Gemfile.lock instead of resolving dependencies.

If a Gemfile.lock does exist, and you have updated your Gemfile, bundler will use the dependencies in the Gemfile.lock for all gems that you did not update, but will re-resolve the dependencies of gems that you did update. You can find more information about this update process below under CONSERVATIVE UPDATING.

bundle update

NAME
bundle-update - Update your gems to the latest available versions

DESCRIPTION
Update the gems specified (all gems, if none are specified), ignoring the previously installed gems specified in the Gemfile.lock. In general, you should use bundle install(1) to install the same exact gems and versions across machines.
You would use bundle update to explicitly update the version of a gem.

まとめ

  • Gemfile.lockがない状態で「bundle install」を行うと、Gemfileに記載されているソフトのインストールを行う
  • bundle installはGemfile.lockを参照して環境をインストールする
  • Gemfile.lockに依存せずにgemの更新を行いたい時は、bundle updateを使う
  • bundle updateはGemfile.lockの更新を行う

Gemfileを更新したときは、bundle updateを実行しておこう!

すみません。最後の一文が嘘でした。。。

追記

ちょっと待った! Railsでgitリポジトリから除外すべきでないファイル:Gemfile.lockとdb/schema.rb | TechRacho
ここを見て誤解があることに気づきました!

bundle installについて

Gemfileにgemが追加された場合(通常は開発時)
Gemfileに追加されたgemとそれに依存する未インストールgemのみがインストールされ、Gemfile.lockはそれらのgemについてのみ更新される。

Gemfileに変更がない場合(通常はデプロイ時)
Gemfile.lockに従ってインストールされる。Gemfileは参照されず、Gemfile.lockは更新されない。

bundle updateについて

bundle updateを実行すると現状のGemfile.lockの内容は無視され、上で言う「Gemfile.lockがない場合」と同じことが行われます。当然ながら、Gemfile.lockは、現時点の最新バージョンと依存関係を持つgemによってごっそり更新されてしまいます。

  • Gemfileを更新して、bundle install を行うのは正しい。
  • bundle updateを行うと現状の環境で使用しているgemに関しても、Gemfileの記述の範囲内で最新のものがインストールされる

Gemfile更新時も、別のgemの状態を同じにする時はbundle installを実行するのが良さそうです。