Skip to content

Instantly share code, notes, and snippets.

@hanachin
Last active January 22, 2021 10:48
Show Gist options
  • Save hanachin/0a2e12e929af29675fd9c7739c1f1c5a to your computer and use it in GitHub Desktop.
Save hanachin/0a2e12e929af29675fd9c7739c1f1c5a to your computer and use it in GitHub Desktop.
require 'date'
class Calendar
using Module.new {
refine(Date) do
def travel_back = Enumerator.produce(self, &:prev_day)
def travel_forward = Enumerator.produce(self, &:next_day)
def beginning_of_month = Date.new(year, month, 1)
def end_of_month = Date.new(year, month, -1)
end
}
def initialize(date) = @date = date
def to_s = [header, week_header, body].join("\n")
private
# delegation
def month = @date.month
def year = @date.year
def beginning_of_month = @date.beginning_of_month
def end_of_month = @date.end_of_month
# print
def body = weeks.map { week_format % _1.map {|d| d.day if d.month == month } }.join("\n")
def header = "%6d %4d" % [month, year]
def week_header = week_format % weeks.first.map { _1.strftime('%A')[0, 2] }
def week_format = "%-3s" * 7
# dates
def first_sunday = beginning_of_month.travel_back.find { _1.sunday? }
def last_saturday = end_of_month.travel_forward.find { _1.saturday? }
def weeks = dates.each_slice(7)
def dates = first_sunday..last_saturday
end
today = Date.today
beginning_of_month = Date.new(today.year, today.month, 1)
Enumerator.produce(beginning_of_month, &:next_month).take(12).each do
puts Calendar.new(_1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment