Class: CosSinCalc::Triangle::Validator

Inherits:
Object
  • Object
show all
Defined in:
lib/cossincalc/triangle/validator.rb

Defined Under Namespace

Classes: ValidationError

Constant Summary collapse

NOT_ENOUGH_VARIABLES =
'3 values must be specified.'
TOO_MANY_VARIABLES =
'Only 3 values should be specified.'
NO_SIDES =
'At least one side must be given.'
INVALID_SIDE =
'Only numbers (above zero) are accepted values for a side.'
INVALID_ANGLE =
'Only numbers (above zero) are accepted values for an angle. Furthermore the angle must remain inside the scope of the sum of all angles in the triangle.'
INVALID_TRIANGLE =
'The specified values do not match a valid triangle.'
CALCULATOR_PRECISION =
0.01

Instance Method Summary collapse

Constructor Details

#initialize(triangle) ⇒ Validator

Returns a new instance of Validator.



20
21
22
# File 'lib/cossincalc/triangle/validator.rb', line 20

def initialize(triangle)
  @triangle = triangle
end

Instance Method Details

#validateObject

Validates the triangle before calculation and raises an exception on errors.



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/cossincalc/triangle/validator.rb', line 25

def validate
  @sides_valid, @angles_valid = {}, {}
  
  t.each do |v|
    @sides_valid[v]  = t.side(v).nil?  || valid_side?(t.side(v))
    @angles_valid[v] = t.angle(v).nil? || valid_angle?(t.angle(v))
  end
  
  errors = error_messages
  errors.empty? || (raise ValidationError.new(errors, @sides_valid, @angles_valid))
end

#validate_calculationObject

Checks whether the calculation was successful and the values given/calculated match a triangle.



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/cossincalc/triangle/validator.rb', line 38

def validate_calculation
  t.each do |v, r|
    raise ValidtionError.new([INVALID_TRIANGLE]) unless valid_side?(t.side(v)) && valid_angle?(t.angle(v))
    
    angle = t.calculate_angle_by_sides(v, r)
    unless angle > t.angle(v) - CALCULATOR_PRECISION && angle < t.angle(v) + CALCULATOR_PRECISION
      raise ValidtionError.new([INVALID_TRIANGLE])
    end
  end
  return true
end