简体   繁体   中英

ruby on rails application wide method in helper vs. controller?

I have several variables that I would like all controllers to access. So I defined them in my application_controller.rb :

      before_filter :initialize_vars

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

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

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

one instance of the logo img should link to the site root 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 the application_helper.rb everything works perfectly. hhmmm.

what / where is the appropriate place for all this stuff? I mean just because I was able to make it work doesn't make it right!

Should I define my instance variables (that I'm treating like global variables) in the application_controller and the logo method in my helper like I've done? I feel like I'm missing some fundamental understanding here of why they need to go in different places. I'm not sure if it's HOW I'm calling the "logo" method or where I'm putting it. I'm going to play with how I'm calling and how I've written the logo method because I feel like both methods should go in the application_controller.

thoughts?

Thanks!

Functions that are related to rendering views are placed in helper files. They typically generate HTML content. If the helper method is used across the app in many places, put them in application_helper.rb , otherwise they have to be placed in corresponding helper files.

As the instance variables you have is going to be accessed in many controllers, you can initialize them in application controller like you have.

Helper methods are used for methods pertaining to the views as it is your views that use the helper methods. The instance variables you have look like they should be refactored into methods that utilize content_for and then yield 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM