【问题标题】:Datatype validation in rails ActiveModel::Validationsrails ActiveModel::Validations 中的数据类型验证
【发布时间】:2020-02-12 21:47:05
【问题描述】:

我想根据数据类型验证类属性。

我正在用 ruby​​ 编写一个 API,我需要检查一个特定的参数数据是否属于 String、hash、Array 等类型。

例如。 我们有

class ApiValidation
  include ActiveModel::Validations
  attr_accessor :fieldName

  validates :fieldName, :presence => true 
end 

与:presence => true 非常相似,我想再添加一个验证,例如:datatype => :string

请建议我一些自定义验证或任何其他方法来满足我的要求。

【问题讨论】:

    标签: ruby-on-rails api validation activerecord activemodel


    【解决方案1】:

    在 Ruby 中,“数据类型”实际上只是类。所以,您真正需要做的就是检查您的custom validation 中的fieldName 属于哪个类(fieldName.class)。

    【讨论】:

      【解决方案2】:

      您可以查看 dry-rb 堆栈。

      https://github.com/dry-rb/dry-types (https://dry-rb.org/gems/dry-types/1.2/) gem 可以满足您的需求。

      来自文档:

      Strict types will raise an error if passed an attribute of the wrong type:

      class User < Dry::Struct
        attribute :name, Types::Strict::String
        attribute :age,  Types::Strict::Integer
      end
      
      User.new(name: 'Bob', age: '18')
      # => Dry::Struct::Error: [User.new] "18" (String) has invalid type for :age
      

      【讨论】:

        【解决方案3】:

        参数总是作为文本接收。 Ruby 没有静态类型,但它有类,因此您的代码需要解析每个属性并将它们转换为您期望的类。

        这可以像使用 Ruby 的内置转换方法一样简单,例如。 to_i、to_sym、to_d、to_h,或者您可能需要添加更多逻辑,例如。 JSON.parse。

        请注意严格和非严格解析之间的区别,这将需要不同的控制流处理。

        >> "1one".to_i
        => 1
        
        >> Integer("1one")
        ArgumentError: invalid value for Integer(): "1one"
        

        【讨论】:

          【解决方案4】:

          根据Rails Guides 和Rails API docs,我们可以使用validates_each 方法,该方法在ActiveModel::Validations 中可用。

          例如:

          class Person
            include ActiveModel::Validations
          
            attr_accessor :first_name, :last_name
          
            validates_each :first_name, :last_name do |record, attr, value|
              record.errors.add attr, " must be a string." unless value.is_a? String
            end
          end
          

          【讨论】:

            猜你喜欢
            • 2016-10-02
            • 1970-01-01
            • 1970-01-01
            • 2011-12-10
            • 2014-03-20
            • 2018-10-06
            • 1970-01-01
            • 2011-06-21
            • 1970-01-01
            相关资源
            最近更新 更多