简体   繁体   English

覆盖 const_missing 在非开发环境中返回 `NameError uninitialized constant`

[英]Overriding const_missing returns `NameError uninitialized constant` in non-dev environments

I have the following code in my rails app我的 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

When it runs in development it works当它在开发中运行时,它可以工作

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

When I run it in production however I get当我在生产中运行它时,我得到了

NameError (uninitialized constant TestModule::TestClass)

If I just copy TestModule::TestClass into the console it works.如果我只是将TestModule::TestClass复制到控制台中,它就可以工作。 It seems just to not work with the const_missing method.似乎只是不适用于const_missing方法。

I suspect it may have something to do with the autoloading as when I set config.cache_classes and config.eager_load to true in development.rb it happens there too.我怀疑它可能与自动加载有关,因为当我在 development.rb 中将config.cache_classesconfig.eager_load设置为 true 时,它也发生在那里。 I can't seem to figure out how to get it to work in cached environments though.我似乎无法弄清楚如何让它在缓存环境中工作。

Change from从改变

super(delete_end_number(name.to_s).to_sym)

To

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM