lib/kan/abilities.rb in kan-0.2.0 vs lib/kan/abilities.rb in kan-0.4.0
- old
+ new
@@ -4,22 +4,28 @@
module Abilities
def self.included(base)
base.extend(ClassMethods)
end
+ class InvalidRoleObjectError < StandardError; end
+ class InvalidAbilityNameError < StandardError; end
+
module ClassMethods
DEFAULT_ROLE_NAME = :base
DEFAULT_ROLE_BLOCK = proc { true }
def register(*abilities, &block)
+ abilities.map!(&:to_sym)
+ raise InvalidAbilityNameError if abilities.include?(:roles)
+
@ability_list ||= {}
- abilities.each { |ability| @ability_list[ability.to_sym] = block }
+ abilities.each { |ability| @ability_list[ability] = block }
end
- def role(role_name, &block)
+ def role(role_name, object = nil, &block)
@role_name = role_name
- @role_block = block
+ @role_block = object ? make_callable(object) : block
end
def role_name
@role_name || DEFAULT_ROLE_NAME
end
@@ -33,10 +39,20 @@
end
def ability_list
@ability_list || {}
end
+
+ private
+
+ def make_callable(object)
+ callable_object = object.is_a?(Class) ? object.new : object
+
+ return callable_object if callable_object.respond_to? :call
+
+ raise InvalidRoleObjectError.new "role object #{object} does not support #call method"
+ end
end
DEFAULT_ABILITY_BLOCK = proc { true }
attr_reader :logger
@@ -46,9 +62,9 @@
@logger = @options.fetch(:logger, Logger.new(STDOUT))
end
def ability(name)
rule = self.class.ability_list[name.to_sym] || @options[:default_ability_block] || DEFAULT_ABILITY_BLOCK
- lambda { |*args| instance_exec(args, &rule) }
+ ->(*args) { instance_exec(args, &rule) }
end
end
end