module Corral::Ability

Public Instance Methods

allow_anything!() click to toggle source

Allow the object to perform any action on any subject. This overrides any cannot rules.

# File lib/corral/ability.rb, line 44
def allow_anything!
  @allow_anything = true
end
authorize!(action, subject, *args) click to toggle source

Check whether the object has authorization to perform the action it intends to on the subject. Raise AccessDenied if it doesn't.

@param action [Symbol] The intended action. @param subject [Object] The subject of the action. @raise [AccessDenied] if the object does not have permission.

# File lib/corral/ability.rb, line 55
def authorize!(action, subject, *args)
  raise AccessDenied if cannot?(action, subject, *args)
end
can(action, subject, &block) click to toggle source

Adds a granting-access rule.

@param action [Symbol] The action, represented as a symbol. @param subject [Object] The subject. @param block [Hash] Variable arguments for more granular matching.

# File lib/corral/ability.rb, line 30
def can(action, subject, &block)
  rule_for(subject).add_grant(action, block)
end
can?(action, subject, *args) click to toggle source

Check whether the object can perform an action on a subject.

@overload can?(action, subject)

@param action [Symbol] The action, represented as a symbol.
@param subject [Object] The subject.

@overload can?(action, subject, args)

@param action [Symbol] The action, represented as a symbol.
@param subject [Object] The subject.
@param args [Hash] Variable arguments for more granular matching.

@return [Boolean] True or false.

# File lib/corral/ability.rb, line 13
def can?(action, subject, *args)
  return true if @allow_anything
  lookup_rule(subject).authorized?(action, subject, args)
end
cannot(action, subject, &block) click to toggle source

Inverse of can.

@see can

# File lib/corral/ability.rb, line 37
def cannot(action, subject, &block)
  rule_for(subject).add_deny(action, block)
end
cannot?(*args) click to toggle source

Inverse of can?.

@see can?

# File lib/corral/ability.rb, line 21
def cannot?(*args)
  not can?(*args)
end

Protected Instance Methods

lookup_rule(subject) click to toggle source

Lookup a rule for a particular subject.

@param subject [Object] The subject.

# File lib/corral/ability.rb, line 76
def lookup_rule(subject)
  case subject
  when Symbol, Module
    r = subjects[subject] || subjects[:all] || NullRule
  else
    subjects[subject.class] || NullRule
  end
end
rule_for(subject) click to toggle source

Find or create a new rule for the specified subject.

@param subject [Object] The subject.

# File lib/corral/ability.rb, line 69
def rule_for(subject)
  subjects[subject] ||= SubjectRule.new
end
subjects() click to toggle source

Subjects hash.

# File lib/corral/ability.rb, line 62
def subjects
  @subjects ||= {}
end