Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable in Rails

I have a feedback form in my Rails application. The feedback form requires initializing of the @support variable, and it should be visible on every page. The initialization is very short:

@support = Support.new(:id => 1)

However it would be nice to have this variable initialized once and access it from everywhere. How is that possible to do?

like image 752
Alexander Savin Avatar asked Mar 26 '11 10:03

Alexander Savin


2 Answers

you can use a helper method (in the application controller) to initialize the support variable . Something like this :

class ApplicationController < ..
   ...
   helper_method :my_var

   def my_var
      @support = Support.new(:id => 1)
   end
   ...

 end
like image 104
hkairi Avatar answered Oct 13 '22 02:10

hkairi


A global variable starts with the dollard sign '$' like :

$support = Support.new(:id => 1)

However, global variables is bad :-) You should read this post by "Simone Carletti".

like image 32
Sandro Munda Avatar answered Oct 13 '22 01:10

Sandro Munda