Class: Qntf::Json::Dataset

Inherits:
Object
  • Object
show all
Defined in:
lib/qntf/storage/json.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, fields = []) ⇒ Dataset

Returns a new instance of Dataset.



19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/qntf/storage/json.rb', line 19

def initialize(name, fields = [])
  @name = name
  @fields = fields
  @data = {}

  @path = File.expand_path("#{name}.json", self.class.source)

  if File.exist?(@path) and !File.zero?(@path)
    load
  else
    bootstrap
  end
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



17
18
19
# File 'lib/qntf/storage/json.rb', line 17

def data
  @data
end

#fieldsObject

Returns the value of attribute fields.



17
18
19
# File 'lib/qntf/storage/json.rb', line 17

def fields
  @fields
end

#nameObject

Returns the value of attribute name.



17
18
19
# File 'lib/qntf/storage/json.rb', line 17

def name
  @name
end

#pathObject

Returns the value of attribute path.



17
18
19
# File 'lib/qntf/storage/json.rb', line 17

def path
  @path
end

Class Method Details

.allObject



8
9
10
11
# File 'lib/qntf/storage/json.rb', line 8

def self.all
  files = Dir.glob(source + '/*.json')
  files.map { |x| new(File.basename(x, '.json')) }
end

.sourceObject



13
14
15
# File 'lib/qntf/storage/json.rb', line 13

def self.source
  ENV['QNTFDIR'] || "#{ENV['HOME']}/.qntf"
end

Instance Method Details

#add_datapoint(datapoint, date = nil) ⇒ Object



38
39
40
41
42
# File 'lib/qntf/storage/json.rb', line 38

def add_datapoint(datapoint, date=nil)
  date ||= Time.now.utc.iso8601(6)
  data[date] = datapoint
  save
end

#add_field(field) ⇒ Object



33
34
35
36
# File 'lib/qntf/storage/json.rb', line 33

def add_field(field)
  @fields << field
  save
end

#loadObject



48
49
50
51
52
# File 'lib/qntf/storage/json.rb', line 48

def load
  data = JSON.parse(File.read(@path))
  @fields = data['fields']
  @data =   data['data']
end

#saveObject



54
55
56
57
58
# File 'lib/qntf/storage/json.rb', line 54

def save
  File.open(@path, 'w') do |file|
    file.puts to_hash.to_json
  end
end

#to_hashObject



44
45
46
# File 'lib/qntf/storage/json.rb', line 44

def to_hash
  {fields: @fields, data: @data}
end