Error during Rails multi sort_by when hitting empty date value
Sorry for the newb question, everyone. Here it is:
I have a hash that looks like this:
{ "id" => { :task => [ { :due => Mon Dec 20 00:00:00 UTC 2010, completed: => "2010-12-18T17:29:57Z", :priority => "1", ... } ] , ... } , ... }
To sort this, I use:
tasks = hash.with_indifferent_access
tasks.sort_by { |k,v| [ v['task'][0]['completed'], v['task'][0]['due'], v['task'][0]['priority'] ] }
This works fin开发者_开发技巧e as long as :due has a date value. When it doesn't have a date value, which is permitted, it looks like this:
:due => ""
Then I get a Rails error saying: "comparison of Array with Array failed."
I tried putting in ternary and other logic to default to a distant date if :due is empty, but it seems this isn't possible in the sort_by block.
Any ideas how to lick this one? Many thanks!
Here is an example assuming that "due" is a string and when empty you want it to sort before other tasks with the same completion value. The idea is to convert both valid dates as well as empty strings into the same comparable data type (in this case the integer number of seconds since the epoch). I have intentionally ignored details of your setup that are irrelevant to your question.
# Required for Time.parse
require 'time'
tasks = [
{
completed: "2010-12-18T17:29:57Z",
due: "Mon Dec 20 00:00:00 UTC 2010",
priority: "1"
},{
completed: "2010-12-18T17:29:57Z",
due: "Mon Dec 20 00:00:00 UTC 2010",
priority: "2"
},{
completed: "2010-12-18T17:29:57Z",
due: "",
priority: "1"
},{
completed: "2010-12-17T17:29:57Z",
due: "Mon Dec 20 00:00:00 UTC 2010",
priority: "1"
},{
completed: "2010-12-19T17:29:57Z",
due: "Mon Dec 20 00:00:00 UTC 2010",
priority: "1"
}
]
require 'pp'
pp tasks.sort_by{ |h| [
Time.parse(h[:completed]),
h[:due].empty? ? 0 : Time.parse(h[:due]).to_i,
h[:priority].to_i
]}
#=> [{:completed=>"2010-12-17T17:29:57Z",
#=> :due=>"Mon Dec 20 00:00:00 UTC 2010",
#=> :priority=>"1"},
#=> {:completed=>"2010-12-18T17:29:57Z", :due=>"", :priority=>"1"},
#=> {:completed=>"2010-12-18T17:29:57Z",
#=> :due=>"Mon Dec 20 00:00:00 UTC 2010",
#=> :priority=>"1"},
#=> {:completed=>"2010-12-18T17:29:57Z",
#=> :due=>"Mon Dec 20 00:00:00 UTC 2010",
#=> :priority=>"2"},
#=> {:completed=>"2010-12-19T17:29:57Z",
#=> :due=>"Mon Dec 20 00:00:00 UTC 2010",
#=> :priority=>"1"}]
精彩评论