Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby on Rails. Class "active" for menu items based on Path or Controller and Action names
ACTIVE_CLASS = 'is-active'.freeze
def active_for(options)
name_of_controller = options.fetch(:controller) { nil }
name_of_action = options.fetch(:action) { nil }
request_path = options.fetch(:path) { nil }
return ACTIVE_CLASS if request_path && request_path == request.path
if name_of_controller == controller_name
ACTIVE_CLASS if name_of_action.nil? || (name_of_action == action_name)
end
end
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav navbar-right">
<li class='<%= active_for(path: "/users/#{current_user.id}") %>'>
<%= link_to current_user %>
</li>
<li class='<%= active_for(controller: "events") %>'>
<%= link_to events_path %>
</li>
<li class='<%= active_for(controller: "users", action: "edit") %>'>
<%= link_to edit_user_path(current_user) %>
</li>
</ul>
</div>
@kstratis
Copy link

kstratis commented Apr 2, 2019

awesome work!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment