module FancyDates
(1..12).each do |mo|
t = Time.mktime(1999,mo)
three_letter = t.strftime("%b")
t.instance_eval do
def [](d)
t = Time.mktime(1999,month,d)
t.instance_eval do
def [](y)
Time.mktime(y,month,day)
end
end
t
end
end
const_set(three_letter.to_sym, t)
end
end
Refactorings
No refactoring yet !
Adam
January 19, 2010, January 19, 2010 22:14, permalink
require 'date'
module FancyDate
class Base < Date
def self.new(month, day = 1, year = 1999)
super(year, month, day)
end
end
class Month < Base
def [](day)
Day.new(month, day.to_i)
end
end
class Day < Base
def [](year)
Year.new(month, day, year.to_i)
end
end
class Year < Base
end
Date::ABBR_MONTHNAMES[1..-1].each_with_index do |name,index|
Object.const_set(name, FancyDate::Month.new(index + 1))
end
end
Pavel Gorbokon
January 20, 2010, January 20, 2010 00:46, permalink
require 'date'
FancyDate = Hash.new do |hash, month|
Hash.new do |hash, day|
Hash.new do |hash, year|
Date.new(year, month, day)
end
end
end
Date::ABBR_MONTHNAMES[1..-1].each_with_index do |name,index|
Object.const_set(name, FancyDate[index+1])
end
Pavel Gorbokon
January 20, 2010, January 20, 2010 00:47, permalink
Or if you need cache dates
require 'date'
FancyDate = Hash.new do |hash, month|
hash[month] = Hash.new do |hash, day|
hash[ day ] = Hash.new do |hash, year|
hash[year] = Date.new(year, month, day)
end
end
end
Date::ABBR_MONTHNAMES[1..-1].each_with_index do |name,index|
Object.const_set(name, FancyDate[index+1])
end
Erik
March 5, 2010, March 05, 2010 13:33, permalink
This is an update to Pavel's code that makes it possible to use either the Month[day] syntax or Month[day][year]
FancyDate = Hash.new do |hash, month|
Hash.new do |hash, day|
date = Date.new(1999, month, day)
date.instance_eval do
def [](year)
Date.new(year, month, day)
end
end
date
end
end
Date::ABBR_MONTHNAMES[1..-1].each_with_index do |name,index|
Object.const_set(name, FancyDate[index+1])
end
This is code that lets you define a date by using syntax like Feb[28][2010]. But it seems messy, is there a cleaner way to do this?