Class: Habits::Status

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/habits/status.rb

Constant Summary collapse

VALUES =
[:green, :yellow, :red, :missed, :on_hold]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(val) ⇒ Status

Returns a new instance of Status.



15
16
17
18
# File 'lib/habits/status.rb', line 15

def initialize(val)
  raise "Invalid status value" unless VALUES.include?(val)
  @value = val
end

Instance Attribute Details

#valueObject (readonly)

Returns the value of attribute value.



13
14
15
# File 'lib/habits/status.rb', line 13

def value
  @value
end

Class Method Details

.resolve(habit, time = Time.now) ⇒ Object

Resolves the status of a habit. Status starts fresh every week.



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/habits/status.rb', line 26

def self.resolve(habit, time=Time.now)
  return Status.on_hold if habit.status == Status.on_hold
  
  statuses = []
  date = Date.new(time.year, time.month, time.day)
  
  habit.days.each do |day|
    activities = habit.activities_on_week(date.cweek, day)
    day_diff = Habit::DAYS.index(day) - date.wday
    day_diff -= 7 if day_diff > 0
    
    if !activities.empty?
      statuses << Status.green
    else
      dl_date = date + day_diff
      deadline = Time.mktime(dl_date.year, dl_date.month, 
                             dl_date.day, 23, 59)
      
      if Date.new(deadline.year, deadline.month, deadline.day).cweek != date.cweek
        statuses << Status.green
      elsif time > deadline
        statuses << Status.missed
      elsif time > (deadline - habit.red_zone)
        statuses << Status.red
      elsif time > (deadline - habit.yellow_zone)
        statuses << Status.yellow
      else
        statuses << Status.green
      end
    end
  end
  statuses.max
end

Instance Method Details

#<=>(other) ⇒ Object



20
21
22
# File 'lib/habits/status.rb', line 20

def <=>(other)
  VALUES.index(self.value) <=> VALUES.index(other.value)
end