Trailblazer parsing data before validation by :populator

196 views Asked by At

So I have my reform object, and I want to parse my string data before validation, to be able to use dry-validation required(:my_field).filled(gt?: 0)

In order to do that I use populator property :membership_fee, populator: MyPopulator

My question is what is the best way to access and parse data that reform object took.

For now, I used:

property :my_field, populator: lambda { |fragment| fragment[:doc]['my_field'] = BigDecimal.new(fragment[:doc]['my_field']) }

But I am not sure if that is the best way to approach it - I mean accessing it by fragment[:doc] is the prettiest way to do that? I am not sure what exactly fragment[:doc] is used for later in reform.

2

There are 2 answers

2
bigelow42 On BEST ANSWER

I would use dry-validation input pre-processing https://dry-rb.org/gems/dry-validation/input-preprocessing/

configure do
  config.type_specs = true
end

required(:my_field, Types::Params::Integer).filled(gt?: 0)
1
Michal Gilewski On

I think You can just assign decimal value to my_field returning that object, for example:

property :my_field, populator: ->(_fragment:, **) do 
  BigDecimal.new(my_field)
end