Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code demonstrating issue to setup validations involving referenced object attributes
require 'dry-validation'
class Type
attr_reader :name
def initialize(name)
@name = name
end
Schema = Dry::Validation.Schema do
key(:name).required
end
end
class Entity
attr_reader :name, :type, :number
def initialize(name, number, type)
@name = name
@number = number
@type = type
end
def valid?
Schema.call({ name: name, number: number, type: type }).message.empty?
end
Schema = Dry::Validation.Schema do
key(:name).required
key(:type).schema(Type::Schema)
rule(number_format: [[:type, :name], :number]) do |type_name, number|
type_name.eql?('CODEP').then(number.format?(/^D\d{3}$/))
end
end
end
entity = Entity.new('foo', 'AbCD', { name: 'CODEP' })
entity.valid?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.