6015f1c7d2c5057f668f4951f3303b28

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?

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 !

A8d3f35baafdaea851914b17dae9e1fc

Adam

January 19, 2010, January 19, 2010 22:14, permalink

No rating. Login to rate!
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
A74c34f1043b833b1fcc86ce9f3521ee

Pavel Gorbokon

January 20, 2010, January 20, 2010 00:46, permalink

1 rating. Login to rate!
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
A74c34f1043b833b1fcc86ce9f3521ee

Pavel Gorbokon

January 20, 2010, January 20, 2010 00:47, permalink

1 rating. Login to rate!

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
6015f1c7d2c5057f668f4951f3303b28

Erik

March 5, 2010, March 05, 2010 13:33, permalink

No rating. Login to rate!

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

Your refactoring





Format Copy from initial code

or Cancel