我正在尝试为预定的有效品牌列表创建验证,作为 ETL 管道的一部分。我的验证要求不区分大小写,因为某些品牌是无关紧要的复合词或缩写。
我创建了一个自定义谓词,但我不知道如何生成适当的错误消息。
我阅读了错误消息文档,但很难解释:
- 如何为我的自定义谓词构建语法?
- 我可以直接在我的模式类中应用消息,而不引用外部 .yml 文件吗?我看了看这里,它似乎不像我希望的那样简单。
下面我给出的代码代表了我使用内置谓词和自定义谓词尝试过的内容,每个谓词都有自己的问题。如果有更好的方法来编写实现相同目标的规则,我很想学习它。
require 'dry/validation'
CaseSensitiveSchema = Dry::Validation.Schema do
BRANDS = %w(several hundred valid brands)
# :included_in? from https://dry-rb.org/gems/dry-validation/basics/built-in-predicates/
required(:brand).value(included_in?: BRANDS)
end
CaseInsensitiveSchema = Dry::Validation.Schema do
BRANDS = %w(several hundred valid brands)
configure do
def in_brand_list?(value)
BRANDS.include? value.downcase
end
end
required(:brand).value(:in_brand_list?)
end
# A valid string if case insensitive
valid_product = {brand: 'Valid'}
CaseSensitiveSchema.call(valid_product).errors
# => {:brand=>["must be one of: here, are, some, valid, brands"]} # This message will be ridiculous when the full brand list is applied
CaseInsensitiveSchema.call(valid_product).errors
# => {} # Good!
invalid_product = {brand: 'Junk'}
CaseSensitiveSchema.call(invalid_product).errors
# => {:brand=>["must be one of: several, hundred, valid, brands"]} # Good... (Except this error message will contain the entire brand list!!!)
CaseInsensitiveSchema.call(invalid_product).errors
# => Dry::Validation::MissingMessageError: message for in_brand_list? was not found
# => from .. /gems/2.5.0/gems/dry-validation-0.12.2/lib/dry/validation/message_compiler.rb:116:in `visit_predicate'