1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Gemfileの `require:` オプションを整理する

1
Posted at

背景

Gemfileで require: false を見かけることはあっても、他にどんな指定ができるのか曖昧だったので整理した

require: オプションとは

Bundlerが Bundler.require でgemを読み込む際に、自動requireの挙動を制御するオプション

# デフォルト(自動でrequire)
gem 'rails'

# 自動requireしない(手動で require 'sidekiq' する必要あり)
gem 'sidekiq', require: false

# gem名と異なるファイル名を指定
gem 'ruby-prof', require: 'ruby_prof'

# 複数ファイルを指定
gem 'aws-sdk', require: ['aws-sdk-s3', 'aws-sdk-sqs']

まとめ表

挙動
省略 / true gem名と同名のファイルを自動でrequireする(デフォルト)
false 自動requireしない。使う箇所で手動 require が必要
'ファイル名' 指定したファイルをrequireする
['a', 'b'] 複数ファイルをrequireする

どんなときに require: false を使うか

  • 起動時に不要なgem:rake taskやバッチ専用のgemなど、Rails起動時に毎回読み込む必要がないもの
  • 起動速度の改善:不要なgemのrequireを省くことでアプリの起動が速くなる(体感したことはない)
  • CLIツール系rubocopbrakeman など、アプリのランタイムでは使わないgem

文字列指定が必要なケース

gem名とrequire対象のファイル名が異なる場合に使う

# gem名は 'ruby-prof' だが、requireするファイルは 'ruby_prof'
gem 'ruby-prof', require: 'ruby_prof'

# gem名は 'rspec-rails' だが、requireするファイルは 'rspec/rails'
gem 'rspec-rails', require: 'rspec/rails'

ハイフン区切りのgem名が多いので、地味に出番がある

感想

  • 気になってるけど、放置みたいなやつはこん感じで記事にしていこう

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?