It seems that a lot of the Rails applications I’ve been working on have a User model that has a many-to-many relation with a Role model, so that users can have a role like “admin” or “manager”, or even multiple roles. Along with this comes the necessity to conditionally show things in views. Recently I’ve started moving away from having explicit @current_user.has_role(”whatever”) calls in the views, to some code in the application_helper.rb file:


module ApplicationHelper

  def admin_only(&block)
    role_only("administrator", &block)
  end

  def manager_only(&block)
    role_only("manager", &block)
  end

private

  def role_only(rolename, &block)
    if not @current_user.blank? and @current_user.has_role?(rolename)
      block.call
    end
  end
end

Now in views I can easily mark off sections that should be displayed to only one user type:


<% admin_only do %>
  <!-- administrator content goes here -->
<% end %>
<% manager_only do %>
  <!-- manager content goes here -->
<% end %>

It would be easy to extend the role_only method to take an array of roles and check for membership in any of them, but I haven’t had need of that yet.

Hat tip to Aaron Longwell for introducing me to this technique.