[英]Datatype validation in rails ActiveModel::Validations
我想验证 class 属性的数据类型。
我正在 ruby 中编写 API,我需要检查特定参数数据是否为字符串、hash、数组等类型。
例如。 我们有
class ApiValidation
include ActiveModel::Validations
attr_accessor :fieldName
validates :fieldName, :presence => true
end
非常类似于:presence => true
,我想再添加一个验证,例如:datatype =>:string
请建议我一些自定义验证或任何其他方法来满足我的要求。
在 Ruby 中,“数据类型”实际上只是类。 因此,您真正需要做的就是在您的自定义验证中检查哪个 class fieldName
属于( fieldName.class
)。
您可以查看 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.