class Polygon::Validator

Validator service for polygon shapes

Could be used to validate if a point is inside a shape

Constants

VERSION

Attributes

shape[R]

Public Class Methods

new(shape) click to toggle source

@param [Polygon::Shape] shape the shape to validate

# File lib/polygon/validator.rb, line 18
def initialize(shape)
  @shape = shape
end

Public Instance Methods

contains_point?(point) click to toggle source

Validate if a point is inside the shape

@param [Polygon::Point] point the point to validate if it is inside the

shape

@return [true, false] true if point is inside the shape

# File lib/polygon/validator.rb, line 27
def contains_point?(point)
  points = shape.points
  winding_number = 0

  points.each.with_index do |point_a, i|
    point_b = point_a == points.last ? points.first : points[i + 1]

    next unless vertically_in_bounds?(point_a, point_b, point)

    winding_number += (left_offset(point_a, point_b, point) <=> 0)
  end

  !winding_number.zero?
end

Private Instance Methods

left_offset(point_a, point_b, point) click to toggle source
# File lib/polygon/validator.rb, line 44
def left_offset(point_a, point_b, point)
  (point_b.x - point_a.x) * (point.y - point_a.y) -
    (point.x - point_a.x) * (point_b.y - point_a.y)
end
vertically_in_bounds?(point_a, point_b, point) click to toggle source
# File lib/polygon/validator.rb, line 49
def vertically_in_bounds?(point_a, point_b, point)
  (point_a.y <= point.y && point_b.y > point.y) ||
    (point_b.y <= point.y && point_a.y > point.y)
end