Skip to content

Instantly share code, notes, and snippets.

@pelted
Last active February 9, 2021 09:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pelted/5dac756f690a61f698145dc9495a9633 to your computer and use it in GitHub Desktop.
Save pelted/5dac756f690a61f698145dc9495a9633 to your computer and use it in GitHub Desktop.
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