加载ActiveModel定制验证红宝石
问题描述:
我想编写一个自定义验证对于给定的验证电话:加载ActiveModel定制验证红宝石
class Worker
include ActiveModel::Validations
def initialize(graph_object)
@graph_object = graph_object
end
attr_accessor :graph_object
validates :graph_object, graph_object_type: {inclusion: [:ready, :active]}
end
class GraphObject
attr_accessor :state
end
我想根据GraphObject#state
验证Worker#graph_object
。因此Worker
在GrapObject
中的传递位于:ready或:active状态时有效。我想尽可能多地重用ActiveModel。
验证文档介绍了设置自定义验证程序的过程,但我无法弄清楚如何执行此操作。
我想我要开始这样的:
class GraphObjectTypeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
end
end
- 选项[:列入] = [:准备好了,:主动]
- 记录是工人的实例(我想...)
-
value我不知道(是
value = record.graph_object
?) - 属性相同价值 - 不知道
也许validates :graph_object, graph_object_type: {inclusion: [:ready, :active]}
没有定义吧?
答
好的我想我想通了 - 我喜欢把调试!谁需要撬!
这样做的一种方式,它是:
class GraphObjectTypeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if options.key?(:inclusion) && not_included?(value.type)
record.errors.add(attribute, "wrong graph object type")
end
end
private
def not_included?(type)
!options[:inclusion].include?(type)
end
end
-
选项[:包含]:
[:ready, :active]
阵列 -
记录:实例:
Worker
-
价值实例的
GraphObject
-
属性:
:graph_object
符号