Module: Allowance::Subject

Defined in:
lib/allowance/subject.rb

Instance Method Summary collapse

Instance Method Details

#allow(verbs, objects = nil, scope = true) ⇒ Object



33
34
35
36
37
38
39
40
# File 'lib/allowance/subject.rb', line 33

def allow(verbs, objects = nil, scope = true)
  expand_permissions(verbs).each do |verb|
    [objects].flatten.each do |object|
      @permissions ||= {}
      @permissions[[verb, object]] = scope
    end
  end
end

#allowed?(verb, object = nil) ⇒ Boolean

Returns:

  • (Boolean)


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/allowance/subject.rb', line 17

def allowed?(verb, object = nil)
  # Allow access if there is a direct match in permissions.
  return true if permissions[[verb, object]]

  # If object is a resource instance, try its class.
  if object.class.respond_to?(:model_name)
    if allowed?(verb, object.class)
      # See if the object is part of the defined scope.
      return allowed_scope(object.class, verb).exists?(object)
    end
  end

  # Once we get here, access can't be granted.
  false
end

#allowed_scope(model, verb = nil) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/allowance/subject.rb', line 42

def allowed_scope(model, verb = nil)
  verb ||= :read

  if p = permissions[[verb, model]]
    case p
      when Hash, String, Array then model.where(p)
      when Proc then p.call(model)
      else model.scoped
    end
  else
    model.where('1=0')   # TODO: replace this with .none once available
  end
end

#define_permissionsObject



12
13
14
15
# File 'lib/allowance/subject.rb', line 12

def define_permissions
  # TODO: log a warning that the subject's define_permissions needs
  #       to be overloaded.
end

#permissionsObject



3
4
5
6
7
8
9
10
# File 'lib/allowance/subject.rb', line 3

def permissions
  unless @permissions_defined
    define_permissions
    @permissions_defined = true
  end

  @permissions || {}
end