Chronic-like in Portuguese

require "rubygems"
require "activesupport"
require "unicode"

class String
  def as_time
    str = self.dup
    str.downcase!
    str.squish!
    str = Unicode.normalize_KD(self).gsub(/[^\x00-\x7F]/n,'')
    
    now = Time.now

    if str == 'hoje'
      Date.today.to_time
    elsif str == 'agora'
      Time.now
    elsif str == 'amanha'
      Date.tomorrow.to_time
    elsif str == 'ontem'
      Date.yesterday.to_time
    elsif str == 'anteontem'
      2.days.ago
    elsif str == 'depois de amanha'
      2.days.from_now
    elsif str =~ /^proxim[oa] (semana|dia|mes|ano)$/
      case $1
        when 'semana' then now.next_week
        when 'dia' then Date.tomorrow.to_time
        when 'mes' then now.next_month
        when 'ano' then now.next_year
      end
    elsif str =~ /^(mes|semana|ano) que vem/
      case $1
        when 'mes' then now.next_month
        when 'semana' then now.next_week
        when 'ano' then now.next_year
      end
    elsif str =~ /^(mes|semana|ano) passad[ao]/
      case $1
        when 'mes' then now.last_month
        when 'semana' then now.beginning_of_week
        when 'ano' then now.last_year
      end
    elsif str =~ /^de (tarde|manha|noite)/
      case $1
        when 'noite' then now.beginning_of_day + 20.hours
        when 'tarde' then now.beginning_of_day + 15.hours
        when 'manha' then now.beginning_of_day + 9.hours
      end
    elsif str =~ /^daqui h?a pouco/
      1.hour.from_now
    elsif str =~ /^daqui(?: h?a)? ([0-9]+) (dias?|mes(?:es)?|semanas?|anos?|horas?|minutos?)/
      num = $1.to_i
      interval = $2.gsub(/e?s$/, '')

      names = {
        'dia' => :day,
        'mes' => :month,
        'semana' => :week,
        'ano' => :year,
        'hora' => :hour,
        'minuto' => :minute
      }
      
      num.send(names[interval]).from_now
    end
  end
end
Displaying 1 Code