LoginSignup
2
2

More than 1 year has passed since last update.

Ruby on Rails | rails console で直接ファイルを require する方法

Last updated at Posted at 2018-07-18

/path/to/rails-application/some/file.rbrequire したい。

絶対パス指定

Rails.root から読む。

require "#{Rails.root}/some/file"

# => true

相対パス指定

相対パス指定だと、Railsアプリケーションのトップディレクトリを基準に読めた。

require_relative "some/file"

# => true

エラー例

require で相対パスから読もうとすると、 ./ を付けない時にエラーになるので注意。

require "some/file"

LoadError: cannot load such file -- some/file

( なんでだよ! と思ったが、この書き方だと多分、インストール済みの ruby gem などだけから読もうとする気がする)

補足

ちなみに実際に rails console を起動したディレクトリと、相対パス指定した時の基準ディレクトリは関係ない様子。

カレントパスの確認はたぶんこいつ。

Dir.pwd

# => "/path/to/rails-application"

環境

  • pry-rails (0.3.6)
  • rails (5.1.5)
  • ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin16]

参考

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

2
2
3

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
2
2