Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Why should we avoid using class variables @@ in rails? Is there any security loopholes with that. Please answer as I am new with rails. and I am much using instance variable @variable_name . I tried once @@variable_name .

I know only about class variable is, Class variable is sharable between object

But I really would like to know Why should we avoid using class variables @@ in rails?

like image 756
Manish Shrivastava Avatar asked Feb 22 '12 14:02

Manish Shrivastava


People also ask

Are class variables bad Ruby?

The problem with class variables in Ruby is that when you inherit from a class then the new class does not get a new copy of its own class variable but uses the same one that it inherited from its superclass.

Why is it not recommended to make all of classes variable public?

Public variables in general in a class are a bad idea. Since this means other classes/programs, can modify the state of instances.

Should you use class variables?

Class variables are useful because they allow you to declare a variable when a class has been built, which can then be used later in your class. Like regular variables, class variables can store data of any type.

When would you use a class variable?

Class variables are declared inside the class definition but outside any of the instance methods and constructors. It is gets created when an instance of the class is created. It is created when the program begins to execute. Changes made to these variables through one object will not reflect in another object.


1 Answers

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.

like image 141
edgerunner Avatar answered Sep 19 '22 16:09

edgerunner