class NoBrainer::GeoSpatial::Polygon

Attributes

coordinates[RW]

Public Class Methods

new(values) click to toggle source
# File lib/nobrainer_geospatial/types/geo_polygon.rb, line 6
def initialize(values)
  # OK, values is either going to be a pair of coords like:
  #    [ [lon1, lat1], [lon2, lat2] ], ...
  #              OR
  #    [point1, point2], ...
  # so we should have either all numeric or an array of arrays...
  raise NoBrainer::Error::InvalidType.new('You must supply at least 4 coordinates') if values.length < 4

  # check to make sure we're not getting invalid parameters or mixed parameters...
  unless values.all? {|c| c.is_a? Numeric} || values.all? {|c| c.is_a? Array}
    raise NoBrainer::Error::InvalidType.new('Points must be an Array or list of numeric')
  end

  self.coordinates = []

  # convert from list of coords to a paired list...
  if values.all? {|c| c.is_a? Numeric}
    raise NoBrainer::Error::InvalidType.new('Must have even number of coordinates!') if values.length.odd?
    values.each_slice(2) do |coords|
      self.coordinates << [coords[0], coords[1]]
    end
  else
    # we already had a paired list... just assign it straight across...
    self.coordinates = values
  end

  check_coordinates(self.coordinates)

end

Private Class Methods

nobrainer_cast_db_to_model(value) click to toggle source

This class method translates a value from the database to the proper type. It is used when reading from the database.

# File lib/nobrainer_geospatial/types/geo_polygon.rb, line 66
def nobrainer_cast_db_to_model(value)
  NoBrainer::GeoSpatial::Polygon.new(*value['coordinates'])
end
nobrainer_cast_model_to_db(value) click to toggle source
# File lib/nobrainer_geospatial/types/geo_polygon.rb, line 60
def nobrainer_cast_model_to_db(value)
  RethinkDB::RQL.new.polygon(*value.coordinates)
end
nobrainer_cast_user_to_model(value) click to toggle source
# File lib/nobrainer_geospatial/types/geo_polygon.rb, line 51
def nobrainer_cast_user_to_model(value)
  case value
    when NoBrainer::GeoSpatial::Polygon then value
    when Array then
      new(value)
    else raise NoBrainer::Error::InvalidType
  end
end

Private Instance Methods

check_coordinates(points) click to toggle source
# File lib/nobrainer_geospatial/types/geo_polygon.rb, line 37
def check_coordinates(points)
  points.each do |point|
    longitude = point[0]
    latitude = point[1]
    if longitude < -180 || longitude > 180
      raise NoBrainer::Error::InvalidType.new('Longitude is out of bounds')
    end
    if latitude < -90 || latitude > 90
      raise NoBrainer::Error::InvalidType.new('Latitude is out of bounds')
    end
  end
end