views:

368

answers:

2

I have a situation where the header partial is called by the standard layout. (This is fairly common I assume) In the header is a search box - just like on stackoverlow. However, when the user is on the search page, I want to remove the search box from the header.

What I attempted to do was put a method in the ApplicationHelper.rb file like this:

def search_page?
    return false;
end

And then in SearchHelper.rb I have this:

def search_page?
    return true;
end

This doesn't work because the search_page function in SearchHelper.rb is the one that is being used no matter what controller is rendering the view. I know I could define a new layout and add a parameter to the header partial to signal not to render the search box, but that seems like overkill.

+1  A: 

First off, a few tweaks to your Ruby.

def search_page?
  true
end

You don't need the semi-colon or the return (whatever the last line will be the return value of your method).

Second, all helpers get loaded when your app is initialised. You can change this behaviour, but it's probably not worth it.

As for the rest, let's say you have a partial called _search_form.html.erb. Create a nice helper method (say, in search_helper.rb)

def search_form
  render(:partial => 'search/search_helper') unless @search_page
end

Use this to call the search form from your layout file. From then, you have some choices.

You can either create a before_filter in your controller:

before_filter :set_search_page

...your actions here...

private

def set_search_page
  @search_page = true
end

Or set the variable in your action:

def some_action
  @search_page = true
end

I'd say though that this is really a view issue, rather than something you want to be doing in your controllers. I'd create a helper method like this (again, in search_helper.rb).

def search_page
  @search_page = true
end

And then in the top of your view for that page, I'd use something like this:

<% search_page %>

(Note that it's <% and not <%= -- there's no output.)

The advantage here is you keep needless instance variables free from your controller.

Aupajo
+1  A: 

In your application helper, define this method:

def search_page?
  controller.controller_name != "search"
end

Replace "search" with whatever your controller is named.

August Lilleaas