Skip to content

Instantly share code, notes, and snippets.

@pawelztef
Created March 20, 2018 09:11
Show Gist options
  • Save pawelztef/d973cacf409d8c8ae82745661dfcd1d8 to your computer and use it in GitHub Desktop.
Save pawelztef/d973cacf409d8c8ae82745661dfcd1d8 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
module ApplicationHelper
def active_for(options = {})
name_of_controller = options[:controller] || nil
name_of_action = options[:action] || nil
request_path = options[:path] || nil
if request_path.nil?
if (name_of_action.nil? or name_of_action == action_name) and
name_of_controller == controller_name
'active'
else
''
end
else
request_path == request.path ? 'active' : ''
end
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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment