Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permanent variable in Rails

Lets say that on top of my Rails app there is a bar with piece of text displayed - latest hot deal, scheduled downtime notfication, something like that. It's a single, on of a kind information that needs to be accessed on basically every request, and may be updated from time to time. What is the best way to achieve this?

What I'd like to do is some kind of permanent global variable (accessible from controllers).

  • It will be updated very rarely, so there's no problem if for some time after update there will be an inconsistency between workers.
  • On the other hand, it should be persistent in case of server fault (periodic backup is enough).
  • It will be accessed really often, so it should be as fast as possible - preferably stay in memory.
  • Also, it's only one of a kind, so I'd really prefer not to bloat the app with a dedicated database model.

Something like that is damn easy in Node.js for example, but I couldn't find a single way to achieve this in Rails. What shall I do?

EDIT

Thanks for the answers so far, but while they're inspiring, I think that I should stress out one key functionality that they're all missing. The variable should be editable inside the app and persistent. While it's possible to edit your variables, in case of server restart I'm back to the default - which is bad.

like image 889
Hubert OG Avatar asked Feb 21 '23 07:02

Hubert OG


1 Answers

It really depends on what you are looking for. You could do something very simply by putting it in your application_controller.rb

class ApplicationController < ActionController::Base
   def system_message
     "Come buy our amazing .99 iphone chocolate bar apps, with 100% more gamification!"
   end
end

That function (and string) is then accessible from any controller in your application. You could also specify something in the after_initialize block in your application.rb file.

config.after_initialize do
  ::MYTEXT  = "MY SUPER AMAZING TEXT"
end

You could also create your own file under the initializers directory, which is preloaded in rails.

so siteAnnounce.rb

MYANNOUNCEMENT = "NOW LISTEN TO ME!"

You may also want to check out this Railscast video about site wide announcements

like image 188
Justin Herrick Avatar answered Mar 08 '23 12:03

Justin Herrick