Skip to content

Instantly share code, notes, and snippets.

@kirel
Created July 22, 2013 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kirel/6054485 to your computer and use it in GitHub Desktop.
Save kirel/6054485 to your computer and use it in GitHub Desktop.
# Usage:
#
# In your controller
#
# before_filter :ser_active_navigation_item
# def set_active_navigation_item
# active_navigation_item :we, :are, :here
# # or
# active_navigation_item controller.controller_name, controller.action_name
# # or
# # any custom logic
# end
#
# or in your view
#
# !!!haml
# - active_navigation_item :we, :are, :here
#
# and then
#
# !!!haml
# %nav.second
# %ul
# %li
# =link_to 'we', we_path, class: ('active' if active_navigation_item?(:we)) # true
# %ul
# =link_to 'are', are_path, class: ('active' if active_navigation_item_class(:we, :are)) # false
# %li= link_to 'there', there_path, class: ('active' if active_navigation_item?(:there)) # nil
#
# Caveats:
# Streaming responses might break this because you are likely calling `active_navigation_item` from your view and `active_navigation_item?` from your layout - this means you have to move setting your active navigation item to the controller
module ActiveNavigationItem
extend ActiveSupport::Concern
# Set if called with arguments
# otherwise get array
def active_navigation_item(*hierarchy)
if hierarchy.any?
@active_navigation_item = hierarchy.map(&:to_sym)
else
@active_navigation_item
end
end
# Get active navigation item state
def active_navigation_item?(*hierarchy)
@active_navigation_item[0...hierarchy.length] == hierarchy.map(&:to_sym) if @active_navigation_item
end
included do
helper_method :active_navigation_item, :active_navigation_item?
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment