Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - Global Variable?

I am a new Ruby on Rails user and had a question. I have an idea of what I want my Users DB to look like but was wondering whether or not I should add an additional value to it. Basically I need a variable to signal to all users that it is safe to proceed with a certain action. This variable would be persistent across all users and should be visible to all users, but I want the server to be able to change this variable as well. When programming in other languages, I would use a global variables, so I wanted to check if that is also the case here. If so, would this be the best approach for going about it: Site-Wide Global Variables in Ruby on Rails. Also, how would I update the global variables. Thanks for any help!

like image 319
hassaanm Avatar asked Jun 23 '10 18:06

hassaanm


People also ask

How do you use a global variable in Ruby?

Assignments to global variables can be made from anywhere in the program. Global variables are always prefixed with a dollar sign. It is necessary to define a global variable to have a variable that is available across classes. When a global variable is uninitialized, it has no value by default and its use is nil.

What is @variable in Ruby?

@variable s are called instance variables in ruby. Which means you can access these variables in ANY METHOD inside the class. [ Across all methods in the class] Variables without the @ symbol are called local variables, which means you can access these local variables within THAT DECLARED METHOD only.

Does Ruby have global variables?

Global Variable has global scope and accessible from anywhere in the program. Assigning to global variables from any point in the program has global implications. Global variable are always prefixed with a dollar sign ($).


1 Answers

A global variable doesn't fit your need. It doesn't spread across all the Ruby processes. If your web server spawns 5 ruby processes to handle 5 request at the same time, the variable defined in the first process won't be visible to the others.

There are other solutions available. You can use a database and store the flag/information on the database. Otherwise, you can use a file and store the value in the file. The best solution would be an in-memory shared data source, such as memcached or Redis.

like image 106
Simone Carletti Avatar answered Oct 04 '22 17:10

Simone Carletti