Module: Credentials::Actor::ClassMethods

Defined in:
lib/credentials/actor.rb

Instance Method Summary collapse

Instance Method Details

#can?(actor, verb, *args) ⇒ Boolean

Returns true if the given actor has permission to perform the action ‘verb’ with the given args.

Returns:

  • (Boolean)


15
16
17
18
19
# File 'lib/credentials/actor.rb', line 15

def can?(actor, verb, *args)
  rulebook.can?(actor, verb, *args) ||
  can_by_association?(actor, verb, *args) ||
  can_by_actor_group?(actor, verb, *args)
end

#can_by_actor_group?(actor, verb, *args) ⇒ Boolean

Returns true if the actor belongs to any groups that have the requested permission.

Returns:

  • (Boolean)


43
44
45
# File 'lib/credentials/actor.rb', line 43

def can_by_actor_group?(actor, verb, *args)
  groups_for(actor).any? { |group| group.respond_to?(:can?) && group.can?(verb, *args) }
end

#can_by_association?(actor, verb, *args) ⇒ Boolean

Returns true if any magic methods give the requested permission. For example, by_association?(user, :edit, post) would try the following (in order):

  • user.is_editor_of?(post)

  • user.is_editor_for?(post)

  • user.is_editor_on?(post)

  • user.is_editor_at?(post)

  • user.is_editor_in?(post)

  • post.editor == user

  • post.editors.include?(user)

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
38
39
40
# File 'lib/credentials/actor.rb', line 30

def can_by_association?(actor, verb, *args)
  return false unless args.size == 1
  noun = verb.to_s.actorize
  object = args.first
  %w(of for on at in).each do |prep|
    return true if actor.respond_to?(method = "is_#{noun}_#{prep}?".to_sym) and actor.send(method, object)
  end
  return true if object.respond_to?(method = noun.to_sym) and object.send(method) == actor
  return true if object.respond_to?(method = noun.pluralize.to_sym) and object.send(method).include?(actor)
  false
end

#groups_for(actor) ⇒ Object

Returns a list of the groups the user belongs to, according to the :groups option to has_credentials.



48
49
50
51
52
53
54
# File 'lib/credentials/actor.rb', line 48

def groups_for(actor)
  case true
  when !credential_options[:groups].blank? then Array(credential_options[:groups]).map(&:to_sym).collect { |g| actor.send(g) }.flatten.uniq
  when actor.respond_to?(:groups) then actor.groups.flatten.uniq
  else []
  end
end