Capítulo 6 - Active Record Migrations - p. 170 e 171
Tim says . . .
If you’re using a float to store values which need to be precise, such as money, you’re a jackass.
Floating point calculations are done in binary rather than decimal, so rounding errors abound in
places you wouldn’t expect.
>> 0. 1+0. 2 == 0. 3
=> false
>> BigDecimal( ' 0. 1' ) + BigDecimal(' 0. 2' ) == BigDecimal( ' 0. 3' )
=> true
---------------
: float Don’t use floats to store currency values, or more accurately, any type of data
that needs fixed precision. Since floating-point numbers are pretty much approximations, any single representation ofa number as a float is probably okay. However,
once you start doing mathematical operations or comparisons with float values, it is
ridiculously easy to introduce difficult to diagnose bugs into your application.
----------------
página 131
5.4.4 Accessing and Manipulating Attributes Before
They Are Typecast
The Active Record connection adapters, classes that implement behavior specific to
databases, fetch results as strings. Rails then takes care of converting them to other
datatypes if necessary, based on the type of the database column. For instance, integer
types are cast to instances of Ruby’s Fixnum class, and so on.
Even if you’re working with a new instance of an Active Record object, and have
passed in constructor values as strings, they will be typecast to their proper type when
you try to access those values as attributes.
Sometimes you want to be able to read (or manipulate) the raw attribute datawithout
having the column-determined typecast run its course first, and that can be done by using
the attribute_before_type_cast accessors that are automatically created in your
model.
For example, consider the need to deal with currency strings typed in by your
end users. Unless you are encapsulating currency values in a currency class (highly
recommended, by the way) you need to deal with those pesky dollar signs and commas.
Assuming that our Timesheet model had a rate attribute defined as a : decimal type,
the following code would strip out the extraneous characters before typecasting for the
save operation:
class Timesheet < ActiveRecord: : Base
before_validation : fix_rate
def fix_rate
self[: rate] = rate_before_type_cast. tr(' $, ' , ' ' )
end
end
Ótimo livro, vale a pena comprar.....
Abraços,
Everaldo