0

我的 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_loadtrue 时也发生了。我似乎无法弄清楚如何让它在缓存环境中工作。

4

1 回答 1

0

从改变

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)
于 2021-03-30T10:46:34.327 回答