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

71 Views Asked by At

I have the following code in my rails app

# 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. It seems just to not work with the const_missing method.

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. I can't seem to figure out how to get it to work in cached environments though.

1

There are 1 best solutions below

0
On

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)