ruby-on-railssortingmongoidruby-on-rails-5mongoid5

Rails sort date by upcoming first, then descending


I have a collection of Appointments which have a start_date DateTime field.

I need to sort those appointments so I have

Ie suppose I have

I'm using relative times for the purpose of giving an example, bear in mind in the code I have to compare to Time.now

[ in_two_days, two_days_ago, tomorrow, yesterday]

I would like the sort to return

[ 
  # First upcoming
  tomorrow, 
  in_two_days,
  # Then most recent first
  yesterday, 
  two_days_ago
]

I am using Mongoid, but since there are few items in the arrays, I would accept a solution using array methods and not criteria (although a solution with a mongoid criteria would be better)


Solution

  • upcoming, past = appointments.sort_by(&:start_date).partition{ |a| a.start_date.future? }
    sorted = [*upcoming, *past.reverse]