【问题标题】:Eager loading ruby modules in Rails 6在 Rails 6 中急切加载 ruby​​ 模块
【发布时间】:2021-12-30 12:14:09
【问题描述】:

我正在尝试快速加载各种 ruby​​ 文件。据我了解,这应该允许在应用程序的其他地方调用这些模块中定义的类,而无需在调用之前使用“require 'filename'”。源文件存储在“lib”目录中,该目录已添加到 page_load_paths 中,在 gps_monitor/application.rb 中添加了以下行

config.eager_load_paths << Rails.root.join("lib")

我尝试使用的文件的精简版本位于 gps_monitor/lib/production_key_generator.rb

require "rails/generators"

module Rails
  module Generators
    class ProductionKeyGenerator < Base # :nodoc:
      
      def self.hello
        "In Hello"
      end
      
      def initialize
        @key = "secret-key"
      end
    end
  end
end  

然后我调用 rails 控制台并尝试访问该类...

sol:gps_monitor sjf$ rails console
Running via Spring preloader in process 68735
Loading development environment (Rails 6.1.4.1)
irb(main):001:0> res = Rails::Generators::ProductionKeyGenerator.new
(irb):1:in `<main>': uninitialized constant Rails::Generators (NameError)
Did you mean?  Enumerator
irb(main):002:0> require 'production_key_generator'
/Users/sjf/.rbenv/versions/3.0.2/lib/ruby/gems/3.0.0/gems/zeitwerk-2.5.1/lib/zeitwerk/loader/callbacks.rb:25:in `on_file_autoloaded': expected file /Users/sjf/TickProjectNG/tick_playbook/apps/gps_monitor/lib/production_key_generator.rb to define constant ProductionKeyGenerator, but didn't (Zeitwerk::NameError)
irb(main):003:0> res = Rails::Generators::ProductionKeyGenerator.new
=> #<Rails::Generators::ProductionKeyGenerator:0x00007ff65fc73b18 @key="secret-key">
irb(main):004:0> 

第一次尝试发出错误“未初始化的常量 Rails::Generators (NameError)”。所以显然该文件并没有像怀疑的那样急切加载。

所以我尝试要求该文件,导致一条消息指出该文件不包含它显然包含的类。

但是,在“要求”成功后尝试访问该类。

我怀疑发生的事情是由于错误消息而导致急切加载失败,但是一旦手动需要,就可以访问该类。

那么为什么它告诉我命名文件不包含命名类?

【问题讨论】:

    标签: ruby-on-rails eager-loading


    【解决方案1】:

    答案是定义 Rails::Generators::ProductionKeyGenerator 的文件需要位于“lib/rails/generators”文件夹中——而不仅仅是“lib”

    错误信息是正确的。 "gps_monitor/lib/production_key_generator.rb 来定义常量ProductionKeyGenerator,但没有"

    它没有定义“ProductionKeyGenerator”,它定义了 Rails::Generators::ProductionKeyGenerator。所以它需要在“lib/rails/generators”中定义正确的类。

    一见即知!

    【讨论】:

      猜你喜欢
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-01
      • 1970-01-01
      相关资源
      最近更新 更多