Class: PerfectShape::Point

Inherits:
Shape
  • Object
show all
Includes:
PointLocation
Defined in:
lib/perfect_shape/point.rb

Overview

Point class includes point-specific operations like ‘#==`, `point_distance` and a fuzzy `contain?` matcher

Instance Attribute Summary

Attributes included from PointLocation

#x, #y

Class Method Summary collapse

Instance Method Summary collapse

Methods included from PointLocation

#min_x, #min_y

Methods inherited from Shape

#==, #bounding_box, #center_x, #center_y, #height, #min_x, #min_y, #normalize_point, #width

Constructor Details

#initialize(x_or_point = nil, y_arg = nil, x: nil, y: nil) ⇒ Point

Returns a new instance of Point.



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/perfect_shape/point.rb', line 41

def initialize(x_or_point = nil, y_arg = nil, x: nil, y: nil)
  if x_or_point.is_a?(Array)
    x, y = x_or_point
    super(x: x, y: y)
  elsif x_or_point && y_arg
    super(x: x_or_point, y: y_arg)
  else
    x ||= 0
    y ||= 0
    super(x: x, y: y)
  end
end

Class Method Details

.point_distance(x, y, px, py) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/perfect_shape/point.rb', line 29

def point_distance(x, y, px, py)
  x = BigDecimal(x.to_s)
  y = BigDecimal(y.to_s)
  px = BigDecimal(px.to_s)
  py = BigDecimal(py.to_s)
  BigDecimal(Math.sqrt((px - x)**2 + (py - y)**2).to_s)
end

Instance Method Details

#contain?(x_or_point, y = nil, distance: 0) ⇒ @code true

Checks if points match, with distance tolerance (0 by default)

false if the point is too far.

Parameters:

  • x

    The X coordinate of the point to test.

  • y (defaults to: nil)

    The Y coordinate of the point to test.

  • distance (defaults to: 0)

    The distance from point to tolerate (0 by default)

Returns:

  • (@code true)

    if the point is close enough within distance tolerance,



70
71
72
73
74
75
# File 'lib/perfect_shape/point.rb', line 70

def contain?(x_or_point, y = nil, distance: 0)
  x, y = normalize_point(x_or_point, y)
  return unless x && y
  distance = BigDecimal(distance.to_s)
  point_distance(x, y) <= distance
end

#max_xObject



54
55
56
# File 'lib/perfect_shape/point.rb', line 54

def max_x
  x
end

#max_yObject



58
59
60
# File 'lib/perfect_shape/point.rb', line 58

def max_y
  y
end

#point_distance(x_or_point, y = nil) ⇒ Object



77
78
79
80
81
# File 'lib/perfect_shape/point.rb', line 77

def point_distance(x_or_point, y = nil)
  x, y = normalize_point(x_or_point, y)
  return unless x && y
  Point.point_distance(self.x, self.y, x, y)
end

#to_aObject

Convert to pair Array of x,y coordinates



84
85
86
# File 'lib/perfect_shape/point.rb', line 84

def to_a
  [self.x, self.y]
end