Created
April 7, 2016 03:32
-
-
Save avit/96f07db8a2ed83c436aff0ed61466e3a to your computer and use it in GitHub Desktop.
Getting ruby Date to respect negative offsets when calculating
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
require 'delegate' | |
require 'date' | |
class AnchoredDate < Delegator | |
def initialize year, month=1, day=1 | |
case year | |
when Fixnum | |
@year = year | |
@month = month | |
@day = day | |
@date = Date.new(@year, @month, @day) | |
else | |
@date = year.to_date | |
@year = @date.year | |
@month = @date.month | |
@day = @date.day | |
end | |
end | |
def __getobj__ | |
@date | |
end | |
def + other | |
build_clone @date + other | |
end | |
def - other | |
build_clone @date - other | |
end | |
def >> other | |
build_clone @date >> other, @day | |
end | |
def << other | |
build_clone @date << other, @day | |
end | |
private | |
def build_clone new_date, new_day=nil | |
new_day ||= @day if @day < 0 && same_day?(new_date) | |
self.class.new(new_date.year, new_date.month, new_day || new_date.day) | |
end | |
def same_day? other | |
other.day == Date.new(other.year, other.month, @day).day | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment