We needed to add CSS to HTML links based on certain conditions (for instance, if you're already there). That's pretty easy to do by using link_to_unless, but the easy way isn't very DRY (Don't Repeat Yourself):
<%= link_to_unless(@current_controller=='faq', "Frequently Asked Questions", faq_path){
link_to("Frequently Asked Questions", faq_path, :class => 'active')
} %>
Hear how the text "Frequently Asked Questions" is screaming at you to stop typing it over & over? Well, this pattern (adding an "active" class to say YOU ARE HERE) happens often enough that it had to be broken out into a helper:
def link_to_active_if( condition, link_title, link_path = {}, opts = {} )
if condition
classes = opts.delete(:class) || ""
classes.rstrip!
# checking to see if "active" is already one of the classes assigned, and if NOT, append it to the classes string
unless classes =~ /^(\w*\s+)*active(?!\w)/
if classes.blank?
classes = 'active'
else
classes << " active"
end
end
end
old_opts = opts.dup
link_to_if( condition, link_title, link_path, opts.merge( {:class => classes} ) ) {
link_to( link_title, link_path, old_opts )
}
end
As you may see, there's kind of a hack at the regex beginning ("unless classes =~ " etc.) Ruby 1.9 users can get around that with the new hotness Regex engine Oniguruma (which allows negative lookbehind assertions), but we're a bit more restricted. At any rate, the craziness checking for "active" means you can send the class "active" in through the opts hash and only get 1 "active" back in the class string.
The new helper call is quite a bit cleaner, even if it doesn't make the questions REAL FAQ's:
<%= link_to_active_if( @current_controller=='faq', "Frequently Asked Questions", faq_path ) %>
That's great in cases where we want the link active for multiple actions in a controller (for instance), but since the current page/action being the exact link location is another common pattern, we can easily add another helper that uses the new link_to_active_if:
def link_to_active_if_current( link_title, link_path = {}, opts = {} )
link_to_active_if current_page?(link_path), link_title, link_path, opts
end
Giving us:
<%= link_to_active_if_current("Frequently Asked Questions", faq_path) %>













