[Soks] Rounding error?
Bil Kleb
Bil.Kleb at nasa.gov
Sun Mar 6 14:21:57 EST 2005
> On 3 Mar 2005, at 16:02, Bil Kleb wrote:
>> It has been changed 22 time(s) (roughly once every 0 days).
Tom Counsell wrote:
> True. Design mistake on my part. Was going to make it shift units to
> hours, minutes and seconds, but hadn't got round to that.
FWIW, here's what I ended up hacking in:
# extended the Numeric class in start.rb:
class Numeric
# similar to distance_of_time_in_words as found in
# actionpack-1.1.0/lib/action_view/helpers/date_helper.rb
def to_time_units
seconds = self.round
case seconds
when 0: "fraction of a second"
when 1: "second"
when 2..45: "#{seconds} seconds"
when 46..90: "minute"
when 91..(60*45): "#{(seconds.to_f/60.0).round} minutes"
when (60*45)..(60*90): "hour"
when (60*90)..(60*60*22): "#{(seconds.to_f/60.0/60.0).round} hours"
when (60*60*22)..(60*60*36): "day"
when (60*60*36)..(60*60*24*26): "#{(seconds.to_f/60.0/60.0/24.0).round} days"
when (60*60*24*26)..(60*60*24*45): "month"
when (60*60*24*45)..(60*60*24*30*11): "#{(seconds.to_f/60.0/60.0/24.0/30.0).round} months"
when (60*60*24*30*11)..(60*60*24*500): "year"
else "#{(seconds.to_f/60.0/60.0/24.0/365.0).round} years"
end
end
end
Note: I originally tried to stick the above directly in
@view/Page_meta.rhtml@ but I ran into syntax errors and
quickly abandoned the attempt because I don't fully
grok ERB yet.
# changed the relevant portion of @view/Page_meta.rhtml@ to
<% seconds_per_change = (Time.now-page.created_on)/page.revisions.size.to_i %>
<p>
It has been changed
<%= page.revisions.size %> time<%= page.revisions.size == 1 ? '' : 's' %>
(roughly once every <%= seconds_per_change.to_time_units %>).
</p>
Regards,
--
Bil Kleb
http://fun3d.larc.nasa.gov
Of course, the above Numeric extension was developed test-first:
require 'test/unit'
class ToTimeUnitsMT < Test::Unit::TestCase
def test_seconds
assert_equal( 'fraction of a second', 0.4.to_time_units )
assert_equal( 'second', 0.8.to_time_units )
assert_equal( 'second', 1.3.to_time_units )
assert_equal( '5 seconds', 5.to_time_units )
end
def test_minutes
assert_equal( 'minute', 46.to_time_units )
assert_equal( '10 minutes', (60*10.4).to_time_units )
end
def test_hours
assert_equal( 'hour', (60*60*1.2).to_time_units )
assert_equal( '2 hours', (60*60*1.8).to_time_units )
end
def test_days
assert_equal( 'day', (60*60*24*0.95).to_time_units )
assert_equal( '20 days', (60*60*24*20).to_time_units )
end
def test_months
assert_equal( 'month', (60*60*24*30*1.1).to_time_units )
assert_equal( '10 months', (60*60*24*30*10).to_time_units )
end
def test_years
assert_equal( 'year', (60*60*24*30*14).to_time_units )
assert_equal( '11 years', (60*60*24*365*11).to_time_units )
end
end
[Numeric extension was here]
More information about the Soks-discuss
mailing list