Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/geo_kit/acts_as_mappable.rb

Overview

Extend Array with a sort_by_distance method. This method creates a “distance” attribute on each object, calculates the distance from the passed origin, and finally sorts the array by the resulting distance.

Instance Method Summary collapse

Instance Method Details

#sort_by_distance_from(origin, opts = {}) ⇒ Object



428
429
430
431
432
433
434
435
# File 'lib/geo_kit/acts_as_mappable.rb', line 428

def sort_by_distance_from(origin, opts={})
  distance_attribute_name = opts.delete(:distance_attribute_name) || 'distance'    
  self.each do |e|
    e.class.send(:attr_accessor, distance_attribute_name) if !e.respond_to? "#{distance_attribute_name}="
    e.send("#{distance_attribute_name}=", origin.distance_to(e,opts))
  end
  self.sort!{|a,b|a.send(distance_attribute_name) <=> b.send(distance_attribute_name)}
end