Jason
Jason

Reputation: 881

Implement a sort as a class method in Ruby

ActiveRecord gives me a back a set of Users. I want to sort those users by a complex function that uses data not persisted in the User object.

Is there a way to use a scope when the data isn't persisted?

Is there a way to write a sort function as a class method, so I can make a call like:

sorted_users = User.first(20).sorted_my_way

Upvotes: 2

Views: 808

Answers (1)

phoet
phoet

Reputation: 18835

i think it is not possible to do it this way.

it is possible to define class methods and scopes that can be called like User.first(20).sorted_my_way but those can only append stuff to the query you create. if you want to sort within ruby, i think that you need to wrap the whole stuff like:

class User
  self.sorted_my_way(limit)
    first(20).sort_by {...}
  end
end
User.sorted_my_way(20)

another thing that you could do would be to use a block style method:

class User
  self.sorted_my_way
    yield.sort_by {...}
  end
end
User.sorted_my_way { first(20) }

Upvotes: 3

Related Questions