Skip to content

Instantly share code, notes, and snippets.

@zelaznik
Last active May 2, 2022 11:21
Show Gist options
  • Save zelaznik/86bc43cec8da28c4866ecc8d35cf1658 to your computer and use it in GitHub Desktop.
Save zelaznik/86bc43cec8da28c4866ecc8d35cf1658 to your computer and use it in GitHub Desktop.
Making an "active" link in Rails / Stimulus
module ApplicationHelper
def active_link_to(*args, **params, &block)
href = block_given? ? args.first : args[1]
active_class_name = params.delete(:active_class_name) || 'active'
if route_is_active?(href)
# Add in the active class name in ruby, just in case javascript is disabled
existing_classes = params[:class] || ''
params[:class] = appended_name(existing_classes, active_class_name)
end
# Add in the 'active-link' controller, but don't erase any other simulus controllers either
params[:data] = params[:data] || {}
existing_controllers = params[:data][:controller] || ''
params[:data][:controller] = appended_name(existing_controllers, 'active-link')
# Pass the optional "active_class_name" value to the active-link controller
params[:data][:active_link_active_class_value] = active_class_name
link_to(*args, **params, &block)
end
def route_is_active?(href)
request.path == href ||
request.path.starts_with?("#{href}/") ||
request.path.starts_with?("#{href}?")
end
def appended_name(original, name)
class_names = original.strip.split(/\s+/).to_set
class_names << name
class_names.join(' ')
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment