10

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?

4 Answers 4

13

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
Sign up to request clarification or add additional context in comments.

2 Comments

This is definitely the way to go. It has the added benefit of not getting executed unless you need it, whereas a before filter will end up needing lots of filters or getting called even when you don't need it.
Thanks Alan, i didn't want to confuse the readers ! that's why i didn't go further :)
5

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".

Comments

5

Rather than a global variable, you probably want to put something in the ApplicationController.

Either:

before_filter initialize_support

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

Or:

helper_method support_form

def support_form
      @support_form ||= Support.new(:id => 1)
end

Comments

2

It sounds like what you really want is to store the data in the user's session, right? For more details, see http://www.ozmox.com/2009/10/13/rails-sessions/.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.