Rails load order changes class definition

I have a very strange error that I have never encountered and cannot find the answer anywhere. I have class definitions that look like this:

# app/models/base/cache_key.rb
class Base
  class CacheKey
    class_attribute :cache_key_template, :instance_writer => false
    self.cache_key_template = "base:tracker-%s-%s"
  end
end

# app/models/other/cache_key.rb
class Other
  class CacheKey < ::Base::CacheKey
    self.cache_key_template = "other:tracker-%s-%s"
  end
end

However, when I switch to the console session, it causes some funky personality

$ rails console
> Base::CacheKey.cache_key_template
=> "base:tracker-%s-%s"
> Other::CacheKey.cache_key_template
=> "base:tracker-%s-%s"
> Other::CacheKey
=> Base::CacheKey

Hmm, strange. How about a different way?

$ rails console
> Other::CacheKey.cache_key_template
=> "other:tracker-%s-%s"
> Base::CacheKey.cache_key_template
=> "base:tracker-%s-%s"
> Other::CacheKey
=> Other::CacheKey

I'm really at a standstill.

+4
source share
1 answer

I reproduced your file structure and got different results, which is ridiculous.

pry(main)> Other::CacheKey.cache_key_template
TypeError: Other is not a class

pry(main)> Other::CacheKey
TypeError: Other is not a class
pry(main)> Other.class
=> Module
pry(main)> Base
=> Base
pry(main)> Base.class
=> Module

Rails seems to be initializing namespaces as modules. Do you have Baseand Otherdefined elsewhere as classes?

: base.rb other.rb /models . cache_key_template .

base.rb other.rb ?

0

All Articles