Skip to content

Instantly share code, notes, and snippets.

@brennovich
Created September 17, 2015 16:58
Show Gist options
  • Save brennovich/8fa78a1c993aad7a04ec to your computer and use it in GitHub Desktop.
Save brennovich/8fa78a1c993aad7a04ec to your computer and use it in GitHub Desktop.
Quick and simple example of how output active menu class for Rails applications
# Example:
#
# Let's say we're are accessing a new form to create a Post, probably
# our page will be rendered by PostsController and new action:
class PostsController < ApplicationController
def new
@post = Post.new
render :new
end
end
# If we want to add class `active` into our menu view we need to
# specify when it should be active for the active_menu_class helper:
#
# app/views/posts/new.html.erb
<ul id="menu">
<li class="<%= active_menu_class('posts', 'new') %>">Novo Post</li>
</ul>
module MenuHelper
# It's best to not use methods with question mark because they suggest
# a return of a boolean (true or false)
#
# Rails give us two helper that tell us which controller and action
# are currently being accessed.
def active_menu_class(active_controller, active_action)
# Could be 'active' instead :active, I just prefer to use a Symbol
# over String
:active if action_controller == controller_name && active_action == action_name
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment