Monday
Nov152010
Find the current_controller? in Rails
Monday, November 15, 2010 at 12:56PM
photo credit: spacesuitcatalyst
Rails provides a very useful current_page?(link) function but I needed a way to find if I was on the current_controller?(link) for adding a css class to menu links. This was useful for when I'm on a deeplink 'users/1/edit' but want to match a menu link to 'users/'. They share the same controller but not a the whole page link.
Download the GIST
#
# A rails helper snippet I find helpful for building main navigation
# when you want to highlight main pages (controllers) when browser
# requests a subpage.
#
# eg. current request '/users/1/edit' but we want to highlight
# the menu link to '/users'. current_page? will be false but
# the current_controller? function will be true
#
# Find if a link is uses the current controller.
# Used in building main navigation to include
# sublinks.
def current_controller?(link)
url_for(link).include? @controller.controller_name
end
# Create list elements for building navigation
def menu_link_li(text, link, classes = "", include_separator = false, new_tab = false)
begin
if current_controller? link
classes += " selected"
end
rescue Exception => e
# deal with a potential error of not using the helper with a request first being made.
end
if new_tab
link_text = link_to text, link, :target => "_blank"
else
link_text = link_to text, link
end
html = %{
mark |
Post a Comment | tagged
ruby in
Web Development
ruby in
Web Development
Reader Comments