Module: Mongoid::Geo::Models

Defined in:
lib/mongoid/geo/geo_near.rb

Instance Method Summary collapse

Instance Method Details

#as_criteria(direction = nil) ⇒ Object



51
52
53
54
55
56
57
# File 'lib/mongoid/geo/geo_near.rb', line 51

def as_criteria direction = nil
  to_models(:save) 
  ids = first.klass.all.map(&:_id)
  crit = Mongoid::Criteria.new(first.klass).where(:_id.in => ids, :fromHash => first.fromPoint.hash) 
  crit = crit.send(direction, :distance) if direction
  crit
end

#to_criteriaObject



59
60
61
62
# File 'lib/mongoid/geo/geo_near.rb', line 59

def to_criteria
  ids = map(&:_id)  
  Mongoid::Criteria.new(first.klass).where(:_id.in => ids).desc(:distance)
end

#to_models(mode = nil) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/mongoid/geo/geo_near.rb', line 37

def to_models mode = nil
  distance_hash = Hash[ self.map {|item| [item._id, item.distance] } ]
  from_hash = Hash[ self.map { |item| [item._id, item.fromPoint] } ]

  ret = to_criteria.to_a.map do |m|
    m[:distance] = distance_hash[m._id.to_s]
    m[:fromPoint] = from_hash[m._id.to_s]
    m[:fromHash] = from_hash[m._id.to_s].hash
    m.save if mode == :save
    m
  end
  ret.sort {|a,b| a.distance <=> b.distance}
end