This is my first try on dry-types and I’m really enjoying it!
require 'dry-types' module Types include Dry::Types.module DecimalFromCurrencyReal = Types::Strict::Decimal.constructor do |value| value = value. gsub(/[^\d,]/, ""). # Remove non-numbers and non-commas tr(',','.') # Translate comma into dot BigDecimal.new(value) end end Types::DecimalFromCurrencyReal[" R$ 12.345.678,90 "] # => #<BigDecimal:7fb452589770,'0.123456789E8',18(27)>
For a type that coerces input, should the name be something like that “DecimalFromCurrencyReal”?
Calling BigDecimal.new(value) at the end of the block to coerce the value, is this the right way to do that? Or is there something built-in?
How can I guarantee that the given value is a String so I can call gsub on it without any fear of raising an exeception? I mean, I would like to raise an exception before calling gsub on it.
Any other suggestions?