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.



9
10
11
12
13
# File 'lib/gamefic/vault.rb', line 9

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

Instance Method Details

#add(object) ⇒ Object

Parameters:

  • object (Object)


21
22
23
24
# File 'lib/gamefic/vault.rb', line 21

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

#arrayArray

Returns:



16
17
18
# File 'lib/gamefic/vault.rb', line 16

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).



48
49
50
# File 'lib/gamefic/vault.rb', line 48

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



28
29
30
31
32
33
# File 'lib/gamefic/vault.rb', line 28

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.



41
42
43
44
45
# File 'lib/gamefic/vault.rb', line 41

def lock
  return @lock_index if @lock_index

  @lock_index = @array.length
end