Define a Hash param that also accepts a String that is validates *then* parsed

I’m wondering how one would define a Hash param (ex: for HTTP headers) that accepts a String, which is first validated using a Regex, then parsed into a Hash. I know about dry-types .constructor and dry-validations’s before(:key_coercer), but am unclear how to insert a validation rule specifically for String values, before the coercion from String to Hash.

I did something vaguely similar to this for XML, maybe this will help

module Types
  XML = String.constrained(format: %r{^<\?xml}).constructor do |input, type|
    if input.is_a?(Nokogiri::XML::Document)
      input
    elsif type.valid?(input)
      Nokogiri.parse(input)
    else
      type.(input)
    end
  end
end
1 Like