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

前端 未结 5 1789
情书的邮戳
情书的邮戳 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:39

    I've suffered from the very same problem with namespaced classes being autoloaded incorrectly. This is the clue to solve it (from Brendan's answer):

    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).

    And I've solved it by moving all my namespaced classes, named Events::Something, into app/components/events/* and creating a file app/components/events.rb with the following content:

    %w(file1 file2 ...).each do |file|  
      require "events/#{file}"
    end
    

    And while this is a little bit manual, it works both for application, console and test modes.

提交回复
热议问题