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

試著忘記壹切 提交于 2019-12-23 04:06:14

问题


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"

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/9085566/how-to-persist-ruby-class-variables-across-page-loads-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!