【问题标题】:Overriding const_missing returns `NameError uninitialized constant` in non-dev environments覆盖 const_missing 在非开发环境中返回 `NameError uninitialized constant`
【发布时间】:2021-03-29 17:08:19
【问题描述】:

我的 Rails 应用程序中有以下代码

# app/models/test_module/text_class.rb
module TestModule
  class TestClass
  end
end

# app/models/test_module.rb
module TestModule
  def self.const_missing(name)
    super(delete_end_number(name.to_s).to_sym)
  end

  def self.delete_end_number(str)
    str.gsub(/\d+$/,'')
  end
end

当它在开发中运行时,它可以工作

>> TestModule::TestClass1
=> TestModule::TestClass

当我在生产中运行它时,我得到了

NameError (uninitialized constant TestModule::TestClass)

如果我只是将TestModule::TestClass 复制到控制台中,它就可以工作。似乎只是不适用于 const_missing 方法。

我怀疑它可能与自动加载有关,因为当我在 development.rb 中将 config.cache_classesconfig.eager_load 设置为 true 时,它​​也发生在那里。不过,我似乎无法弄清楚如何让它在缓存环境中工作。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-5 ruby-2.6


    【解决方案1】:

    改变

    super(delete_end_number(name.to_s).to_sym)
    

    const = delete_end_number(name.to_s).to_sym
    ActiveSupport::Dependencies.load_missing_constant(self, const)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多