Class: Grubber::Store

Inherits:
Object
  • Object
show all
Defined in:
lib/grubber/store.rb

Constant Summary collapse

DEFAULT_PATH =
"/Users/#{`whoami`.strip}/.grubber"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ Store

Returns a new instance of Store.



11
12
13
14
15
# File 'lib/grubber/store.rb', line 11

def initialize(opts={})
  @path = opts[:path] || DEFAULT_PATH
  
  setup
end

Instance Attribute Details

#contentObject

Returns the value of attribute content.



7
8
9
# File 'lib/grubber/store.rb', line 7

def content
  @content
end

#pathObject

Returns the value of attribute path.



7
8
9
# File 'lib/grubber/store.rb', line 7

def path
  @path
end

Class Method Details

.loadObject



17
18
19
20
21
22
23
24
# File 'lib/grubber/store.rb', line 17

def self.load
  client = new

  data = client.read
  return data unless data.nil?

  client.reset
end

.update(data) ⇒ Object



26
27
28
29
30
31
32
33
# File 'lib/grubber/store.rb', line 26

def self.update(data)
  return unless data.is_a?(Hash)
  
  client = new
  client.content[:grubber].merge!(data)
  client.write
  data
end

Instance Method Details

#base_configObject



69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/grubber/store.rb', line 69

def base_config
  lat, lng      = *Lost.current_position
  current_time  = Time.now.to_i

  { 
    grubber: {
      location: {
        lat: lat,
        lng: lng  
      },
      created_at: current_time
    }
  }
end

#readObject



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/grubber/store.rb', line 41

def read
  begin
    yml = YAML.load_file(path)
  rescue TypeError => e
    return nil
  end
  
  return nil unless yml

  yml
end

#reloadObject



53
54
55
# File 'lib/grubber/store.rb', line 53

def reload
  @content = read
end

#resetObject



61
62
63
64
65
66
67
# File 'lib/grubber/store.rb', line 61

def reset
  File.open(path, 'w') do |f|
    f.write(base_config.to_yaml)
  end

  reload
end

#setupObject



35
36
37
38
39
# File 'lib/grubber/store.rb', line 35

def setup
  return reload if File.exist?(path)

  reset
end

#writeObject



57
58
59
# File 'lib/grubber/store.rb', line 57

def write
  File.open(path, 'w'){|f| f.write(content.to_yaml) }
end