Created
July 16, 2021 13:21
-
-
Save coryjamescrook/97c069dbc308ef6d3abbf2a3f291be30 to your computer and use it in GitHub Desktop.
Utility fn for generating a visual representation of time-based models in ruby
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
# outputs something like the following: | |
# | |
# <-------------------------x-------------------------> | |
# |-----------------| | |
# |----------------------------------| | |
# |--------------------| | |
# |------------------------------| | |
# | |
def create_ascii_timeline_for_time_based_models(list) | |
earliest_time = list.sort_by(&:begin).first.begin | |
latest_time = list.sort_by(&:end).last.end | |
hours_range_between_min_and_max = (latest_time - earliest_time) / (60 * 60) | |
minimum_desired_width = 49 | |
maximum_desired_width = 193 | |
# add 1 as padding for middle point of timeline | |
relative_desired_width = (hours_range_between_min_and_max.to_i * 2) + 1 | |
desired_width = [[minimum_desired_width, relative_desired_width].max, maximum_desired_width].min | |
divisor = hours_range_between_min_and_max / desired_width | |
output = "# <" | |
# add 1 to account for the rounding down that happens with to_i | |
half_width = (desired_width / 2).to_i + 1 | |
half_width.times { output << "-" } | |
output << "x" | |
half_width.times { output << "-" } | |
output << ">\n" | |
# the calculated length of the header minus the newline char, plus 4 spaces for padding | |
num_of_chars_to_end_of_range = (output.length - 1) + 6 | |
list.each_with_index do |item, index| | |
append_value = "# " | |
len_in_hours = (item.end - item.begin) / (60 * 60) | |
distance_in_hours_from_min_start = (item.begin - earliest_time) / (60 * 60) | |
spaces_before_start = (distance_in_hours_from_min_start / divisor).to_i | |
spaces_before_start.times { append_value << " " } | |
append_value << "|" | |
(len_in_hours / divisor).to_i.times { append_value << "-" } | |
append_value << "|" | |
num_of_spaces = num_of_chars_to_end_of_range - append_value.length | |
num_of_spaces.times { append_value << " " } | |
id_text = item.id || "item: #{index + 1}" | |
append_value << "<-- #{id_text}" | |
append_value << "\n" | |
output << append_value | |
end | |
puts output | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment