DataMapper and BigDecimal – validation

I just spent two hours stuffing around because dm-validations said my BigDecimal wasn’t valid due to it not being a number.

<BigDecimal:2afb413904b0,'0.2857142857 1428571428 5714285714 2857142857 1428571428 5714285714 2857142857 143E1',81(90)>
DataMapper::Validate::ValidationErrors:0x2afb41397670 @errors={:brokerage_percent=>["Brokerage percent must be a number"]}

As you can see it certainly is a number and a BigDecimal. The issue is it doesn’t fit inside the constraints I have specified via scale & precision

property :brokerage_percent, BigDecimal, :scale => 2, :precision => 5

So all you have to do when assigning a value to a BigDecimal property is round it then to string it (maybe you don’t need to ‘to_s’ i can’t be bothered with this anymore…).

irb(main):001:0> require 'bigdecimal'
=> true
irb(main):002:0> sum = BigDecimal.new("20.1121212515151515")
=> #<BigDecimal:2af7589f48c0,'0.2011212125 15151515E2',27(27)>
irb(main):003:0> my_property = BigDecimal.new("#{sum.round(2).to_s}")
=> #<BigDecimal:2af7589e5258,'0.2011E2',18(18)>
irb(main):008:0> my_property.to_s("F")
=> "20.11"

I think that data mapper should handle this sort of thing automatically….

Well after speaking with dkubb – all we really need to do is have a better error message. I’ll create a ticket for that later – want these todo’s done today!

  • http://twitter.com/volkantufekci volkan Tüfekçi

    Thanks a lot. Saved at least 2 hours with your post :)