简体   繁体   中英

How to persist Ruby class variables across page loads in Rails?

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"

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.

您可以尝试将它们存储在会话变量,缓存中,甚至存储在其自己的表(参考表)中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM