0

I'm trying to validate the value of a key into my schema.

But I'm getting a no implicit conversion of Float into String because the value is a float and I'm using a regex to validate the format.

VALIDATION_PARAMETERS = Dry::Validation.Schema(ApplicationSchema) do
  required(:uid, :string).filled
  required(:value).filled

  rule(insulating_surface: [:uid, :value]) do |uid, value|
    uid.eql?('insulating_surface').then(value.format?(FLOAT_FORMAT))
  end
end

I also tried to convert Float into String but it returns undefined method format?' for #<String:0x0000557d8877a910>

rule(insulating_surface: [:uid, :value]) do |uid, value|
  uid.eql?('insulating_surface').then(value.to_s.format?(FLOAT_FORMAT))
end
Guillaume
  • 1,437
  • 2
  • 15
  • 17
  • Why do you need to validate Float with Regexp? Or let me ask this differently: how could you create a float value in Ruby that does _not_ match the "float pattern"? – Konstantin Strukov May 24 '19 at 12:33
  • @KonstantinStrukov Sometimes the type of `value` can change with `uid` If `uid` is 'insulating_surface', then I must check `value` must be a Float. If `uid` is 'accommodation_type', then I must check `value` is a String with a specific pattern of words – Guillaume May 24 '19 at 12:44
  • Got it. But why regexp? Check the class explicitly (better using built-in predicates). See the answer below - maybe it will help – Konstantin Strukov May 24 '19 at 12:52

1 Answers1

1

I'm not very familiar with dry-validation, but I see a lot of built-in predicates documented, including the float? one. Try the following instead:

rule(insulating_surface: [:uid, :value]) do |uid, value|
  uid.eql?('insulating_surface') > value.float?
end
Konstantin Strukov
  • 2,899
  • 1
  • 10
  • 14
  • 1
    Might also consider `decimal?` as rails has a tendency to use `BigDecimal` over `Float` in a lot of cases. but this is the correct way to validate this and I have used `dry-validation` in multiple projects – engineersmnky May 24 '19 at 16:46
  • @engineersmnky I'm extremely sorry for the late reply. The reason is that we are validating the user's input. We found a solution by preprocessing the data from the controller before using the validation – Guillaume May 27 '19 at 20:41