Shan
Shan

Reputation: 653

How can a value be stored so that it's shared across an entire request in Ruby on Rails?

How can a value be stored so that it's shared across an entire request (i.e. make it accessible in controllers , views and models )?

  1. Put is as a Global variable
  2. Create a Singleton and store it in a class variable
  3. Store it in a thread locally.

Upvotes: 2

Views: 1060

Answers (5)

Santhosh
Santhosh

Reputation: 29124

Any instance variable initialized in a controller#action will be available in the views. To use these variables in a model, you could pass them as an argument to the model method.

Upvotes: 3

Benjamin Bouchet
Benjamin Bouchet

Reputation: 13181

Variable set at start-up and for which the value is not supposed to change. Shared and identical for all users and all threads: use a constant.

Variable set at run-time for which the value can change. Shared and identical for all users and all threads: use class instance variable.

Variable 'private' for a user and a thread, but accessible across all rails components: use a Thread variable.

Upvotes: 1

xlembouras
xlembouras

Reputation: 8295

I think the only way to have this functionality, is to have a session (or session like) store mechanism.

Having a session store will make your data available in all controllers and views, and you can pass the data as a parameter to your models.

If you don't want to have that kind of data in your session, you can store a hashed uid in the session and make a look up in an additional store (such as redis). eg:

uid = session[:uid]
data_1 = Redis.handler_get_data_1_by_id(uid)

which will give you:

  • flexibility (you can add extra data to a user or whatever you identifier is)
  • security (your data are on your system only and by having a hashed_id different sessions can't access each others data)
  • performance (as redis' performance is similar to a memcache)

Upvotes: 0

Rahul Singh
Rahul Singh

Reputation: 3427

you can create a custom configuration variable in your initializers, create a file say global_var.rb inside your config/initializers

inside this file declare any variable and assign it a value like

custom_var = "Hello World!"

now to use this you have to do

Rails.configuration.custom_var = custom_var , so your global_var.rb should include

custom_var = "Hello World!"
Rails.configuration.custom_var = custom_var

now you have Rails.configuration.custom_var which will output Hello World and you can use it anywhere.

but this will be initialized whenever you start your application/rails server.

Upvotes: 0

Andrii Furmanets
Andrii Furmanets

Reputation: 1161

Probably you can store value in session like this session[:foo] = @foo, and you should have ability to get this value whatever you want

Upvotes: 1

Related Questions