Why is my class variable reinitialized with cattr_accessor (JRuby, Rails)

Ok, I know this is a bit of a frankenstack, but I'm running JRuby on Rails, and I'm relatively new to both. I see some kind of behavior that I cannot understand, and I would like to know that I am doing something wrong or if this is a problem with my stack. The main problem is that it seems that my class attributes are reinitialized, which I would never have expected.

Here is 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 is that every time init_an_attr is called, the if condition is true, and I end up reassigning @@ an_attr.

Is this expected behavior? If so, you can explain why, because for me, an appointment should only happen once.

+4
source share
1 answer

In Rails, when launched in development mode, classes are not cached. MyController and all other classes are reloaded on each request. When launched in production, this is not so - classes are cached.

However, even in production, this variable will be local to a specific application instance - if you are working with two Mongrels, for example, each of them will have a different version of this variable.

If you want the state to be configured for multiple queries, consider either using a session or storing values ​​in your database. Class variables are really not suitable for cross-query storage.

+3
source

Source: https://habr.com/ru/post/1341347/


All Articles