I’ve discovered dry-validation a few days ago and I’m currently trying it out on a project. Now I’ve come to the point where I was thinking about creating schemas dynamically. If I understand correct I can simply create my own schema class with something like:
class Schema < Dry::Validation::Schema::Form
define! do
required(:whatever).value(:str?)
end
end
Let’s say I would like to pass in which fields of my schema are optional since this differs from case to case. Is there any non hacky way to achieve this?
We have a rather sophisticated mechanism for building schemas dynamically by using a formalized rule AST (provided by dry-logic). The DSL is a front-end for building that AST, but if somebody wants to define a schema dynamically I would recommend building an AST and then it’s a matter of passing it to schema builder. Please let me know if this is something you’d like to do, I can provide some examples.
Thanks for you reply. It’s been a while. But yeah if you would have some examples on how to build an AST, I would appreciate it! I love the idea of dry-validation. Thanks for your amazing work guys!
Things changed a lot since 2017 The main idea of using an AST is still the same though but there are now various nitty-gritty details that make it a bit hard to instantiate a schema object manually.
In order to make this easy we’d have to add a public API that would take a list of rules and turn that into a schema object. Right now this is as far as you can go:
Now, having a list of rules is just not enough to instantiate a schema. A schema uses an internal “step processor” that supports before/after hooks and has three main steps that are applied when a schema validates data, one of those steps is “rule applier” and that is what needs the rules produced by the compiler.
Please remember that I am not saying it’s not possible, I’m just saying it requires a bit of a ceremony See what the DSL is doing to get an idea of what I’m talking about.
I’m definitely interested in adding a first-class public API to make this very simple though - please feel free to report an issue and I’ll schedule it for 2.0.0 release.
I am wondering if anything has changed since 2020 on this?
Looking to build dry validations on the fly for user-defined form fields and validations - a scenario where the activerecord validations cannot be used.
What would be the best approach to building validation rules on the fly and running them?