Ruby/Time/Time Extension

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Add day ordinal suffix to Time

class Time
  def day_ordinal_suffix
    if day == 11 or day == 12
      return "th"
    else
      case day % 10
      when 1 then return "st"
      when 2 then return "nd"
      when 3 then return "rd"
      else return "th"
      end
    end
  end
end
time = Time.local(2008, 8, 31, 2, 3, 4, 5)
time.strftime("The %e#{time.day_ordinal_suffix} of %B") # => "The 31st of December"



Add step method to Time

class Time
  def step(other_time, increment)
   raise ArgumentError, "step can"t be 0" if increment == 0
    increasing = self < other_time
    if (increasing && increment < 0) || (!increasing && increment > 0)
      yield self
      return
    end
    d = self
    begin
      yield d
      d += increment
    end while (increasing ? d <= other_time : d >= other_time)
  end
  def upto(other_time)
    step(other_time, 1) { |x| yield x }
  end
end
the_first = Time.local(2004, 1, 1)
the_second = Time.local(2004, 1, 2)
the_first.step(the_second, 60 * 60 * 6) { |x| puts x }
the_first.upto(the_first) { |x| puts x }



Validate a date

class Time
  def Time.validate(year, month=1, day=1,
                    hour=0, min=0, sec=0, usec=0)
    require "date"
    begin
      d = Date.new(year,month,day)
    rescue
      return nil
    end
    Time.local(year,month,day,hour,min,sec,usec)
  end
end
t1 = Time.validate(2000,11,30)  # Instantiates a valid object
t2 = Time.validate(2000,11,31)  # Returns nil