How do I use dry-validation or dry-schema to remove empty Strings from a HTTP params
Hash entirely? Instead of coercing them to nil
, I would prefer to just omit them entirely, so that the params
Hash is much smaller before sending it to a backend Sidekiq worker.
I think you can use this dry-rb - dry-schema v1.10 - Processor steps
If what you want to do is remove keys with empty values the example is doing exactly that.
I guess I could call .reject { |k,v| v.empty? }
.
schema = Dry::Schema.Params do
required(:name).value(:string)
optional(:age).value(:integer)
before(:value_coercer) do |result|
result.to_h.reject { |k,v| v.empty? }
end
end
schema.call(name: 'Jane', age: '')
# => #<Dry::Schema::Result{:name=>"Jane"} errors={} path=[]>
Is this the ideal way of filtering out empty Strings?
Well, I also dont know if there is a better way, I have used this feature in the past but the experimental
warning on the docs made me leave a TODO on the code to investigate this a bit better.
How would I “DRY” up that before(:value_coercer)
code if I needed to add it to multiple Dry::Schema
s or Dry::Validation:Contract
s? I suppose I could store the block as a constant and pass it in as &BLOCK
. Since the actual schema block is evaluated within a Dry::Schema::DSL
instance, I cannot call include
to include Mixin modules that have self.included
hooks. Would I define a Mixin module
with a self.extended
method and extend the Mixin module
inside the Dry::Schema
?
I dont know the proper way of extracting that.
This really ugly (and probably wrong) monkey patch on Dry::Schema::ProcessorSteps
apparently works but I’m positive it will break other stuff
class Dry::Schema::ProcessorSteps
reject_empty = [proc {|r| r.to_h.reject { |k,v| v.empty? }}]
option :before_steps, default: -> { {value_coercer: reject_empty} }
end
schema = Dry::Schema.Params do
required(:name).value(:string)
optional(:age).value(:integer)
end
p schema.call(name: 'Jane', age: '')
#<Dry::Schema::Result{:name=>"Jane", :age=>""} errors={:age=>["must be an integer"]} path=[]>