Created
February 18, 2020 08:24
-
-
Save ReganRyanNZ/1c2af559702e8182503d18eec83b7889 to your computer and use it in GitHub Desktop.
Ruby implementation of Cal (printing calendar)
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
# This was a fun exercise to recreate the bash tool `cal`, which prints a calendar of the current month in your terminal | |
require 'minitest/autorun' | |
require 'date' | |
class Cal | |
def print_calendar(date = Date.today) | |
puts calendar(date) | |
end | |
def calendar(date) | |
[ | |
calendar_title(date), | |
'Su Mo Tu We Th Fr Sa', | |
format_days_of_month(date).each_slice(7).map { |slice| slice.join(' ') }, | |
'' | |
].join("\n") | |
end | |
private | |
def format_days_of_month(date) | |
days_in_month = Date.new(date.year, date.month, -1).day | |
first_day_day_of_week = Date.new(date.year, date.month, 1).wday | |
padding = Array.new(first_day_day_of_week, '') | |
month_with_padding = padding + (1..days_in_month).to_a | |
month_with_padding.map do |day| | |
day.to_s.rjust(2) | |
end | |
end | |
def calendar_title(date) | |
date.strftime("%B %Y").center(20) | |
end | |
end | |
# Running the file will print today's date | |
Cal.new.print_calendar(Date.today) | |
# Running the file will also automatically run the tests | |
class TestCal < Minitest::Test | |
describe '#calendar' do | |
it 'prints April 2020 correctly' do | |
# Test data has hardcoded `\s` instead of spaces because many text editors auto-trim whitespace | |
april_calendar = <<-CALENDAR | |
April 2020\s\s\s\s\s | |
Su Mo Tu We Th Fr Sa | |
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 | |
CALENDAR | |
assert_equal( | |
april_calendar, | |
Cal.new.calendar(Date.parse('2020-04-01')) | |
) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment