Class: Gamefic::Vault

Inherits:
Object
  • Object
show all
Defined in:
lib/gamefic/vault.rb

Overview

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.

Instance Method Summary collapse

Constructor Details

#initializeVault

Returns a new instance of Vault.



7
8
9
10
11
# File 'lib/gamefic/vault.rb', line 7

def initialize
  @set = Set.new
  @array = []
  @lock_index = nil
end

Instance Method Details

#add(object) ⇒ Object

Parameters:

  • object (Object)


19
20
21
22
# File 'lib/gamefic/vault.rb', line 19

def add object
  @array = @set.add(object).to_a
  object
end

#arrayArray

Returns:



14
15
16
# File 'lib/gamefic/vault.rb', line 14

def array
  @array.freeze
end

#deletable?(object) ⇒ Boolean

Returns True if the object is deletable (i.e., not locked).

Returns:

  • (Boolean)

    True if the object is deletable (i.e., not locked).



46
47
48
# File 'lib/gamefic/vault.rb', line 46

def deletable? object
  @lock_index.to_i <= @array.find_index(object).to_i
end

#delete(object) ⇒ Boolean

Returns True if object was deleted.

Parameters:

  • object (Object)

Returns:

  • (Boolean)

    True if object was deleted



26
27
28
29
30
31
# File 'lib/gamefic/vault.rb', line 26

def delete object
  return false unless deletable?(object) && @set.delete?(object)

  @array = @set.to_a.freeze
  true
end

#lockObject

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.



39
40
41
42
43
# File 'lib/gamefic/vault.rb', line 39

def lock
  return @lock_index if @lock_index

  @lock_index = @array.length
end