crystal-gauntlet/src/lib/format.cr

94 lines
2.4 KiB
Crystal
Raw Normal View History

2022-12-30 17:04:27 +01:00
module CrystalGauntlet::Format
extend self
2022-12-31 15:04:43 +01:00
TIME_FORMAT = "%Y-%m-%d %H:%M:%S"
2022-12-31 19:44:56 +01:00
# used when sending back to the client as an absolute date
TIME_FORMAT_GD_FRIENDLY = "%d/%m/%Y %H.%M"
# safe to send back in comments
TIME_FORMAT_USER_FRIENDLY = "%d/%m/%Y %H:%M"
2022-12-31 15:04:43 +01:00
def fmt_timespan(s : Time::Span) : String
seconds = s.total_seconds.floor()
minutes = s.total_minutes.floor()
hours = s.total_hours.floor()
days = s.total_days.floor()
months = (s.total_days / 30).floor()
years = (s.total_days / 365).floor()
case
when months >= 17
"#{years.to_i} year#{years == 1 ? "" : "s"}"
when days >= 31
"#{months.to_i} month#{months == 1 ? "" : "s"}"
when hours >= 24
"#{days.to_i} day#{days == 1 ? "" : "s"}"
when minutes >= 60
"#{hours.to_i} hour#{hours == 1 ? "" : "s"}"
when seconds >= 60
"#{minutes.to_i} minute#{minutes == 1 ? "" : "s"}"
else
"#{seconds.to_i} second#{seconds == 1 ? "" : "s"}"
end
end
2023-01-04 10:07:22 +01:00
def fmt_timespan_bit(n : Int, s : String) : String | Nil
if n > 0
2023-01-05 10:17:14 +01:00
return "#{n}#{s}"
2023-01-04 10:07:22 +01:00
end
end
def fmt_timespan_long(s : Time::Span) : String
[
2023-01-05 10:17:14 +01:00
{s.days, "d"},
{s.hours, "h"},
{s.minutes, "m"},
{s.seconds, "s"}
2023-01-04 10:07:22 +01:00
].map { |n, s| fmt_timespan_bit(n.floor().to_i, s) }.compact.join(" ")
end
2022-12-31 19:44:56 +01:00
def fmt_time(s : Time, colon_safe=false) : String
s.to_s(colon_safe ? TIME_FORMAT_USER_FRIENDLY : TIME_FORMAT_GD_FRIENDLY)
end
2022-12-31 20:05:39 +01:00
def fmt_value(v, colon_safe=false, tilda_safe=false, pipe_safe=false) : String
2022-12-30 17:04:27 +01:00
case v
when Bool
v ? "1" : "0"
2022-12-31 15:04:43 +01:00
when Time::Span
2022-12-31 19:44:56 +01:00
fmt_timespan(v)
when Time
if config_get("formatting.date") == "relative"
fmt_timespan(Time.utc - v)
else
fmt_time(v, colon_safe)
end
2023-01-02 13:21:49 +01:00
when Nil
""
2022-12-30 17:04:27 +01:00
else
2022-12-31 20:05:39 +01:00
v = v.to_s
v = Clean.clean_special(v)
if !colon_safe
v = v.gsub(":", "")
end
if !tilda_safe
v = v.gsub("~", "")
end
if !pipe_safe
v = v.gsub("|", "")
end
v
2022-12-30 17:04:27 +01:00
end
end
def fmt_hash(hash) : String
2022-12-31 20:05:39 +01:00
hash.map_with_index{ |(i, v)| "#{i}:#{fmt_value(v, false, true, false)}" }.join(":")
2022-12-30 17:04:27 +01:00
end
2022-12-31 14:25:43 +01:00
def fmt_song(hash) : String
2022-12-31 20:05:39 +01:00
hash.map_with_index{ |(i, v)| "#{i}~|~#{fmt_value(v, true, false, false)}" }.join("~|~")
2022-12-31 14:25:43 +01:00
end
2022-12-31 19:29:51 +01:00
def fmt_comment(hash) : String
2023-01-01 08:06:25 +01:00
hash.map_with_index{ |(i, v)| "#{i}~#{fmt_value(v, false, false, true)}" }.join("~")
2022-12-31 19:29:51 +01:00
end
2022-12-30 17:04:27 +01:00
end