class Todo::Support::Date

Constants

AGO
DATE
FORMAT
LAST
MONTHS
MSGS
NUMS
SEP
WDAYS

Attributes

date[R]

Public Class Methods

new(date = ::Date.today) click to toggle source
# File lib/todo/support/date.rb, line 19
def initialize(date = ::Date.today)
  @date = date.is_a?(String) ? Time.parse(date).to_date : date.to_date
end

Public Instance Methods

format(str, opts = {}) click to toggle source
# File lib/todo/support/date.rb, line 23
def format(str, opts = {})
  apply(str.downcase).strftime(opts[:format] || FORMAT)
end

Private Instance Methods

ago(type, num) click to toggle source
# File lib/todo/support/date.rb, line 51
def ago(type, num)
  type, num = :day, num * 7 if type == :week
  1.upto(num).inject(date) { |date, _| date.send(:"prev_#{type}") }
end
apply(str) click to toggle source
# File lib/todo/support/date.rb, line 29
def apply(str)
  if str =~ DATE
    Time.parse(str).to_date
  elsif respond_to?(str, true)
    send(str)
  elsif str =~ AGO
    ago(singularize($2).to_sym, to_number($1))
  elsif str =~ LAST
    last($1)
  else
    fail MSGS[:unknown] % str
  end
end
last(str) click to toggle source
# File lib/todo/support/date.rb, line 56
def last(str)
  str = last_workday if str == 'workday'
  key = str.to_s.downcase[0, 3].to_sym
  last_wday(key) || last_month(key) || fail(MSGS[:unknown] % str)
end
last_month(key) click to toggle source
# File lib/todo/support/date.rb, line 62
def last_month(key)
  return unless num = MONTHS.index(key)
  date = self.date.prev_month
  date = date.prev_month until date.month == num + 1
  date
end
last_wday(key) click to toggle source
# File lib/todo/support/date.rb, line 69
def last_wday(key)
  return unless num = WDAYS.index(key)
  date = self.date.prev_day
  date = date.prev_day until date.wday == num
  date
end
last_workday() click to toggle source
# File lib/todo/support/date.rb, line 93
def last_workday
  num = ::Date.today.wday - 1
  WDAYS[num == -1 ? 5 : num]
end
pluralize(str) click to toggle source
# File lib/todo/support/date.rb, line 85
def pluralize(str)
  "#{str}s".sub(/ss$/, 's')
end
singularize(str) click to toggle source
# File lib/todo/support/date.rb, line 89
def singularize(str)
  str.sub(/s$/, '')
end
to_number(str) click to toggle source
# File lib/todo/support/date.rb, line 80
def to_number(str)
  ix = NUMS.index(str.to_sym)
  ix ? ix + 1 : str.to_i
end
today() click to toggle source
# File lib/todo/support/date.rb, line 43
def today
  date
end
wday_ix(day) click to toggle source
# File lib/todo/support/date.rb, line 76
def wday_ix(day)
  WDAYS.index(day.to_s.downcase[0, 3].to_sym)
end
yesterday() click to toggle source
# File lib/todo/support/date.rb, line 47
def yesterday
  ago(:day, 1)
end