Saturday, October 06, 2007

distance_of_time_in_words in Turkish

In certain websites, you sometimes see notes like 'this comment was added 2 hours ago' .
If you use RoR (Ruby on Rails for the uninitiated), distance_of_time_in_words method in DateHelper accomplishes that.
What if your site is in another language, how do you manage to translate these messages? It's pretty simple actually...
For example for a Turkish implementation, simply append the code below to the end of your
application.rb file.

module ActionView::Helpers::DateHelper
def distance_of_time_in_words(from_time, to_time = 0, include_seconds = false)
from_time = from_time.to_time if from_time.respond_to?(:to_time)
to_time = to_time.to_time if to_time.respond_to?(:to_time)
distance_in_minutes = (((to_time - from_time).abs)/60).round
distance_in_seconds = ((to_time - from_time).abs).round

case distance_in_minutes
when 0..1
return (distance_in_minutes==0) ? 'bir dakika kadar önce' : '1 dakika önce' unless include_seconds
case distance_in_seconds
when 0..5 then '5 saniye kadar önce'
when 6..10 then '10 saniye kadar önce'
when 11..20 then '20 saniye kadar önce'
when 21..40 then 'yarım dakika kadar önce'
when 41..59 then 'bir dakika kadar önce'
else '1 dakika önce'

when 2..45 then "#{distance_in_minutes} dakika önce"
when 46..90 then '1 saat kadar önce'
when 90..1440 then "#{(distance_in_minutes.to_f / 60.0).round} saat kadar önce"
when 1441..2880 then '1 gün önce'
else "#{(distance_in_minutes / 1440).round} gün önce"