Inconsistent “LoadError” behavior with 'lib' namespacing/autoloading

前端 未结 5 1790
情书的邮戳
情书的邮戳 2020-12-24 07:19

We have just created a new file in \'lib\' that has spawned a series of headaches involving load errors.

/lib/response_set.rb:

module MyCompany
  cla         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-24 07:46

    We had a similar issue which, after digging, turned out to be caused by the changes in Rails 3.x and autoload_paths.

    Our case appeared only in test (RAILS_ENV=test). When Rails was loading the controllers, it scrambled about looking for each controller's matching model (due to a ActionController::Base.wrap_parameters set in an initializer). Eventually it wound down to the method mentioned above (load_missing_constant). Since our autoload_paths included both lib and lib/**, Rails pulled in all the files from all the subdirectories under lib. Unfortunately, it appears to ignore the implied namespace when loading from subdirectories. It expected foo/base.rb to define Base vs. Foo::Base. That seems to be the core flaw: load_missing_constant invokes search_for_file which returns any file whose name matches (e.g., in my example, foo/base.rb was returned as it matched base.rb).

    It's hard to say if this is an error in Rails - in that it violates the namespace-to-directory mapping assumed by Ruby - or a misuse of autoload_paths.

    We have worked around this for now by removing lib/** from our autoload_paths and adding the necessary require statements to application.rb.

提交回复
热议问题