Validating against a partial schema


#1

Same context as: https://github.com/dry-rb/dry-validation/issues/261

So I tried to enable partial validation by adding the method below to Dry::Validation::Schema:

def only(*rules)
  self.class.new(self.class.rules.select { |rule| rules.include?(rule.name) }, options)
end

It seems to work in a simple use case:

[49] pry(main)> schema = Dry::Validation.Schema { required(:name).filled; required(:age).maybe(:int?) }
[50] pry(main)> schema.({}).errors
=> {:name=>["is missing"], :age=>["is missing"]}
[51] pry(main)> schema.only(:name).({}).errors
=> {:name=>["is missing"]}
[52] pry(main)> schema.only(:age).({}).errors
=> {:age=>["is missing"]}
[53] pry(main)> schema.only(:age).(age: '1').errors
=> {:age=>["must be an integer"]}
[54] pry(main)> schema.only(:name).(name: 'foo', age: '1').errors
=> {}

So is this a reasonable implementation to achieve validating against a partial schema…?


#2

Yes, that’s actually pretty sweet. I’ll keep this in mind when working on dry-validation 1.0.0.