Active Menu in Rails

Info: Dieser Blogeintrag wurde von meinem alten Blogging Engine, die ich selbst gebaut hatte, umgezogen. Ich hatte leider nicht die Zeit die Platform fertig zu entwickeln oder neue Features hinzuzufügen. Deshalb lest ihr diesen Artikel nun in Ghost.

For this Site i was searching for a clean and nice way to mark an active menu element. For example, if you "Click" on Blog, the Blog element is Highlighted in awesome weed green color.

Some Developers using Rails are implementing some helper methods in Application_Helper.rb for example Yannis in an Stackoverflow Answer. His way to solve this problem is creating 2 helper methods, one for an controller and the other one for the action.

Looks like this:

def controller?(*controller)  

def action?(*action)  

Same here on Skilldrick's Solution:

def nav_link(link_text, link_path)  
 class_name = current_page?(link_path) ? 'current' : ''

 content_tag(:li, :class => class_name) do
 link_to link_text, link_path

He is generating a HTML Tag with everything needed inside. Nicer way but also a double checker.

So after a while I found a Helper Integrated in Rails named current_page?

my Solution

Defintion: current_page?(options)

True if the current request URI was generated by the given options.

The Awesome Way:

Let's start with an example:
I have my URL like this:

current_page?(controller: 'articles')  
# >true - because the controller is Articles_Controller.rb 

# >true - because the URL is BaseURL + /blog

# We can also check for an Controller + an Action
current_page?(controller: 'articles', action: 'index')  
# >true 

current_page?(action: 'new')  
# >true - or only an Action

current_page?(action: 'old')  
# >false - invalid Action 

A larger or realistic Example: We want to dedect if we are on the Site's Root or not. If we are mark the item as active, otherwise not.

<% if current_page?('/') %>  
 <a class=\"active green item\" href=\"/\">
<% else %>  
 <a class=\"green item\" href=\"/\">
<% end %>  
 <div class=\"column\"><i class=\"home icon\"></i>bMalum</div>

Or also with some RegEx :P

 <% if /\\/articles\\b/.match(request.fullpath) || current_page?('/blog') %>


current_page?(controller: 'test')  
# false - for an