Class: TickingAway::JSONFileStorage

Inherits:
Object
  • Object
show all
Defined in:
lib/ticking_away/json_file_storage.rb

Overview

Class to store !timeat stats as a JSON file in local storage and return !timepopularity stats for a provided !timeat call

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filename = 'ticking_away_stats.json') ⇒ JSONFileStorage

Returns a new instance of JSONFileStorage.



10
11
12
13
# File 'lib/ticking_away/json_file_storage.rb', line 10

def initialize(filename = 'ticking_away_stats.json')
  @filename = filename
  @stats = read_from_file
end

Instance Attribute Details

#filenameObject (readonly)

Returns the value of attribute filename.



7
8
9
# File 'lib/ticking_away/json_file_storage.rb', line 7

def filename
  @filename
end

#statsObject

Returns the value of attribute stats.



8
9
10
# File 'lib/ticking_away/json_file_storage.rb', line 8

def stats
  @stats
end

Instance Method Details

#full_match?(stat_name, key) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
40
41
# File 'lib/ticking_away/json_file_storage.rb', line 37

def full_match?(stat_name, key)
  return true if key.length == stat_name.length || key[stat_name.length] == '/'

  false
end

#get_stat(stat_name) ⇒ Object

Get the number of times !timeat was called for a tz_info or prefix. Partial prefix matches do not count.



28
29
30
31
32
33
34
35
# File 'lib/ticking_away/json_file_storage.rb', line 28

def get_stat(stat_name)
  call_count = 0
  stats.each do |key, value|
    call_count += value if key.start_with?(stat_name) && full_match?(stat_name, key)
  end

  call_count
end

#increment_stat(stat_name) ⇒ Object

Add 1 to a !timeat <tz_info> stat and save the hash as JSON to a file



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

def increment_stat(stat_name)
  if stats[stat_name]
    stats[stat_name] += 1
  else
    stats.merge!({ stat_name => 1 })
  end
  save_stats
end

#read_fileObject



47
48
49
# File 'lib/ticking_away/json_file_storage.rb', line 47

def read_file
  File.read(filename)
end

#read_from_fileObject

Get saved stats on instantiation or return an empty hash



52
53
54
55
# File 'lib/ticking_away/json_file_storage.rb', line 52

def read_from_file
  return JSON.parse(read_file) if File.file?(filename)
  {}
end

#save_statsObject



43
44
45
# File 'lib/ticking_away/json_file_storage.rb', line 43

def save_stats
  File.write(filename, JSON.dump(stats))
end