コマンド入力の際の bundle exec , bin/ について

ターミナルでコマンドを入力する際、
$bundle exec ~~~$bin/~~~などの打ち方がある。
それぞれの用途についてまとめる。

$ bundle exec

  • これをつけた場合、プロジェクト内のgemが反映される。
  • つけない場合、システム全体のgemが反映され、バージョンの違いによるエラーが発生したりする。

$ bin/

  • これをつけた場合、プロジェクト内のbinフォルダ内のファイルが呼び出される。

例) bin/rails

#!/usr/bin/env ruby
APP_PATH = File.expand_path('../config/application', __dir__)
require_relative '../config/boot'
require 'rails/commands'

3行目に着目。
config/boot.rb

ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__)

require 'bundler/setup' # Set up gems listed in the Gemfile.
require 'bootsnap/setup' # Speed up boot time by caching expensive operations.

これにより、プロジェクト内のGemfileが読み込まれる。
すなわちbundle execと同様。

  • railsコマンドだけ、そのまま入力した時自動的に bin/rails と入力した時と同じ挙動をするようになっている。

まとめ

  • binフォルダ内にないコマンド
    →bundle exec
  • binフォルダ内にあるコマンド
    →bin/
  • rails コマンド
    →そのままでも良い