class Functio::DataStorage
Manages data storage. DataStorage
handles each record data as a Hash, so it expects Hashes when stores data and returns Hashes when retrieves data.
Attributes
data_dir[R]
Directory path of data file.
data_file[R]
Path of data file.
Public Instance Methods
all()
click to toggle source
Returns all stored records as an Array of Hashes. Each Hash is a record.
# File lib/functio/data_storage.rb, line 58 def all table.map(&:to_h) end
delete(fields)
click to toggle source
Deletes a record that matches exactly the fields
passed in. See DataStorage#find
for fields
Hash description. Returns true
if the record matching fields
is deleted successfully or false
otherwise.
# File lib/functio/data_storage.rb, line 65 def delete(fields) tbl = table row_idx = tbl.find_index { |row| row_matches?(row, fields) } return false unless row_idx tbl.delete(row_idx) if tbl.empty? FileUtils.remove_dir(data_dir, true) else File.open(data_file, 'w') { |f| f.write(tbl.to_csv) } end true end
find(fields)
click to toggle source
Finds a record that matches exactly the fields
Hash passed. The keys of fields
Hash are the field names and the values are the field values to match exactly with the record searched for.
# File lib/functio/data_storage.rb, line 52 def find(fields) found = table.find { |row| row_matches?(row, fields) } found.to_h if found end
store(record)
click to toggle source
Stores a record
Hash. The keys of record
Hash are the field names and the values are the field values.
# File lib/functio/data_storage.rb, line 40 def store(record) FileUtils.mkdir_p(data_dir) CSV.open(data_file, 'a') do |csv| csv.seek(0, IO::SEEK_END) csv << record.keys if csv.pos == 0 csv << record.values end end
Private Instance Methods
row_matches?(row, fields)
click to toggle source
# File lib/functio/data_storage.rb, line 86 def row_matches?(row, fields) row.fields(*fields.keys) == fields.values end
table()
click to toggle source
# File lib/functio/data_storage.rb, line 80 def table CSV.table(data_file) rescue SystemCallError CSV::Table.new([]) end