Class: Guts::PermissionsController

Inherits:
ApplicationController show all
Defined in:
app/controllers/guts/permissions_controller.rb

Overview

Permissions controller

Instance Method Summary collapse

Instance Method Details

#createObject

Note:

Redirects to #index if successfull or re-renders #new if not

Creates a permission for an object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'app/controllers/guts/permissions_controller.rb', line 39

def create
  authorize Permission, :create?

  ActiveRecord::Base.transaction do
    # Takes the custom grants field from the form and loops
    # and merges it into ther permission_params
    params.fetch(:grants, {}).each do |resource, grants|
      grants.each do |grant|
        Permission.new(
          permission_params.merge(
            resource: resource,
            grant: grant
          )
        ).save!
      end
    end
  end

  # Success, all done
  flash[:notice] = 'Permission was successfully granted.'
  redirect_to polymorphic_path([@object, :permissions])
rescue ActiveRecord::RecordInvalid => _
  # Something did not validate
  redirect_to new_polymorphic_path([@object, :permission])
end

#destroyObject

Revokes a permission



66
67
68
69
70
71
72
# File 'app/controllers/guts/permissions_controller.rb', line 66

def destroy
  @permission = @object.permissions.find { |p| p.id == params[:id].to_i }
  @permission.destroy if @permission

  flash[:notice] = @permission ? 'Permission was revoked.' : 'Error revoking permission.'
  redirect_to polymorphic_path([@object, :permissions])
end

#indexObject

Displays the permissions for an object



9
# File 'app/controllers/guts/permissions_controller.rb', line 9

def index; end

#newObject

Assigning a permission to an object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/controllers/guts/permissions_controller.rb', line 12

def new
  @permission = Permission.new
  authorize @permission

  # Load ApplicationPolicy first to get defaults
  standard_grants = grant_methods Guts::ApplicationPolicy
  
  # Loop over all policies
  @policies = {}
  Dir.new(Guts::Engine.root.join('app', 'policies', 'guts'))
     .entries
     .select { |file| file =~ /_policy/ }
     .each do |file|
       # Skip application policy since we completed that one
       next if file =~ /application_policy/

       # Get resource name, merge grants with standard grants
       klass    = "Guts::#{file.camelize.gsub('.rb', '')}"
       resource = klass.remove 'Policy'
       grants   = standard_grants | grant_methods(klass.constantize)

       @policies[resource] = grants
     end
end