Lev Denisov
Lev Denisov

Reputation: 2171

Why some Ruby constants (classes, modules) should be explicitly required in Rails?

There seems to be two types of classes in ruby, one type I don't need to require they're always accessible (like Float, Array, Hash, etc.). They are a part of ruby and this is expected.

But there are also some constants that are not accessible unless explicitly required (like REXML, Observable, YAML). They are part of Ruby too and I would expect to be able to access them without require.

Why these constants are not available without require?

In Rails guides it is not recommended to explicitly require anything as this messes up Rails autoload mechanism. If these constants need to be required anyway, what is the best way to do it?

Should I use require or require_dependency?

Should I use require at the top of the file where the constant is used or should I do it globally somehow?

EDIT: Also, since constants availability depends on the loading order it is easy to forget to require some file and it will not break until load order changes somehow. What is the best way to not face such error except being extra alert about every constant you use?

Upvotes: 2

Views: 275

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230276

There are two kinds of things that are "built-in".

  1. Ruby core. These things you don't have to require. They're part of the language itself. Array, Hash, etc.
  2. Standard library (stdlib). Things like Struct, OpenStruct, additional functionality of Time, etc. They are not essential to the language. Just functionality that is available to you. If you don't use, say, REXML in your program, it doesn't need to be loaded (which would be waste of CPU time and memory). So, you have to require these things prior to using them.

If these constants need to be required anyway, what is the best way to do it?

If you don't monkeypatch them, then you just go ahead and require them whereever you want. I normally do it at the top of the file where they are used.

If you do monkeypatch them, I suggest you reconsider. :)

Upvotes: 2

Related Questions