rhannequin / astronoby

Ruby library based on astronomy and astrometry books
https://dev.to/rhannequin/series/17782
MIT License
59 stars 2 forks source link

Introduce `Astronoby::Distance` value object #78

Closed rhannequin closed 6 months ago

rhannequin commented 6 months ago

Distances are used in the library here and there. To deal with different units, conversion used to be calculated in the logic itself.

This introduces a new value object for handling distances: Astronoby::Distance.

It can be initialized with meters, kilometers and astronomical units, while the distance is always stored in meters, the international unit for distances.

As a regular value object, it is immutable, handles comparison with other Astronoby::Distance objects, and can be used in some arithmetic operations with the + or - operators.

In the library, all distance notions have been converted to this new value object, with significant breaking changes:

Precision

Because distances are stored in meters, floating points rounding errors are quite likely. For now, I don't think this is a problem. But if we start to see it is one, we'll have to introduce BigDecimal again.

ten_meters = Astronoby::Distance.from_meters(10)
ten_kilometers = Astronoby::Distance.from_kilometers(10)

ten_meters < ten_kilometers
# => true

sum = ten_meters + ten_kilometers
sum.meters
# => 10010

sum.au
# => 6.691271709390715e-08