Skip to content

Instantly share code, notes, and snippets.

@avit
Created April 7, 2016 03:32
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 avit/96f07db8a2ed83c436aff0ed61466e3a to your computer and use it in GitHub Desktop.
Save avit/96f07db8a2ed83c436aff0ed61466e3a to your computer and use it in GitHub Desktop.
Getting ruby Date to respect negative offsets when calculating
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