Sha256: 680c121597f9195a7e0be358617fd0383d9bbaa32d2770ca484fb4edb8b85db7

Contents?: true

Size: 2 KB

Versions: 2

Compression:

Stored size: 2 KB

Contents

module Surrounded
  module Context
    class AccessError < ::StandardError; end
  end
  module AccessControl
    def self.extended(base)
      base.send(:include, AccessMethods)
      Surrounded::Exceptions.define(base, exceptions: :AccessError)
    end
    
    private
    
    def disallow(*names, &block)
      names.map do |name|
        define_access_method(name, &block)
      end
    end
    alias guard disallow
    
    def trigger_return_content(name, *args, &block)
      %{

        method_restrictor = "disallow_#{name}?"
        if self.respond_to?(method_restrictor, true) && self.send(method_restrictor)
          raise ::#{self.to_s}::AccessError.new("access to #{self.name}##{name} is not allowed")
        end

      #{super}
      }
    end
    
    def define_access_method(name, &block)
      mod = Module.new
      mod.class_eval {
        define_method "disallow_#{name}?" do
          begin
            apply_behaviors
            instance_exec(&block)
          ensure
            remove_behaviors
          end
        end
      }
      const_set("SurroundedAccess#{name}", mod)
      include mod
    end
    
    module AccessMethods
      # Return a Set of all defined triggers regardless of any disallow blocks
      def all_triggers
        self.class.triggers
      end
    
      # Return a Set of triggers which may be run according to any restrictions defined
      # in disallow blocks.
      def triggers
        all_triggers.select {|name|
          method_restrictor = "disallow_#{name}?"
          !self.respond_to?(method_restrictor, true) || !self.send(method_restrictor)
        }.to_set
      end

      # Ask if the context will allow access to a trigger given the current players.
      def allow?(name)
        unless self.respond_to?(name)
          raise NoMethodError, %{undefined method `#{name}' for #{self.inspect}}
        end
        if self.respond_to?("disallow_#{name}?")
          !self.public_send("disallow_#{name}?")
        else
          true
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
surrounded-1.0.0 lib/surrounded/access_control.rb
surrounded-0.9.11 lib/surrounded/access_control.rb