Why should we avoid using class variables @@ in rails?

Simply because they are not thread safe. Many rails=capable servers are multi-threaded. That means there may be multiple running instances of your application at any given time and any request by one of your users is going to be arbitrarily assigned to one of them. Class variables are not shared between processes so there is a possibility that your class variable will be different in a subsequent request.

Even if you deliberately manage to run your app in a single threaded server, there is no guarantee that your app won’t be restarted between requests, losing your class variable.

If you want functionality similar to what class variables provide, I strongly recommend that you look into key-value stores such as Memcached or Redis.

Leave a Comment