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.
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
19 20 21 22 |
# File 'lib/gamefic/vault.rb', line 19 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).
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.
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 |
#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.
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 |