Last active
December 15, 2015 14:39
-
-
Save srpouyet/5276314 to your computer and use it in GitHub Desktop.
Rails 3 active class navigation helper which by default takes query params into account.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# application_helper.rb | |
# Dynamically set the current navigation item to "active". | |
# Takes query params into account by default. | |
# Passing in nil for query_params ignores query params. | |
# Based on http://stackoverflow.com/a/8552816/545017 | |
# Returns true when path is the active (current) path | |
def active_path?(path, include_query_params = true) | |
if include_query_params | |
current_params = params.keep_if { |key, value| !["action", "controller", "id"].include? key } | |
query_params = path =~ /\?/ ? Rack::Utils.parse_nested_query(path.split("?").last) : {} | |
(current_page?(path) && query_params == current_params) | |
else | |
current_page?(path) | |
end | |
end | |
# Extends link_to, injects "active" css class when href is active | |
def active_link_to(*args, &block) | |
path = block ? args[0] : args[1] | |
html_options = args.last.is_a?(Hash) ? args.pop.symbolize_keys : {} | |
inject_active_class(html_options) if active_path?(path) | |
args << html_options | |
link_to(*args, &block) | |
end | |
# See active_link_to | |
def inject_active_class(html_options) | |
html_options[:class] = html_options.has_key?(:class) ? html_options.delete(:class) + ' active' : 'active' | |
html_options | |
end | |
# See active_li_link_to | |
def active_class_if_current(path) | |
{class: "active"} if active_path?(path) | |
end | |
# Haml active_li_link_to. Returns link wrapped in li tag. | |
# Sets li & a class to "active" when href path is active. | |
def active_li_link_to(*args, &block) | |
path = block ? args[0] : args[1] | |
haml_tag :li, active_class_if_current(path) do | |
haml_concat(active_link_to(*args, &block)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment