Sha256: 0724971c158279d9c73c68b2b57cd0fc6cfd97470d1ef4a98cbba437db7d69e5

Contents?: true

Size: 1.28 KB

Versions: 2

Compression:

Stored size: 1.28 KB

Contents

module Gamefic
  # An array wrapper that exposes a protected interface. The array is always
  # returned frozen. It can only be modified through #add and #delete. The
  # vault can be "locked" to prevent existing elements from being deleted.
  #
  class Vault
    def initialize
      @set = Set.new
      @array = []
      @lock_index = nil
    end

    # @return [Array]
    def array
      @array.freeze
    end

    # @param object [Object]
    def add object
      @array = @set.add(object).to_a
      object
    end

    # @param object [Object]
    # @return [Boolean] True if object was deleted
    def delete object
      return false unless deletable?(object) && @set.delete?(object)

      @array = @set.to_a.freeze
      true
    end

    # Lock the current elements in the vault.
    #
    # After the vault is locked, calling #delete on a locked element will leave
    # the element in the array and return false. Elements added after the lock
    # can be deleted.
    #
    def lock
      return @lock_index if @lock_index

      @lock_index = @array.length
    end

    # @return [Boolean] True if the object is deletable (i.e., not locked).
    def deletable? object
      @lock_index.to_i <= @array.find_index(object).to_i
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
gamefic-3.1.0 lib/gamefic/vault.rb
gamefic-3.0.0 lib/gamefic/vault.rb