【发布时间】:2015-02-27 23:14:30
【问题描述】:
如何为这个哈希参数编写正确的params 验证:
{
"files": {
"main.c": {
"contents": "#include <stdio.h> ...",
"foo": "bar"
},
"main.h": {
"contents": "#define BLAH ...",
"foo": "baz"
},
... more files here ...
}
}
files 是我要验证的哈希参数。 files 的每个键都可以是任何东西(字符串);这些值是具有特定格式的哈希值,也需要验证(需要contents 和foo)。我正在使用葡萄 0.9.0。
这就是我想要的:
params do
optional :files, type: Hash do
requires <any key>, type: Hash do
requires :contents, type: String
requires :foo, type: String
end
end
end
我已经阅读了documentation,但我不知道如何实现这种验证。甚至可能吗?我需要编写自定义验证器吗?
另一种方法是改为:
{
"files":
[
{
"name": "main.c",
"contents": "#include <stdio.h> ...",
"foo": "bar"
},
{
"name": "main.h",
"contents": "#define BLAH ...",
"foo": "baz"
}
]
}
可以像这样轻松验证:
params do
optional :files, type: Array do
requires :name, type: String
requires :contents, type: String
requires :foo, type: String
end
end
但现在我失去了拥有唯一文件名的能力。
【问题讨论】:
-
您阅读了哪些文档?你尝试过什么?
-
@vgoff 我读过these docs。我尝试过的唯一代码类似于我的问题中的第一个 ruby 块,但它总是失败(即
requires '*'和requires /.*/,但我知道这些无论如何都行不通)。