require 'rails' module Symphonia module Permissions @@mapper = [] @@used_names = [] mattr_accessor :mapper, :used_names class PermissionMissingError < RuntimeError; end class << self def map(&block) if block_given? yield self end end def register(name, options={}) return if @@used_names.include?(name) p = Permission.new(name, options) @@used_names << p.name.to_s mapper << p p end def update(name) self.get(name) || raise(PermissionMissingError) end # Returns the permission of given name or nil if it wasn't found # Argument should be a symbol def get(name) mapper.detect{|i| i.name == name} end def all mapper end def find_all(permission_names=[]) ps = used_names & Array(permission_names).compact ps.collect{|m| get(m.to_sym)} end end class Permission attr_reader :name # actions => [:controller_name => [:action, :action, :action]] def initialize(name, options={}) @name = name @perms = Hash.new { |hash, key| hash[key] = Array.new } end alias_method :id, :name def to_s @name.to_s end def allowed?(controller, action) Array(@perms[controller.to_sym]).include?(action.to_sym) end def add(controller, actions=[]) @perms[controller] += actions end def remove_actions(controller, actions=[]) @perms[controller] -= actions end def remove_controller(controller) @perms.delete(controller) end def controllers @controllers ||= @perms.keys end def allow_action?(controller, action) controller = controller.to_sym action = action.to_sym if self.controllers.include?(controller) return @perms[controller].include?(action) else return false end end end end end