module Ohm::Geoindex::ClassMethods

Public Instance Methods

geoindex(coords) click to toggle source
# File lib/ohm/geoindex.rb, line 34
def geoindex(coords)
  @geoindex = coords
end
within(center, radius, withdist: nil, sort: nil, count: nil) click to toggle source
# File lib/ohm/geoindex.rb, line 38
def within(center, radius, withdist: nil, sort: nil, count: nil)
  raise IndexNotFound unless @geoindex
  unless center.is_a?(self.ancestors.first) || (center.is_a?(Array) && center.size == 2)
    raise ArgumentError, "center must be a set of [lng, lat] coordinates or model already in the index." 
  end

  args = center.is_a?(self.ancestors.first) ? ['GEORADIUSBYMEMBER', key[:geoindex], center.id] : ['GEORADIUS', key[:geoindex], *center]
  args << parse_radius(radius)
  args << "withdist" if withdist
  args << sort if sort
  args << ["count", count] if count

  results = redis.call(*(args.flatten))

  # extract ids so we can fetch all at once
  # can be [:id, :id, ...] or [[:id, :dist], [:id, :dist], ...]
  ids = results.map { |r| [*r][0] }
  models = self.ancestors.first.fetch(ids)

  if withdist
    results.each_with_index.map { |r,i| [models[i], r[1].to_f] }
  else
    models
  end
end

Protected Instance Methods

parse_radius(r) click to toggle source
# File lib/ohm/geoindex.rb, line 65
def parse_radius(r)
  r.downcase.strip.scan(/(\d+)\s*(\S+)/).flatten
end