dry-validation:使用Dry :: Validation.Schema不区分大小写的“ included_in?”验证

时间:2018-11-19 18:18:38

标签: ruby predicate dry-rb

我正在尝试为ETL管道的一部分中的有效品牌的预定列表创建一个验证。我的验证要求不区分大小写,因为某些品牌的复合词或缩写无关紧要。

我创建了一个自定义谓词,但是我不知道如何生成适当的错误消息。

我读了the error messages doc,但是在解释时遇到了困难:

  • 如何为我的自定义谓词构建语法?
  • 是否可以在不引用外部.yml文件的情况下直接在架构类中应用消息?我看着here,似乎并不像我希望的那样简单。

下面,我给出了代表我尝试使用内置谓词和自定义谓词的尝试的代码,每个谓词都有自己的问题。如果有更好的方法来编写可以实现相同目标的规则,我很乐意学习。

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'

1 个答案:

答案 0 :(得分:1)

引用我的错误消息的正确方法是引用谓词方法。无需担心argvalue

en:
  errors:
    in_brand_list?: "must be in the master brands list"

此外,通过执行以下操作,我能够在没有单独的.yml的情况下加载此错误消息:

CaseInsensitiveSchema = Dry::Validation.Schema do
  BRANDS = %w(several hundred valid brands)

  configure do
    def in_brand_list?(value)
      BRANDS.include? value.downcase
    end

    def self.messages
      super.merge({en: {errors: {in_brand_list?: "must be in the master brand list"}}})
    end     
  end

  required(:brand).value(:in_brand_list?)
end

我仍然希望看到其他实现,特别是对于不区分大小写的通用谓词。许多人说dry-rb的组织方式奇妙,但我很难遵循。