ruby-on-railsrubyrails-spring

Class variable reset with rails / spring


I've a class defined as such:

class PublicationJob < ActiveJob::Base
  def self.jobs
    @jobs ||= Hash{|h, k| h[k] = []}
  end
  def self.register(format, job_class)
    jobs[format] << job_class
  end
  # [...]
end

To register different job classes, I put in an initializer:

PublicationJob.register(:tex, SaveJob)
PublicationJob.register(:saved_tex, TexJob)
#...

The in the rails console I try:

PublicationJob.jobs
#> {:tex => [SaveJob], :saved_tex => [TexJob]}

But if I exit the console (Ctrl-D) then restart it, at some point the hash will be empty!

Why is the class variable reset in this case?

I use rails 4.2.1 and spring, and I know that if I kill/stop spring it works again for some time. Is it related to spring?


Solution

  • Okay, so this was entirely Spring related, and I fixed it by removing spring.

    Thanks to @NekoNova who pointed me to the right part of the documentation, I found that:

    This saves off the first version of the User class, which will not be the same object as User after the code has been reloaded:

    [...]

    So to avoid this problem, don't save off references to application constants in your initialization code.

    In other words, I can't initialize my classes using initializers, because althought it'll work in production, it won't work in development.