Module: Authorization::AuthorizationHelper

Defined in:
lib/declarative_authorization/helper.rb

Instance Method Summary collapse

Instance Method Details

#has_any_role?(*roles) ⇒ Boolean

Returns:

  • (Boolean)


66
67
68
69
70
# File 'lib/declarative_authorization/helper.rb', line 66

def has_any_role?(*roles)
  controller.has_any_role?(*roles) do
    yield if block_given?
  end
end

#has_any_role_with_hierarchy?(*roles) ⇒ Boolean

Returns:

  • (Boolean)


72
73
74
75
76
# File 'lib/declarative_authorization/helper.rb', line 72

def has_any_role_with_hierarchy?(*roles)
  controller.has_any_role_with_hierarchy?(*roles) do
    yield if block_given?
  end
end

#has_role?(*roles) ⇒ Boolean

While permitted_to? is used for authorization in views, in some cases content should only be shown to some users without being concerned with authorization. E.g. to only show the most relevant menu options to a certain group of users. That is what has_role? should be used for.

Examples:

<% has_role?(:sales) do %>
<%= link_to 'All contacts', contacts_path %>
<% end %>
...
<% if has_role?(:sales) %>
<%= link_to 'Customer contacts', contacts_path %>
<% else %>
...
<% end %>

Returns:

  • (Boolean)


53
54
55
56
57
# File 'lib/declarative_authorization/helper.rb', line 53

def has_role?(*roles)
  controller.has_role?(*roles) do
    yield if block_given?
  end
end

#has_role_with_hierarchy?(*roles) ⇒ Boolean

As has_role? except checks all roles included in the role hierarchy

Returns:

  • (Boolean)


60
61
62
63
64
# File 'lib/declarative_authorization/helper.rb', line 60

def has_role_with_hierarchy?(*roles)
  controller.has_role_with_hierarchy?(*roles) do
    yield if block_given?
  end
end

#permitted_to?(privilege, object_or_sym = nil, options = {}) ⇒ Boolean

If the current user meets the given privilege, permitted_to? returns true and yields to the optional block. The attribute checks that are defined in the authorization rules are only evaluated if an object is given for context.

Examples:

<% permitted_to? :create, :users do %>
<%= link_to 'New', new_user_path %>
<% end %>
...
<% if permitted_to? :create, :users %>
<%= link_to 'New', new_user_path %>
<% else %>
You are not allowed to create new users!
<% end %>
...
<% for user in @users %>
<%= link_to 'Edit', edit_user_path(user) if permitted_to? :update, user %>
<% end %>

To pass in an object and override the context, you can use the optional options:

permitted_to? :update, user, :context => :account

Returns:

  • (Boolean)


31
32
33
34
35
# File 'lib/declarative_authorization/helper.rb', line 31

def permitted_to?(privilege, object_or_sym = nil, options = {})
  controller.permitted_to?(privilege, object_or_sym, options) do
    yield if block_given?
  end
end