Reusing schema by switch required to optionsl

I do have these to schema and beside the required and optional they are the same. the reason is when creating this object all of the mare required but to patch the object any given parameter is OK.

 Dry::Validation.Schema do
    required(:name).filled(:str?)
    required(:begin_date).filled(:date?)
    required(:energyprice_cents_per_kilowatt_hour).filled(:float?)
    required(:baseprice_cents_per_month).filled(:int?)
  end

  Dry::Validation.Schema  do
    optional(:name).filled(:str?)
    optional(:begin_date).filled(:date?)
    optional(:energyprice_cents_per_kilowatt_hour).filled(:float?)
    optional(:baseprice_cents_per_month).filled(:int?)
  end

is there a ‘dryer’ way ?

1 Like

I’d like to know an answer to this question too. I’d like to reuse the code between an Update schema and a Create schema but make all the fields in the Update schema optional.

P. S. The best I managed to do so far is this:

class BaseSchema < Dry::Validation::Schema
  module Predicates
    include Dry::Logic::Predicates

    predicate(:name?) do |val|
      str?(val)
    end

    predicate(:code?) do |val|
      str?(val) & min_size?(3, val) & max_size?(10, val)
    end
  end

  configure do
    predicates(Predicates)
  end

  define! do
    required(:name) { name? }
    required(:code) { code? }
  end
end

class UpdateSchema < BaseSchema
  define! do
    optional(:name) { name? }
    optional(:code) { code? }
  end
end