Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 692
twinturbotom Avatar asked Jan 19 '23 21:01

twinturbotom


1 Answers

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.

like image 179
Arun Kumar Arjunan Avatar answered Jan 25 '23 23:01

Arun Kumar Arjunan