Skip to content

Instantly share code, notes, and snippets.

@suweller
Last active August 29, 2015 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suweller/10978651 to your computer and use it in GitHub Desktop.
Save suweller/10978651 to your computer and use it in GitHub Desktop.
Display menu items based on role-based access control
# Given an app with Role-based access control (for example cancan)
module MenuHelper
def menu_item(*args)
options = args.last.is_a?(Hash) ? args.pop : {}
klass = args.pop
return nil unless can?(:index, klass)
args << klass.model_name.route_key
path = "/#{args.join('/')}"
content_tag(:li, class: ('active' if request.path.starts_with?(path))) do
link_to(t(args.join('.'), scope: 'app.menu'), path, options)
end
end
end
app:
menu:
admin:
users: All users
manager:
users: My team
%ul.menu
%li= link_to(
= menu_item(:admin, User, id: 'people')
= menu_item(:manager, User, id: 'folks')
-# Some exceptions may need to be made...
- if current_user.persisted?
%li= link_to 'Sign out', destroy_user_session_path, method: :delete
- else
%li= link_to "Sign in", new_user_session_path
-# Resulting in:
<ul class='menu'>
<li id='people'><a href='/admin/users'>All users</a></li>
<li id='folks' class='active'><a href='/manager/users'>My team</a></li>
</ul>
<!-- etc... -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment