Sha256: 17aa5c4fa1253f895e0ad8ea28bdd8313dadfa259e9663ac808af41cfe8f1e5d

Contents?: true

Size: 1.81 KB

Versions: 1

Compression:

Stored size: 1.81 KB

Contents

module Allowance
  module Subject
    def permissions
      unless @permissions_defined
        define_permissions
        @permissions_defined = true
      end

      @permissions || {}
    end

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

    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

    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

    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

  private

    def expand_permissions(*perms)
      perms.flatten.map do |p|
        case p
          when :manage then [:manage, :index, :show, :new, :create, :edit, :update, :destroy]
          when :create then [:create, :new]
          when :read   then [:read, :index, :show]
          when :update then [:update, :edit]
          else p
        end
      end.flatten
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
allowance-0.2.0 lib/allowance/subject.rb