A simple Ruby class for matching Rails controller/action patterns against current routes. Perfect for adding active states to navigation elements.
Drop nav_matcher.rb
into your Rails app (e.g., lib/nav_matcher.rb
or app/models/nav_matcher.rb
).
NavMatcher uses a simple pattern-based DSL:
# Single controller#action
'users#index' # Matches users controller, index action
# Multiple actions for same controller
'users#index,show,edit' # Matches users controller with index, show, OR edit actions
# Different controllers and actions
'users#index,posts#show' # Matches users#index OR posts#show
'users#index,show,posts#create' # Matches users#index, users#show, OR posts#create
'api/users#show' # Matches api/users controller, show action
'admin/posts#index,edit' # Matches admin/posts controller with index OR edit actions
# Check if current route matches pattern
NavMatcher.active?('users#index', 'users', 'index')
# => true
NavMatcher.active?('users#index,show', 'users', 'edit')
# => false
# app/helpers/application_helper.rb
class ApplicationHelper
def active_nav?(pattern)
NavMatcher.active?(pattern, params[:controller], params[:action])
end
def nav_class(pattern, active_class: 'active', inactive_class: '')
active_nav?(pattern) ? active_class : inactive_class
end
end
<!-- Simple active class -->
<%= link_to "Users", users_path, class: nav_class('users#index') %>
<!-- Multiple actions -->
<%= link_to "User Management", users_path,
class: nav_class('users#index,show,edit') %>
<!-- Mixed controllers -->
<%= link_to "Content", "#",
class: nav_class('users#index,posts#show,create') %>
<!-- Conditional rendering -->
<% if active_nav?('admin/users#index,show') %>
<div class="admin-notice">You're managing users</div>
<% end %>
Pattern | Matches | Description |
---|---|---|
users#index |
users#index | Single route |
users#index,show |
users#index, users#show | Multiple actions, same controller |
users#index,posts#show |
users#index, posts#show | Different controllers |
users#index,show,posts#create,edit |
users#index, users#show, posts#create, posts#edit | Mixed pattern |
api/users#show |
api/users#show | Namespaced controller |
admin/users#index,show,api/posts#create |
admin/users#index, admin/users#show, api/posts#create | Mixed with namespaces |