Skip to content

Instantly share code, notes, and snippets.

@jeperkins4
Created June 28, 2012 16:59
Show Gist options
  • Save jeperkins4/3012524 to your computer and use it in GitHub Desktop.
Save jeperkins4/3012524 to your computer and use it in GitHub Desktop.
Refactor of InvoiceLedger detailed_invoiced_equipments_by_location
Originally...
def invoiced_equipments_by_location
locations = {}
self.invoiced_equipments.each do |e|
if locations[e.equipment.location].nil?
locations[e.equipment.location] = 1
else
locations[e.equipment.location] = locations[e.equipment.location] + 1
end
end
locations
end
Refactored...
def detailed_invoiced_equipments_by_location
locations = {}
location_hash = self.invoice.invoiceable.locations.index_by(&:id)
equipment_hash = Equipment.where(:location_id => location_hash.keys).index_by(&:id)
self.invoiced_equipments.each do |e|
equipment = equipment_hash[e.equipment_id]
loc = location_hash[equipment.location_id]
if locations[loc].nil?
locations[loc] = [equipment]
else
locations[loc] << equipment
end
end
locations
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment