Is it possible to embedd another validation schema in a new one? (**not** nest)


#1

Let’s say if I have this schema:

      Schema = Dry::Validation.Params do
        required(:company_id).filled(:int?)
        required(:names).filled(:array?)
        optional(:company_branch_id).maybe(:int?)
      end

Can I embed it into another schema that contains high levels rules?
The result of this embedding would create a schema like this:

      NewSchema = Dry::Validation.Params do
        required(:company_id).filled(:int?)
        required(:names).filled(:array?)
        optional(:company_branch_id).maybe(:int?)
        validate(..) do 
        end
        rule(...) do 
        end
      end

I could imagine it working something like this:

      NewSchema = Dry::Validation.Params do
        schema(Schema)
        validate(..) do 
        end
        rule(...) do 
        end
      end

I know solniss mentioned that it will be easily possible in the new 1.0 dry-validation/dry-schema, but is there a way to do it now?


#2

Hey,

When you say embed I thought that you where referring to https://dry-rb.org/gems/dry-validation/reusing-schemas/

But I think you need a base schema like:

class AppSchema < Dry::Validation::Schema
  configure do |config|
    config.messages_file = '/my/app/config/locales/en.yml'
    config.messages = :i18n
  end

  def email?(value)
    true
  end

  define! do
    # define common rules, if any
  end
end

# now you can build other schemas on top of the base one:
Dry::Validation.Schema(AppSchema) do
  # define your rules
end

More on the topic here https://dry-rb.org/gems/dry-validation/basics/working-with-schemas/