So, if you are ever somewhere where they ask you to write code on the wall with dry-erase marker, then you are covered.
Me, I never realized how much I love using a keyboard and watching the letters I type appear on the screen. Writing by hand is for suckers and/or poets.
class Mod
def self.ago(seconds)
case true
when seconds.to_i < 60
s = seconds.to_i
return "#{s} second#{s>1 ? "s" : ""} ago."
when seconds.to_i < 3600
m = seconds.to_i/60
s = seconds.to_i%60
return "#{m} minute#{m>1 ? "s" : ""}, #{s} second#{s>1 ? "s" : ""} ago."
when seconds.to_i < (3600 * 24)
h = seconds.to_i/3600
m = (seconds.to_i/60)%60
s = seconds.to_i%60
return "#{h} hour#{h>1 ? "s" : ""}, #{m} minute#{m>1 ? "s" : ""}, #{s} second#{s>1 ? "s" : ""} ago."
else
d = seconds.to_i / (3600 * 24)
h = (seconds.to_i/3600)%24
m = (seconds.to_i/60)%60
s = seconds.to_i%60
return "#{d} day#{d>1 ? "s" : ""}, #{h} hour#{h>1 ? "s" : ""}, #{m} minute#{m>1 ? "s" : ""}, #{s} second#{s>1 ? "s" : ""} ago."
end
end
end
and the tests:
require 'test_helper'
class ModTest < ActiveSupport::TestCase
test "ago function" do
assert_equal "1 second ago.", Mod.ago(1)
assert_equal "40 seconds ago.", Mod.ago(40)
assert_equal "1 minute, 1 second ago.", Mod.ago(61)
assert_equal "3 minutes, 1 second ago.", Mod.ago(181)
assert_equal "2 minutes, 40 seconds ago.", Mod.ago(160)
assert_equal "1 hour, 3 minutes, 1 second ago.", Mod.ago(3600 + 181)
assert_equal "2 hours, 3 minutes, 2 seconds ago.", Mod.ago((3600 * 2)+ 182)
assert_equal "1 day, 0 hour, 1 minute, 1 second ago.", Mod.ago((60*60*24) + 61)
assert_equal "1 day, 3 hours, 1 minute, 1 second ago.", Mod.ago((60*60*24) + 3600 + 3600 + 3600 + 61)
assert_equal "2 days, 3 hours, 0 minute, 6 seconds ago.", Mod.ago(((60*60*24)*2) + 3600 + 3600 + 3600 + 6)
end
end






