module SimpleCan::ClassMethods

Public Instance Methods

add_method_to(scope, method) click to toggle source
# File lib/simple_can.rb, line 52
def add_method_to(scope, method)
  strategy_set!

  klass = self
  method = method.to_s
  role, name, do_raise = SimpleCan.strategy.roles.reduce(nil) do |acc, r|
    acc || method.match(/^#{r}_(.+(!)|.+)$/)&.captures&.unshift(r)
  end
  return if name.nil?
  scope.send(:define_method, name) do |*args, &blk|
    can = SimpleCan.strategy.test(role, klass.capability)
    if !can && !do_raise.nil?
      raise SimpleCan::Unauthorized, "unauthorized for #{name} with #{role}"
    elsif !can
      if respond_to?("fail_#{name}")
        return send("fail_#{name}")
      else
        return SimpleCan.strategy.fail(role, name)
      end
    else
      return send(method, *args, &blk)
    end
  end
end
capability() click to toggle source
# File lib/simple_can.rb, line 82
def capability
  Thread.current[THREAD_VAR]
end
capability=(role) click to toggle source
# File lib/simple_can.rb, line 77
def capability=(role)
  strategy_set!
  Thread.current[THREAD_VAR] = SimpleCan.strategy.to_capability(role)
end
method_added(method) click to toggle source
# File lib/simple_can.rb, line 42
def method_added(method)
  orig_method_added(method)
  add_method_to(self, method)
end
singleton_method_added(method) click to toggle source
# File lib/simple_can.rb, line 47
def singleton_method_added(method)
  orig_singleton_method_added(method)
  add_method_to((class << self; self; end), method)
end
strategy_set!() click to toggle source
# File lib/simple_can.rb, line 38
def strategy_set!
  SimpleCan.strategy_set!
end
with_capability(role) { || ... } click to toggle source
# File lib/simple_can.rb, line 86
def with_capability(role)
  self.capability = role
  yield
ensure
  self.capability = nil
end