lib/mongoid/geospatial/fields/point.rb in mongoid-geospatial-4.0.1 vs lib/mongoid/geospatial/fields/point.rb in mongoid-geospatial-5.0.0

- old
+ new

@@ -2,14 +2,16 @@ module Geospatial # Point # class Point include Enumerable - attr_reader :x, :y + attr_accessor :x, :y, :z def initialize(x, y, z = nil) - @x, @y, @z = x, y, z + @x = x + @y = y + @z = z end # Object -> Database # Let's store NilClass if we are invalid. # @@ -27,49 +29,76 @@ def each yield x yield y end + # # Point representation as a Hash # - # @return (Hash) + # @return [Hash] with { xl => x, yl => y } + # def to_hsh(xl = :x, yl = :y) { xl => x, yl => y } end alias_method :to_hash, :to_hsh + # # Helper for [self, radius] + # + # @return [Array] with [self, radius] + # def radius(r = 1) [mongoize, r] end - # Helper for [self, radius / earth radius] + # + # Radius Sphere + # + # Validates that #x & #y are `Numeric` + # + # @return [Array] with [self, radius / earth radius] + # def radius_sphere(r = 1, unit = :km) radius r.to_f / Mongoid::Geospatial.earth_radius[unit] end # # Am I valid? # - # Validates that x & y are `Numeric` + # Validates that #x & #y are `Numeric` # + # @return [Boolean] if self #x && #y are valid + # def valid? x && y && x.is_a?(Numeric) && y.is_a?(Numeric) end # # Point definition as string # # "x, y" # # @return [String] Point as comma separated String + # def to_s "#{x}, #{y}" end # + # Point inverse/reverse + # + # MongoDB: "x, y" + # Reverse: "y, x" + # + # @return [Array] Point reversed: "y, x" + # + def reverse + [y, x] + end + + # # Distance calculation methods. Thinking about not using it # One needs to choose and external lib. GeoRuby or RGeo # # Return the distance between the 2D points (ie taking care # only of the x and y coordinates), assuming the points are @@ -98,11 +127,11 @@ class << self # # Database -> Object # Get it back def demongoize(obj) - obj && Point.new(*obj) + obj && new(*obj) end # # Object -> Database # Send it to MongoDB @@ -120,11 +149,14 @@ end # Converts the object that was supplied to a criteria # into a database friendly form. def evolve(obj) - obj.respond_to?(:x) ? obj.mongoize : obj + case obj + when Point then obj.mongoize + else obj + end end private # @@ -149,12 +181,12 @@ # [] -> [] # [1,2] -> [1.0, 2.0] # # @return (Array) # - def from_array(ary) - return nil if ary.empty? - ary.flatten[0..1].map(&:to_f) + def from_array(array) + return nil if array.empty? + array.flatten[0..1].map(&:to_f) end # # Sanitize a `Point` from a `Hash` #