LoginSignup
6
5

More than 3 years have passed since last update.

rubocopのConventionからexpand_path、__FILE__、__dir__を理解する

Last updated at Posted at 2018-11-17

rspecを導入してrubocopを実行すると以下のConventionが表示された

$ bundle exec rubocop
〜省略〜
spec/rails_helper.rb:4:14: C: Style/ExpandPathArguments: Use expand_path('../config/environment', __dir__) instead of expand_path('../../config/environment', __FILE__).
require File.expand_path('../../config/environment', __FILE__)
             ^^^^^^^^^^^
〜省略〜

rubocopが言っていること:
expand_path('../../config/environment', __FILE__)の代わりに
expand_path('../config/environment', __dir__)を使ってね。

本当に書き直していいのか?:
expand_path__FILE____dir__がフワッとしていたので今回の内容に合わせて整理

  • 取得したいものは、{app_dir}/config/environment
  • File.expand_pathは第1引数の絶対パスを返す。
  • File.expand_pathの第2引数は参照の基準となるパス。
  • __FILE__は実行ファイル名を相対パスで取得する
  • __dir__は実行ファイルのディレクトリ名を絶対パスで取得する

試してみる:
ディレクトリ構成

{app_dir}
├── config
│   ├── environment.rb # ←ここを参照しようとしている
├── spec # 実行されるカレントディレクトリ
│   ├── rails_helper.rb # ←ここから

検証

$ cd spec/
$ pry
[1] pry(main)> File.expand_path('../../config/environment', __FILE__)
=> "/Users/XXX/app/{app_dir}/config/environment"
[2] pry(main)> File.expand_path('../config/environment', __dir__)
=> "/Users/XXX/app/{app_dir}/config/environment"

同じ結果が取得できた。書き換えても問題ない。

参考:
https://docs.ruby-lang.org/ja/latest/method/File/s/expand_path.html
https://docs.ruby-lang.org/ja/latest/method/Kernel/m/__dir__.html

6
5
2

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
6
5