Sha256: 4448d0264dcd018c10d0f43ab15cf281ce04926466b071d363ccc689bd555b82

Contents?: true

Size: 1.13 KB

Versions: 1

Compression:

Stored size: 1.13 KB

Contents

require 'logger'

module Kan
  module Abilities
    def self.included(base)
      base.extend(ClassMethods)
    end

    module ClassMethods
      DEFAULT_ROLE_NAME = :base
      DEFAULT_ROLE_BLOCK = proc { true }

      def register(*abilities, &block)
        @ability_list ||= {}
        abilities.each { |ability| @ability_list[ability.to_sym] = block }
      end

      def role(role_name, &block)
        @role_name = role_name
        @role_block = block
      end

      def role_name
        @role_name || DEFAULT_ROLE_NAME
      end

      def role_block
        @role_block || DEFAULT_ROLE_BLOCK
      end

      def valid_role?(*args)
        role_block.call(*args)
      end

      def ability_list
        @ability_list || {}
      end
    end

    DEFAULT_ABILITY_BLOCK = proc { true }

    attr_reader :logger

    def initialize(options = {})
      @options = options
      @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) }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
kan-0.2.0 lib/kan/abilities.rb