Sort_by different variables?


#1

I have a user control panel that generates an event log by merging
various things that can happen on the site. These are:

user joins
user receives invitation
user completes invitation
user refers someone
user referee activates account

So I want to merge these events into a single array and sort them. It
works well sorting by created_at. However, I do not have unique classes
for all of the events I want to merge (yeah, REST would have worked well
here). So when I populate the array I do this:

  # create array of all events for the log
  @events = []
  @events << @user.invitations
  @events << @user.pending_referrals
  @events << @user.active_referrals
  @events = @events.flatten!.sort_by {|x| x.created_at }.reverse

A pending_referral and active_referral are the same object,but pending
has an activated_at = nil and an active_referral has activated_at =
datetime. So, it is possible to sort this array by created_at OR
activated_at?


#2

2009/2/9 Taylor S. removed_email_address@domain.invalid:

works well sorting by created_at. However, I do not have unique classes
for all of the events I want to merge (yeah, REST would have worked well
here). So when I populate the array I do this:

 # create array of all events for the log
 @events = []
 @events << @user.invitations
 @events << @user.pending_referrals
 @events << @user.active_referrals
 @events = @events.flatten!.sort_by {|x| x.created_at }.reverse

First of all, I believe you want #concat and not #<<:

irb(main):003:0> a = []
=> []
irb(main):004:0> a << [1,2,3]
=> [[1, 2, 3]]
irb(main):005:0> a << [6,7,8]
=> [[1, 2, 3], [6, 7, 8]]
irb(main):006:0> a
=> [[1, 2, 3], [6, 7, 8]]

irb(main):007:0> a = []
=> []
irb(main):008:0> a.concat [1,2,3]
=> [1, 2, 3]
irb(main):009:0> a.concat [6,7,8]
=> [1, 2, 3, 6, 7, 8]
irb(main):010:0> a
=> [1, 2, 3, 6, 7, 8]

A pending_referral and active_referral are the same object,but pending
has an activated_at = nil and an active_referral has activated_at =
datetime. So, it is possible to sort this array by created_at OR
activated_at?

arr.sort_by {|x| x.activated_at || x.created_at}

Kind regards

robert


#3

Thanks a lot, Robert!