为什么我的 ActiveRecord 类实例变量在开发模式下的第一个请求后消失了?
我的 AR 类之一有一个类实例变量。 我在启动时使用初始化程序设置了它的值,之后除了读取它之外,不再触摸它。 在开发模式下,该值在第一次向 Web 服务器发出请求后消失。 但是,当运行测试、使用控制台或运行生产服务器时,这种情况不会发生。
# The AR class
class Group < ActiveRecord::Base
class << self
attr_accessor :path
end
end
# The initializer
Group.path = File.join(RAILS_ROOT, "public", "etc")
# First request in a view
%p= Group.path #=> "/home/rails/app/public/etc"
# Second request in a view
%p= Group.path #=> nil
开发模式是否有某些东西会在每个请求中删除类中的实例变量? 如果是这样,有没有办法对特定变量或类禁用此功能?
I have a class instance variable on one of my AR classes. I set its value at boot with an initializer and, after that, never touch it again except to read from it. In development mode, this value disappears after the first request to the web server. However, when running tests, using the console or running the production server this does not happen.
# The AR class
class Group < ActiveRecord::Base
class << self
attr_accessor :path
end
end
# The initializer
Group.path = File.join(RAILS_ROOT, "public", "etc")
# First request in a view
%p= Group.path #=> "/home/rails/app/public/etc"
# Second request in a view
%p= Group.path #=> nil
Is there something about development mode that nukes instance variables from classes with each request? If so, is there a way to disable this for specific variables or classes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在开发模式下,类不会被缓存,这意味着它们都会在每次请求时重新加载。 在测试和生产模式下,它们会被缓存,这意味着您的类实例变量会继续存在。 缓存设置在 config/environments 的相关文件中设置。
一种解决方法是在初始化程序中设置全局变量或环境变量,然后定义类级别访问器以返回该值。
In development mode, classes are not cached, which means they are all reloaded on every request. In test and production mode, they are cached which means your class instance varaibles suvives. The caching setting is set in the relevant files in config/environments.
One workaround is to set a global or environment variable in your initializer and then define your class-level accessor to return that value.