Ensure entities are sortable before sorting

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the dumb-mistakes-and-gotchas category.

Last Updated: 2024-11-21

The files on a product page were displayed in a bogus order. The order was insane, with 2012 appearing before 2008 and 2011 appearing after.

The sort code was:

@notes_files.
  group_by(&:author).
  sort_by {|group| group[1].max_by(&:created_at) }.
  each.with_index do |notes_file_author_file_group, index|
     ...
  end

The issue was that each group[1].max_by(&:created_at) returned a NotesFile instance, instead of a date (as I expected), and NotesFile - a complex database-backed object - are very odd sort keys indeed. Therefore I got a bogus sort.

The fix was to do group[1].map(&:created_at).max and ensure I was sorting on actual timestamps. (Actually, as I will talk about in another diary entry, it would have been better to do all the sorting in the DB instead using an order clause).

Lessons

When doing a sort, ensure the entity is properly comparable. Ruby will try to sort ANYTHING and not complain (instead just quietly give bogus results)