Does anyone have experience with / can anyone suggest best practices for storing quantities with large variants in magnitude?
For example, an attribute in one of my models is used to store a weight that could be anything from a few micrograms up to a kilogram or more. My assumption is to convert everything to the smallest unit and store it in the database as an integer (since I might lose accuracy with a float?), but it seems weird to be storing kilogram quantities in micrograms..
Is anybody able to suggest a ruby/rails plugin that might help with this kind of behavior, in the more generic sense? In the same way that a ‘time’ field in a database is converted into a Time object in ruby, how would I go about best intercepting the database entry -> class attribute process, converting a field into my class of choice?
Is there a design pattern for storing varying unit magnitudes that I’m just not thinking of?
If precision is important, then what you propose is a good idea. Whether with currency or weights, store the integer amount of the smallest unit you can measure.
Alternatively, use
BigDecimal, which provides support for arbitrary precision (as in you-get-to-choose-the-precision, not as in Ruby-randomly-chooses-it). Good support for storing this depends on your database—for example, PostgreSQL provides theNUMERICdata type precisely for this purpose—and requires support from your ORM (presumably ActiveRecord, which supports this in migrations through the:decimalcolumn type).Even though money typically varies by orders of magnitude smaller than the difference between micrograms to kilograms, you will not run into any problems if you handle this like money and just set your precision appropriately.