Sha256: 74fffb7b2d94cf244cbf40eecaf82cfaed27dc53ce7e4cb4245be54f3e14ea1b
Contents?: true
Size: 1.67 KB
Versions: 2
Compression:
Stored size: 1.67 KB
Contents
module Allowance class Permissions def initialize @permissions = {} yield(self) if block_given? end def allowed?(verb, object = nil) return true if @permissions[[verb, object]] # If object is a resource instance, try its class if object.class.respond_to?(:find) if allowed?(verb, object.class) # See if the object is part of the defined scope return !scoped_model(verb, object.class). find(:first, :conditions => { :id => object.id }).nil? end end false end alias_method :can?, :allowed? def allow!(verbs, objects = nil, scope = true, &blk) expand_permissions(verbs).each do |verb| [objects].flatten.each do |object| @permissions[[verb, object]] = scope # TODO: add blk, too end end end alias_method :can!, :allow! def method_missing(name, *args, &blk) if name.to_s =~ /(.+)!$/ allow!($1.to_sym, *args, &blk) elsif name.to_s =~ /(.+)\?$/ allowed?($1.to_sym, *args, &blk) else super end end def scoped_model(verb, model) if p = @permissions[[verb, model]] case p when Hash, String, Array then model.where(p) when Proc then p.call(model) else model end else model.where(false) end end private def expand_permissions(*permissions) permissions.flatten.map do |p| case p when :manage then [:manage, :index, :show, :new, :create, :edit, :update, :destroy] when :view then [:view, :index, :show] else p end end.flatten end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
allowance-0.1.1 | lib/allowance/permissions.rb |
allowance-0.1.0 | lib/allowance/permissions.rb |