Class: Functio::DataStorage

Inherits:
Object
  • Object
show all
Defined in:
lib/functio/data_storage.rb

Overview

Manages data storage. DataStorage handles each record data as a Hash, so it expects Hashes when stores data and returns Hashes when retrieves data.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeDataStorage

:nodoc:



33
34
35
36
# File 'lib/functio/data_storage.rb', line 33

def initialize # :nodoc:
  @data_dir = File.join(ENV['HOME'], '.functio')
  @data_file = File.join(data_dir, 'functions.csv')
end

Instance Attribute Details

#data_dirObject (readonly)

Directory path of data file.



28
29
30
# File 'lib/functio/data_storage.rb', line 28

def data_dir
  @data_dir
end

#data_fileObject (readonly)

Path of data file.



31
32
33
# File 'lib/functio/data_storage.rb', line 31

def data_file
  @data_file
end

Instance Method Details

#allObject

Returns all stored records as an Array of Hashes. Each Hash is a record.



58
59
60
# File 'lib/functio/data_storage.rb', line 58

def all
  table.map(&:to_h)
end

#delete(fields) ⇒ Object

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.



65
66
67
68
69
70
71
72
73
74
75
76
# 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) ⇒ Object

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.



52
53
54
55
# 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) ⇒ Object

Stores a record Hash. The keys of record Hash are the field names and the values are the field values.



40
41
42
43
44
45
46
47
# 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