Class: Gamefic::Vault
- Inherits:
-
Object
- Object
- Gamefic::Vault
- 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
- #add(object) ⇒ Object
- #array ⇒ Array
-
#deletable?(object) ⇒ Boolean
True if the object is deletable (i.e., not locked).
-
#delete(object) ⇒ Boolean
True if object was deleted.
-
#initialize ⇒ Vault
constructor
A new instance of Vault.
-
#lock ⇒ Object
Lock the current elements in the vault.
Constructor Details
#initialize ⇒ Vault
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
21 22 23 24 |
# File 'lib/gamefic/vault.rb', line 21 def add object @array = @set.add(object).to_a object end |
#deletable?(object) ⇒ Boolean
Returns 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.
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 |
#lock ⇒ Object
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 |