1

I have a class variable that I would like to set from an initilizer and have the value kept from then on. The example below works for only the first page load. Is there a better way to do this?

app/models/token.rb

class Token    
  class << self
    attr_accessor :salt
  end
end

config/initilizers/token.rb

Token.salt = "savory hash"
Tim Santeford
  • 27,385
  • 16
  • 74
  • 101

2 Answers2

4

In development mode, your class is going to get reloaded with every request, so the value that's set in an initializer at app startup will not persist when the class is reloaded after the first request. (The result of "config.cache_classes = false" in your development.rb).

However, if you want to set a value in an initializer and have it persist in development mode, you can either add it as a constant:

initializers.rb

 SALT='savory_hash'

OR as an application config variable:

application.rb

 module YourAppsName
  class Application < Rails::Application
   config.token_salt = "savory_hash"
  end
 end

which would be accessible anywhere in the app with:

 Rails.application.config.token_salt

Of course, if you enable class caching in your environment, you should find that your variable's value will persist without doing anything of the above.

miked
  • 4,489
  • 1
  • 17
  • 18
0

You can try storing them in session variables, cache, or even within its own table (a reference table).

MrDanA
  • 11,489
  • 2
  • 36
  • 47