Class: Kaizen::Store

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

Constant Summary collapse

DB_DIR =
File.join(Dir.home, '.config', 'kaizen')
DB_PATH =
File.join(DB_DIR, 'improvements.db')
MAX_TEXT =
200

Instance Method Summary collapse

Constructor Details

#initializeStore

Returns a new instance of Store.



15
16
17
18
# File 'lib/kaizen/store.rb', line 15

def initialize
  FileUtils.mkdir_p(DB_DIR)
  @pstore = PStore.new(DB_PATH)
end

Instance Method Details

#add(text) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/kaizen/store.rb', line 20

def add(text)
  raise 'Improvement text is required.' if text.nil? || text.strip.empty?
  raise "Too long. Maximum #{MAX_TEXT} characters." if text.length > MAX_TEXT

  @pstore.transaction do
    entries = @pstore['entries'] || []
    new_id = (entries.map { |e| e[:id] }.max || 0) + 1
    entries << {
      id: new_id,
      text: text.strip,
      date: Date.today.to_s,
      time: Time.now.strftime('%H:%M')
    }
    @pstore['entries'] = entries
    new_id
  end
end

#log(days) ⇒ Object



67
68
69
70
# File 'lib/kaizen/store.rb', line 67

def log(days)
  start_date = Date.today - (days - 1)
  range(start_date, Date.today)
end

#monthObject



62
63
64
65
# File 'lib/kaizen/store.rb', line 62

def month
  start_date = Date.today - 29
  range(start_date, Date.today)
end

#streakObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/kaizen/store.rb', line 72

def streak
  dates = all_entries
          .map { |e| e[:date] }
          .uniq
          .sort
          .reverse

  return 0 if dates.empty?

  today_str = Date.today.to_s
  yesterday_str = (Date.today - 1).to_s
  return 0 unless [today_str, yesterday_str].include?(dates.first)

  count = 1
  (0...dates.length - 1).each do |i|
    break unless (Date.parse(dates[i]) - Date.parse(dates[i + 1])).to_i == 1

    count += 1
  end
  count
end

#todayObject



49
50
51
# File 'lib/kaizen/store.rb', line 49

def today
  by_date(Date.today.to_s)
end

#total_countObject



94
95
96
# File 'lib/kaizen/store.rb', line 94

def total_count
  all_entries.length
end

#total_daysObject



98
99
100
# File 'lib/kaizen/store.rb', line 98

def total_days
  all_entries.map { |e| e[:date] }.uniq.length
end

#undoObject



38
39
40
41
42
43
44
45
46
47
# File 'lib/kaizen/store.rb', line 38

def undo
  @pstore.transaction do
    entries = @pstore['entries'] || []
    raise 'Nothing to undo.' if entries.empty?

    removed = entries.pop
    @pstore['entries'] = entries
    removed
  end
end

#weekObject



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

def week
  start_date = Date.today - 6
  range(start_date, Date.today)
end

#yesterdayObject



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

def yesterday
  by_date((Date.today - 1).to_s)
end