Class: CustomTracker::Table

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/custom_tracker/table.rb

Overview

A group of entries with similar data.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Table

Creates new table.

Options Hash (options):

  • columns (Array<Symbol>)

    array of column names all the entries which are added to this table are required to store it.

  • saving_block (#call)

    callable object which must accept Array<Entry> - array of entries to save and Table - self.

  • autosave (Integer, nil) — default: nil

    if Integer provided data will be automatically saved if amount of unsaved entries reach specified value.



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/custom_tracker/table.rb', line 41

def initialize(options)
  @columns = options[:columns].select { |s| s.is_a? Symbol }
  @columns.freeze

  @saving_block = options[:saving_block]
  unless @saving_block.respond_to? :call
    raise ArgumentError, "saving_block is not responding to call method!", caller
  end

  @autosave = options[:autosave] ? options[:autosave].to_i : nil

  @size_saved = 0
  @unsaved_entries = []
  @mutex = Mutex.new
end

Instance Attribute Details

#columnsArray<Symbol> (readonly)



28
29
30
# File 'lib/custom_tracker/table.rb', line 28

def columns
  @columns
end

Instance Method Details

#accepts?(entry) ⇒ Boolean



61
62
63
# File 'lib/custom_tracker/table.rb', line 61

def accepts?(entry)
  @columns.all? { |sym| entry.has? sym }
end

#record(entry, options = {}) ⇒ Entry?

Checks whether this entry is acceptable and saves it.

Options Hash (options):

  • instant_save (Boolean)

    if enabled #save will be called after adding.



75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/custom_tracker/table.rb', line 75

def record(entry, options = {})
  entry = Entry.new(entry) if entry.is_a? Hash

  instant_save = !!options[:instant_save]

  if accepts? entry
    @unsaved_entries.push(entry)
    save if instant_save || (@autosave && size_unsaved >= @autosave)
    entry
  else
    nil
  end
end

#saveInteger

Saves all unsaved entries.

Execution of this method is syncronized with Mutex local to current table.



95
96
97
98
99
100
101
102
103
104
# File 'lib/custom_tracker/table.rb', line 95

def save
  @mutex.synchronize do
    @saving_block.call(@unsaved_entries, self)
    re = @unsaved_entries.size
    @size_saved += re
    @unsaved_entries.clear

    re
  end
end

#sizeInteger



10
11
12
# File 'lib/custom_tracker/table.rb', line 10

def size
  size_unsaved + size_saved
end

#size_savedInteger



22
23
24
# File 'lib/custom_tracker/table.rb', line 22

def size_saved
  @size_saved
end

#size_unsavedInteger



16
17
18
# File 'lib/custom_tracker/table.rb', line 16

def size_unsaved
  @unsaved_entries.size
end