Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 618
Horse Voice Avatar asked Mar 04 '14 23:03

Horse Voice


People also ask

What does @@ means in Ruby?

@@ denotes a class variable, i.e. it can be inherited. This means that if you create a subclass of that class, it will inherit the variable.

What decides which controller receives which requests in Rails?

Routing decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different actions. Each action's purpose is to collect information to provide it to a view.

How many types of variables are used in Ruby and what are they?

There are different types of variables in Ruby: Local variables. Instance variables. Class variables.

What does controller do in Rails?

The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.


2 Answers

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)...

like image 55
raviolicode Avatar answered Nov 10 '22 04:11

raviolicode


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

like image 42
Tony Hopkinson Avatar answered Nov 10 '22 06:11

Tony Hopkinson