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?
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.
Public variables in general in a class are a bad idea. Since this means other classes/programs, can modify the state of instances.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With