Skip to content

Instantly share code, notes, and snippets.

@bdmac
Created February 1, 2012 02:37
Show Gist options
  • Save bdmac/1714732 to your computer and use it in GitHub Desktop.
Save bdmac/1714732 to your computer and use it in GitHub Desktop.
Heroku memory problem
coordinate_map = Destination.only(:id, :coordinates).all.inject({}) {|h, d| h[d.id.to_s] = d.coordinates.reverse; h}
user_count = User.where(destination_id: nil).count
0.step(user_count, BATCH_SIZE) do |offset|
User.where(destination_id: nil).limit(BATCH_SIZE).skip(offset).each do |user|
next unless user.coordinates.present?
# This used to be a one-liner but broke it up to see if it helped mem-usage
distances = coordinate_map.each_with_object({}) {|(k,v), h| h[k] = user.distance_from(v)}
destination_id = distances.min_by(&:last).first
user.update_attribute(:destination_id, destination_id) rescue nil
distances = nil
destination_id = nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment