Encapsulate the concept of staleness into its own class

Extract it from a single helper method and wrap it in a method object.
This lets us add tests around it and then (later) split the domain
concerns from the view concerns.
This commit is contained in:
Matt Rogers 2013-03-07 22:22:17 -06:00
parent d7e9b384f7
commit ccf5323588
2 changed files with 89 additions and 0 deletions

18
lib/staleness.rb Normal file
View file

@ -0,0 +1,18 @@
require 'active_support/all'
class Staleness
def self.days_stale(item, current_user)
if item.due || item.completed?
return ""
elsif item.created_at < current_user.time - (current_user.prefs.staleness_starts * 3).days
return " stale_l3"
elsif item.created_at < current_user.time - (current_user.prefs.staleness_starts * 2).days
return " stale_l2"
elsif item.created_at < current_user.time - (current_user.prefs.staleness_starts).days
return " stale_l1"
else
return ""
end
end
end

View file

@ -0,0 +1,71 @@
require_relative '../minimal_test_helper'
require_relative '../../lib/staleness'
FakeUser = Struct.new(:time, :prefs)
FakePrefs = Struct.new(:staleness_starts)
FakeTask = Struct.new(:due, :completed, :created_at) do
def completed?
self.completed
end
end
class StalenessTest < Test::Unit::TestCase
def now
@now ||= Time.utc(2013, 2, 28, 0, 0, 0)
end
def day0
@day0 ||= Time.utc(2013, 2, 27, 0, 0, 0)
end
def day24
@day24 ||= Time.utc(2013, 2, 4, 0, 0, 0)
end
def day16
@day16 ||= Time.utc(2013, 2, 12, 0, 0, 0)
end
def day8
@day8 ||= Time.utc(2013, 2, 20, 0, 0, 0)
end
def fake_prefs
@fake_prefs ||= FakePrefs.new(7)
end
def setup
@current_user = FakeUser.new(now, fake_prefs)
end
def test_item_with_due_date_is_not_stale_ever
todo = FakeTask.new(day24, false, now)
assert_equal "", Staleness.days_stale(todo, @current_user)
end
def test_complete_item_is_not_stale
todo = FakeTask.new(day16, true, day24)
assert_equal "", Staleness.days_stale(todo, @current_user)
end
def test_young_item_is_not_stale
todo = FakeTask.new(nil, false, now)
assert_equal "", Staleness.days_stale(todo, @current_user)
end
def test_staleness_level_one
todo = FakeTask.new(nil, false, day8)
assert_equal " stale_l1", Staleness.days_stale(todo, @current_user)
end
def test_staleness_level_two
todo = FakeTask.new(nil, false, day16)
assert_equal " stale_l2", Staleness.days_stale(todo, @current_user)
end
def test_staleness_level_three
todo = FakeTask.new(nil, false, day24)
assert_equal " stale_l3", Staleness.days_stale(todo, @current_user)
end
end