Rails unable to autoload constant from file despite being defined in that file

丶灬走出姿态 提交于 2019-12-03 22:59:16
MIdhun Krishna

Rails augments the constant lookup mechanism of ruby.

Constant lookup in Ruby:

Similar to method missing, a Module#constant-missing is invoked when a reference to a constant fails to be resolved. When we refer to a constant in a given lexical scope, that constant is searched for in:

Each entry in Module.nesting 
Each entry in Module.nesting.first.ancestors
Each entry in Object.ancestors if Module.nesting.first is nil or a module.

When we refer to a constant, Ruby first attempts to find it according to this built-in lookup rules.

When ruby fails to find... rails kicks in, and using its own lookup convention and its knowledge about which constants have already been loaded (by ruby), Rails overrides Module#const_missing to load missing constants without the need for explicit require calls by the programmer.

Its own lookup convention?

Contrasting Ruby’s autoload (which requires the location of each autoloaded constant to be specified in advance) rails following a convention that maps constants to file names.

Points::Calculator # =>points/calculator.rb

Now for the constant Points::Calculator, rails searches this file path (ie 'points/calculator.rb') within the autoload paths, defined by the autoload_paths configuration.

In this case, rails searched for file path points/calculator in its autoloaded paths, but fails to find file and hence this error/warning is shown.

This answer is an abstract from this Urbanautomation blog.

Calculator should be a class to be autoloaded correctly

module Points
  class Calculator
  ...
  end
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!