Horse Voice
Horse Voice

Reputation: 8348

Are @@variables in a Ruby on Rails controller specific to the users session, or are all users going to see the same value?

I have a controller in which there is a "viewless" action. That controller is used to set a variable called @@ComputedData={}. But the data is computed based on a csv file a user of the application uploaded. Now are users going to see their specific data or will the @@ComputeData be the same for all users? Could someone explain me this concept? I'm really shaky on it. Thank you in advance and sorry for the noob question.

Upvotes: 6

Views: 6952

Answers (3)

raviolicode
raviolicode

Reputation: 2175

Be careful about using class variables in Rails.

Class variables are not shared between processes, so you will get inconsistent results.

For more information, look at:

  1. O'Reilly Ruby - Don't Use Class Variables!
  2. Why should we avoid using class variables @@ in rails?

You can always use a class and class methods to have the same data for all users:

class Computation
  attr_reader :computed_data
  @computed_data = 3
end

So you can ask for Computation.computed_data (will be 3),

but Computation.computed_data = 4 will give you a NoMethodError.

If you on the other side, if you want computed_data per user basis, you should save it on a database in an ActiveRecord Model (the typical case for Rails)...

Upvotes: 6

Tony Hopkinson
Tony Hopkinson

Reputation: 20320

@@ComputedData is a class variable. All users are going to see the same data, so baaaad idea.

Upvotes: 4

Rafa Paez
Rafa Paez

Reputation: 4860

Do not confuse class variables (@@) with global variables ($). In this post you will see the explanation and the different between them.

Upvotes: 2

Related Questions