Sha256: 28564d7f98177c0403a737746411f6fe37a0803b9ee251299c5ccfcd99c9f6b8

Contents?: true

Size: 1.28 KB

Versions: 2

Compression:

Stored size: 1.28 KB

Contents

module Abilities
  class Definitions

    attr_reader :user

    def initialize(user, &block)
      @user = user
      Proxy.new self, &block
    end

    def can?(action, resource)
      id = resource_id(resource)
      if id != :any && can?(action, :any)
        true
      elsif actions = registry[id]
        if policy = (actions[action] || actions[:manage])
          if policy.is_a?(Proc)
            user.instance_exec resource, &policy
          else
            policy
          end
        else
          false
        end
      else
        false
      end
    end

    def cannot?(*args)
      !can?(*args)
    end

    def add(actions, resources, policy)
      unless actions.is_a?(Array)
        actions = [actions]
      end
      unless resources.is_a?(Array)
        resources = [resources]
      end
      resources.each do |resource|
        actions.each do |action|
          id = resource_id(resource)
          registry[id] ||= {}
          registry[id][action] = policy
        end
      end
    end

    private

    def registry
      @registry ||= {}
    end

    def resource_id(resource)
      case resource
      when :any
        resource
      when Class
        resource.name.underscore.to_sym
      else
        resource.class.name.underscore.to_sym
      end
    end

  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
abilities-4.0.0.1 lib/abilities/definitions.rb
abilities-4.0.0.0 lib/abilities/definitions.rb