Skip to content

Instantly share code, notes, and snippets.

@benatkin
Created April 16, 2009 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benatkin/96553 to your computer and use it in GitHub Desktop.
Save benatkin/96553 to your computer and use it in GitHub Desktop.
class Monthly
def initialize(date = Date.today)
@date = date
end
def first
Date.civil(@date.year, @date.month, 1)
end
def last
date = first
date += 1 until date.succ.day == 1
date
end
def first_on_calendar
date = first
date -= 1 until date.wday == 0
date
end
def last_on_calendar
date = last
date += 1 until date.wday == 6
date
end
def calendar_dates
dates = []
first_on_calendar.upto(last_on_calendar) {|d| dates << d}
dates
end
end
require 'timecop'
require 'monthly'
describe Monthly do
describe 'April 2009' do
before do
Timecop.freeze(Date.civil(2009, 4, 16)) do
@monthly = Monthly.new
end
end
it 'should give april 1 for the first day' do
@monthly.first.should == Date.civil(2009, 4, 1)
end
it 'should give april 30 for the last day' do
@monthly.last.should == Date.civil(2009, 4, 30)
end
it 'should give march 29 for the first day on calendar' do
@monthly.first_on_calendar.should == Date.civil(2009, 3, 29)
end
it 'should give may 2 for the last day on calendar' do
@monthly.last_on_calendar.should == Date.civil(2009, 5, 2)
end
it 'should give the correct set of dates' do
dates = %w(
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 1 2
).map {|s| s.to_i}
@monthly.calendar_dates.map {|d| d.day}.should == dates
end
end
describe 'October 2008' do
before do
@monthly = Monthly.new(Date.civil(2008, 10, 20))
end
it 'should give october 1 for the first day' do
@monthly.first.should == Date.civil(2008, 10, 1)
end
it 'should give october 31 for the last day' do
@monthly.last.should == Date.civil(2008, 10, 31)
end
it 'should give september 28 for the first day on calendar' do
@monthly.first_on_calendar.should == Date.civil(2008, 9, 28)
end
it 'should give november 1 for the last day on calendar' do
@monthly.last_on_calendar.should == Date.civil(2008, 11, 1)
end
it 'should give the correct set of dates' do
dates = %w(
28 29 30 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
).map {|s| s.to_i}
@monthly.calendar_dates.map {|d| d.day}.should == dates
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment