Class: JSONFilePersistedCollection

Inherits:
Object
  • Object
show all
Defined in:
lib/util/json_file_persisted_collection.rb

Overview

Collection of items that are automatically persisted to a JSON file

Instance Method Summary collapse

Constructor Details

#initialize(file) ⇒ JSONFilePersistedCollection

Creates a new JSONFilePersistedCollection



10
11
12
# File 'lib/util/json_file_persisted_collection.rb', line 10

def initialize( file )
  @store = JSONStore.new(file, true)
end

Instance Method Details

#delete(item) ⇒ Hash

Deletes the first element from this persisted collection that is equal to item



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/util/json_file_persisted_collection.rb', line 32

def delete( item )
  r = nil
  @store.transaction do
    if @store['collection'].nil?
      r = {}
      @store.abort
    end
    r = @store['collection'].delete_at(@store['collection'].index(item) || @store['collection'].length)
    r = {} if r.nil?
  end
  r
end

#lengthFixnum

Returns the length of the collection



67
68
69
# File 'lib/util/json_file_persisted_collection.rb', line 67

def length
  @store.transaction { @store['collection'].nil? ? 0 : @store['collection'].length }
end

#push(item) ⇒ JSONFilePersistedCollection

Pushes (appends) the given hash on to the end of this persisted collection



19
20
21
22
23
24
25
# File 'lib/util/json_file_persisted_collection.rb', line 19

def push( item )
  @store.transaction do
    @store['collection'] = Array.new if @store['collection'].nil?
    @store['collection'].push(item)
  end
  self
end

#replace(item, replacement) ⇒ Hahs

Replaces the first element from this persisted array that matches item, with replacement



50
51
52
53
54
# File 'lib/util/json_file_persisted_collection.rb', line 50

def replace( item, replacement )
  r = delete item
  push replacement
  r
end

#to_aArray<Hash>

Returns an array representation of this collection



60
61
62
# File 'lib/util/json_file_persisted_collection.rb', line 60

def to_a
  @store.transaction { @store['collection'].nil? ? {} : @store['collection'] }
end