Crystal: Formatting case statement with number literals and ranges can look bad

Created on 11 Jul 2018  路  6Comments  路  Source: crystal-lang/crystal

def to_pretty(t)
  a = (Time.now - t).to_i

  case a
  when               0 then "just now"
  when               1 then "a second ago"
  when 2..59           then a.to_s + " seconds ago"
  when 60..119         then "a minute ago" # 120 = 2 minutes
  when 120..3540       then (a/60).to_i.to_s + " minutes ago"
  when 3541..7100      then "an hour ago" # 3600 = 1 hour
  when 7101..82800     then ((a + 99)/3600).to_i.to_s + " hours ago"
  when 82801..172000   then "a day ago" # 86400 = 1 day
  when 172001..518400  then ((a + 800)/(60*60*24)).to_i.to_s + " days ago"
  when 518400..1036800 then "a week ago"
  else                      ((a + 180000)/(60*60*24*7)).to_i.to_s + " weeks ago"
  end
end

Numeric literals are right aligned while the numeric ranges are left aligned which looks a bit ugly.

Most helpful comment

I can fix this by canceling the right alignment altogether if all when values are not numbers.

All 6 comments

Formatting is an imperfict art ~ but that does look stupid

I prefer if we remove all those aligning rules from the formatter. They are nice but they have these corner cases and probably many more.

@mjago I would appreciate it if you could watch your tone a bit, especially if your contribution to the discussion is short of any value beyond your opinion, which often is more effectively collected through Github's reactions feature.

Let's not throw the baby out with the bathwater, removing the alignment of then would make this code look a lot worse than it is right now.

I can fix this by canceling the right alignment altogether if all when values are not numbers.

The downside of auto alignment on long case blocks is potentially big git diffs, when single line length is changed and the the diff is now multi-line instead of single line.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

chocolateboy picture chocolateboy  路  87Comments

stugol picture stugol  路  70Comments

ezrast picture ezrast  路  84Comments

fridgerator picture fridgerator  路  79Comments

benoist picture benoist  路  59Comments