Hi, welcome to Word of Mike, my little corner of the internet. I am a Software/Web Developer working in North Yorkshire. I mainly write about programming but my other passion is politics so beware. (click to hide)

2014-04-01 09:18:39 UTC

Highlighting Active Tabs in Rails

Just a simple helper method for highlighting active UI tabs in Rails based upon the controller and action that rendered the page.

# # #
# If you pass:
#  - String, then it highlight for that controller name
#  - Array, then it will highlight for those actions
#  - Hash, then it will highlight for only those controller and action combinations
def is_active?(controller_action_hash_or_array_or_string)
  controller = params[:controller]
  action = params[:action]

  controller_action_hash =
    case controller_action_hash_or_array_or_string
    when Array
      { controller => controller_action_hash_or_array_or_string }
    when String
      { controller_action_hash_or_array_or_string => nil }
    when Hash
      raise ArgumentError, "what are you even ..."

  controller_action_hash = Hash[controller_action_hash.map{|k,v| [k, [v || action].flatten]}]

  "active" if controller_action_hash.key?(controller) && controller_action_hash[controller].include?(action)
A bootstrap implementation of a tabbed nav with the various possible uses of the helper might look like:
<ul class="nav nav-tabs">
  <li class="<%= is_active?('item_one' => 'show') %>"><%= link_to "Item 1", item_one_path(@item) %></li>
  <li class="<%= is_active?('item_two') %>"><%= link_to "Item 2", item_two_path %></li>
  <li class="<%= is_active?(['show', 'index']) %>"><%= link_to "Item 3", item_three_path %></li>
  <li class="<%= is_active?({ controller_one: [:show, :edit] }) %>"><%= link_to "Item 4", item_three_path %></li>
  <li class="<%= is_active?({ controller_one: nil, controller_two: nil }) %>"><%= link_to "Item 5", item_four_path %></li>