Raaz
Raaz

Reputation: 1751

How do I declare a variable that is accessible throughout the whole Rails application?

My application depends upon a variable page_name but the value in the variable page_name is set only after submitting a form.

Should I use a session? When I searched I found out that sessions will be destroyed if my application is behind a load-balancer.

What would be a better way to make a variable accessible throughout the whole Rails application?

Creating a constant could have solved my problem but the value in the variable is not set until the user fill the data in a form field and submits the data. So basically, the user is responsible to fill the value in the variable my whole application depends upon.

Upvotes: 1

Views: 1845

Answers (3)

luke
luke

Reputation: 1578

title is a local variable. They only exists within its scope, which is the current block.

@title is a instance variable, and it is available to all methods within the class.

You can read more in "Struggling With Ruby: Variables".

In Ruby on Rails, declaring your variables in your controller as instance variables like @title makes them available to your view.

Upvotes: 0

jrochkind
jrochkind

Reputation: 23317

Sessions aren't neccesarily destroyed by a load balancer -- it depends on your session configuration AND your load balancer configuration/capabilities. But ordinarily sessions should work fine with a load balancer. But session variables are just available to.. that session. Is the value session-specific, or is it really global accross sessions?

If the latter, I'd just stick it in the database. Even make a new table for GlobalVariables or something, with just name and value.

It's a "hacky" solution, but it'll work fine, and is easy to do.

But as I re-read your question... nevermind, I don't think you actually want to do what you asked anyway. There's no reason you should need to create a "variable that is accessible through the whole rails app" to solve that problem. You shouldn't need sessions either. I'll let others try to answer your un-asked actual questions.

Upvotes: 1

Phil
Phil

Reputation: 2807

You'll need to persist the value in either the database (using ActiveRecord), or in a shared memcache server (assuming you can accept the variable will be lost if it is pushed out of cache).

You'll just set the database value for example in your controller create action just like any other model.

First, create the model

rails generate model variable_name variable_value

To save a value in it from your def create action:

@app_store = AppStore.find_or_initialize_by_name('variable_name')
@app_store.variable_value = secure_params[:variable_value]
@app_store.save

then retrieve from anywhere in your app with

@app_store = AppStore.find_by_name('variable_name')
val = @app_store.variable_value

Upvotes: 5

Related Questions