It seems that this Google API does not support sorting by name, which means pagination becomes a challenge.
If I was stuck on this, I would probably grab the full contacts list, and persist it in either
(a) a disk file, or
(b) Memcached or Redis, or
(c) a database table.
Of course other issues arise when persisting objects, the main one being defining good parameters for your code to know when to re-sync the list, or to simply throw it away.
If you choose (c), then your sorting and paging can be done the typical ways.
But if you choose (a) or (b), then you can sort at the time you save the list.
Ruby makes it easy to sort an array loaded into memory. If it's a big array, you can even sort it in place to avoid duplicating it. I'm not sure what your response
object looks like, but here is some code assuming it's an array of objects with your name
attribute.
my_objects = response # ...or whatever extracts the array of objects
# Modifies array in place...
my_objects.sort! { |a, b| a.name <=> b.name }
# To sort descending...
my_objects.sort! { |a, b| b.name <=> a.name }
# To sort by zip first (assuming a `zip` attr) then by `name`...
my_objects.sort! { |a, b| 2 * (a.zip <=> b.zip) + (a.name <=> b.name) }
# To sort by zip first (assuming a `zip` attr) then by `name` DESCENDING...
my_objects.sort! { |a, b| 2 * (a.zip <=> b.zip) + (b.name <=> a.name) }
This all works because of the signum or spaceship operator, <=>
. You can learn more about it here:
What is the Ruby <=> (spaceship) operator?
https://en.wikipedia.org/wiki/Sign_function