Created
December 28, 2009 06:16
-
-
Save dandean/264555 to your computer and use it in GitHub Desktop.
rails smart_link_to highlights itself when the URL matches it's href
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
module ApplicationHelper | |
# `smart_link_to` is an *exact* copy of `link_to`, with some added functionality. | |
# I would rather simply call `link_to` and then add in my bits, but I don't know | |
# how to proxy `call_to` with the given arguments. | |
def smart_link_to(*args, &block) | |
if block_given? | |
options = args.first || {} | |
html_options = args.second | |
concat(link_to(capture(&block), options, html_options).html_safe!) | |
else | |
name = args.first | |
options = args.second || {} | |
html_options = args.third | |
# Check if a wrapper element should be rendered around the link | |
wrap = options[:wrap] | |
# Delete wrap option from options so it doesn't affect the rest of the tag... | |
options.delete(:wrap) if !wrap.nil? | |
url = url_for(options) | |
if html_options | |
html_options = html_options.stringify_keys | |
href = html_options['href'] | |
convert_options_to_javascript!(html_options, url) | |
tag_options = tag_options(html_options) | |
else | |
tag_options = nil | |
end | |
href_attr = "href=\"#{url}\"" unless href | |
tag = "<a #{href_attr}#{tag_options}>#{name || url}</a>".html_safe! | |
# If a wrap was specified, add it to the tag. | |
if !wrap.nil? | |
tag = "<#{wrap}>" + tag + "</#{wrap}>" | |
end | |
href_value = tag.match(/href="(.*?)"/)[1] | |
# Check if current request path starts with the rendered href value | |
# Unless the rendered href value is "/" | |
# Only show "/" link as on if href is exactly "/" | |
if (request.path == "/" && href_value =="/") || (href_value != "/" && request.path.starts_with?(tag.match(/href="(.*?)"/)[1])) | |
# href and url are equal, add the "on" class to the tag. | |
if tag.include?('class="') | |
# inject into class attribute | |
tag = tag.sub(/(class=")/, '\0on') | |
else | |
# add class attribute and name | |
tag = tag.sub(/>/, ' class="on">') | |
end | |
end | |
tag # return the tag | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment