OK, I know this is a bit of a frankenstack, but I am running JRuby on Rails, and I'm relatively new to both. I'm seeing some behavior that I can't understand, and I'd开发者_开发知识库 like to know if I'm doing something wrong or if its a problem with my stack. The basic issue is that it appears that my class attributes are being reinitialized, something that I wouldn't expect to ever happen.
Here's essentially my code
class MyController < ActionController::Base
cattr_accessor :an_attr
before_filter :init_an_attr
def init_an_attr
if @@an_attr.nil?
@@an_attr = {}
end
# do some other stuff here
end
end
The problem lies in the fact that every time init_an_attr is called, the condition on the if evaluates to true, and I end up reassigning @@an_attr.
Is that the expected behavior? If so can you explain why, because to me, the assignment should only happen once.
In Rails, when running in development mode, classes are not cached. MyController, and all other classes are reloaded on each request. When running in production, this is not the case - classes are cached.
However, even in production, this variable will be local to a particular application instance - if you're running with two Mongrels, for example, each will have a different version of this variable.
If you want state to be set across multiple requests, consider either using the session, or storing values in your database. Class variables are really not appropriate for cross-request storage.
精彩评论