2

I want to store a single variable across all my users in a rails application.

  • This variable is just an integer that can change sometimes.
  • I want it to persist across different launch of the server.
  • I want any controller to be able to change (and persist) the value

It sounds really easy to do, but I can't find any tool that would do it for me...

Antzi
  • 12,831
  • 7
  • 48
  • 74
  • Maybe not the perfect solution, but an Idea: Add a `Table/Model/Controller` for exactly this variable, that only can be Updated, Created and destroyed. Now you create your integer and you can use It from any controller by using `Model.where(false).update(value: 1970)` or `Model.where(false).value`. – Saggex Apr 23 '14 at 05:54
  • It would work but... I would like not to create a Table just to store a single integer. – Antzi Apr 23 '14 at 06:17
  • I understand, but If you won't find a solution, this might be helping. Here is someone, who allready asked a quite similar question: [Where to put Global variables in Rails 3](http://stackoverflow.com/questions/3598785/where-to-put-global-variables-in-rails-3) – Saggex Apr 23 '14 at 06:36
  • If not table persist it like a pid file in your shared folder. I do that for some mutexing related stuff – AshwinKumarS Apr 23 '14 at 06:37
  • Or create a helper method in your `application_controller.rb` like it's suggested here: [Global variable in Rails](http://stackoverflow.com/questions/5441798/global-variable-in-rails) – Saggex Apr 23 '14 at 06:39

3 Answers3

0

I would create a Key/Value table and model.

So far, it would only store one key, the integer you're talking about. Later, it could do a little more. The value could be a JSON document so you can store any kind of JSON supported native types very easily.

Mick F
  • 7,312
  • 6
  • 51
  • 98
0

Simply create a model with one attribute. And then create one instance of that model. Then access this from your controllers

for example

Model.first.attribute
Marco Prins
  • 7,189
  • 11
  • 41
  • 76
0

I ended up using the gem rails-settings-cached

It provide an easy way to access a persistant variable:

Setting.a_setting = 42
Setting.a_setting #42
Antzi
  • 12,831
  • 7
  • 48
  • 74