LoginSignup
22
22

More than 5 years have passed since last update.

requireせずに勝手に読み込まれるとでも思ってるの?

Posted at

ちょっと挑発的なタイトル使ってみたかっただけです。すみません。

引用するコードなどはRails 4.0.2で。
https://github.com/rails/rails/tree/v4.0.2

ruby2.0.0p247

なぜrequireせずにクラスやモジュールが使えるのか?

いや、requireしているんですけどね。
どこでどのようにやっているかの話。

どこでしているのか?

またもやAcitveSupportさんです。イケメンですね。

AcitveSupport::Dependencies
https://github.com/rails/rails/blob/v4.0.2/activesupport/lib/active_support/dependencies.rb

詳しい内容は、過去に似たような記事書いてた方がいたので、割愛します。

Rails の自動読み込みの話
http://blog.eiel.info/blog/2013/09/07/autoload-rails/

どういう仕組みか?

rubyにはみなさんご存知、method_missingのほかにも、const_missingというmethodがあります。

hoge.rb
class Hoge
  def call_const_missing
    Hoge::Moge
  end

  def self.const_missing(const_name)
    p const_name
  end
end

Hoge.new.call_const_missing
#=> :Moge

見つからなかったconstがsymbolでもらえます。
これがもらえればなんとか出来そうですね!

実際、そのような仕組みでAS::Dependenciesもrequireをしています。
(もうちょっとゴニョゴニョしてるんですが)

そういえば、rubyのautoloadは無くなるのかな?

どうなるのかな。
でも、今のところあんまり使わずに様子見ようって感じかね。

"I strongly discourage the use of autoload in any standard libraries" (Re: autoload will be dead)
https://bugs.ruby-lang.org/issues/5653

ActiveSupport::Autoloadも優秀だと思うけど、path書かないと意図しない読み込みがされたりして怖いんだよね。

まとめ

  • 結局、行き着く先はrequire
  • const_missingすごいね
  • Kernel.autoloadModule.autoloadはなくなるかも??
22
22
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
22
22