如何在Rails的页面加载中持久化Ruby类变量? [英] How to persist Ruby class variables across page loads in Rails?

查看:63
本文介绍了如何在Rails的页面加载中持久化Ruby类变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要在初始化器中设置的类变量,并且此后一直保留该值.以下示例仅适用于第一页加载.有更好的方法吗?

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

app/models/token.rb

class Token    
  class << self
    attr_accessor :salt
  end
end

config/initilizers/token.rb

config/initilizers/token.rb

Token.salt = "savory hash"

推荐答案

在开发模式下,您的类将随每个请求重新加载,因此当类为在第一个请求后重新加载. (在您的development.rb中" config.cache_classes = false "的结果).

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

initializers.rb

 SALT='savory_hash'

或作为应用程序配置变量:

OR as an application config variable:

application.rb

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.

这篇关于如何在Rails的页面加载中持久化Ruby类变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆