Created
March 30, 2010 18:27
-
-
Save babelian/349400 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Date | |
#hard coded to GB holidays if Holidays gem is installed. | |
def advance_working_days(working_dates_required) | |
return self if working_dates_required == 0 | |
if Gem.available?('holidays') | |
require 'holidays' | |
require 'holidays/gb' | |
end | |
new_date = self.dup | |
direction = working_dates_required > 0 ? 1 : -1 | |
working_dates_stepped = 0 | |
until working_dates_required == working_dates_stepped | |
#you probably never want to advance more than 100 working days etc, so this is a sign somethings up. | |
raise "looping on #{self.inspect} #{working_dates_required}" if(self-new_date).abs > 100 | |
#step a day | |
new_date += direction | |
#determine if new day is a weekend/holiday | |
weekend = [0,6].include?(new_date.wday) | |
holiday = defined?(Holidays) ? Holidays.on(new_date, :gb).not_blank? : false | |
#consider it a working step if its not | |
working_dates_stepped += direction unless (weekend || holiday) | |
end | |
new_date | |
end | |
end | |
describe Date do | |
describe "#advance_working_days" do | |
context "skips weekends" do | |
# pop over the weekend | |
it "Fri, 19 Mar 2010 + 1 working days -> Mon, 22 Mar 2010" do | |
Date.parse('2010-03-19').advance_working_days(1).should == Date.parse('2010-03-22') | |
end | |
# two weeks | |
it "Fri, 19 Mar 2010 + 6 working days -> Mon, 29 Dec 2010" do | |
Date.parse('2010-03-19').advance_working_days(6).should == Date.parse('2010-03-29') | |
end | |
end | |
context "holidays" do | |
# skip christmas eve, christmas, boxing day | |
it "Thu, 23 Dec 2010 + 3 working days -> Tue, 28 Dec 2010" do | |
Date.parse('2010-12-23').advance_working_days(3).should == Date.parse('2010-12-28') | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment