Ruby on rails Using a broad method in helper and controller?

I have several variables that I would like to get from all controllers. Therefore, I defined them in my application application_controller.rb:

before_filter :initialize_vars def initialize_vars @siteTitle = "my title" @companyName = "company" end 

No problems. I wanted to do something similar with the logo, so I created another method that was called using before_filter.

  def logo image_tag("Logo.jpg", :alt => "Logo") end 

one instance of the img logo should link to the root of the site, so I called it with:

 <%=h link_to logo, root_path %> 

but it didn’t work in my layout! When I add my logo method to application_helper.rb, everything works fine. hhmmm.

what / where is a suitable place for all this? I mean only because I was able to do this, it does not do everything right!

Should I define my instance variables (which I consider to be global variables) in the application_controller and the logo method in my helper, how did I do this? I feel that I lack a fundamental understanding of why they need to go to different places. I'm not sure if this is HOW I call the β€œlogo” method or where I put it. I will play with the way I call, and how I wrote the logo method, because I feel that both methods should go to application_controller.

thoughts?

Thanks!

+4
source share
2 answers

Functions associated with rendering views are placed in auxiliary files. Usually they generate HTML content. If the helper method is used throughout the application in many places, put them in application_helper.rb , otherwise they should be placed in the corresponding helper files.

Since the instance variables that you have access to will be available in many controllers, you can initialize them in the application controller, just like you do.

+7
source

Helper methods are used for methods related to views, as these are your views that use helper methods. The instance variables that you see should be reorganized into methods that use content_for and then give them in your main layout file.

http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for

http://railscasts.com/episodes/8-layouts-and-content-for

+2
source

All Articles