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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With