ruby-on-rails - 如何从 ruby 哈希构建 GQL?
问题描述
我正在构建一个 rspec 助手来测试我的 graphql 请求。
到目前为止,这是我的帮手:
def mutation_params(name, attributes:, return_types:)
{
query:
<<~GQL
mutation {
#{name}(
input: { attributes: #{attributes} })
#{return_types}
}
GQL
}
end
我必须这样声明attributes
:
let(:attributes) do
<<~GQL
{
email: "#{email_param}",
password: "#{password_param}"
}
GQL
end
现在我想知道我能做些什么才能简单地将 myarguments
作为哈希传递,并让该mutations_params
方法通过迭代它们来从该哈希构建 GQL。
let(:attributes) do
{
email: email_param,
password: password_param
}
end
就像是:
def mutation_params(name, attributes:, return_types)
gql_attributes = <<~GQL
{
}
GQL
attributes.each do |key, value|
gql_attributes merge with
<<~GQL
"#{key}": "#{value}"
GQL
end
{
query:
<<~GQL
mutation {
#{name}(
input: { attributes: #{gql_attributes} })
#{return_types}
}
GQL
}
end
但这显然行不通。我认为我的问题是我真的不明白那<<~GQL
是什么以及如何操纵它。
解决方案
您正在寻找 Ruby 2.3 中引入的波浪形heredoc。它就像一个普通的heredoc,但它没有前导缩进。https://ruby-doc.org/core-2.5.0/doc/syntax/literals_rdoc.html
所以换句话说,它只是一个字符串!GQL 位是任意的,但却是传达heredoc 目的的好方法。
你可以编写一个这样的助手来将哈希转换为 GraphQL 字符串
def hash_to_mutation(hash)
attr_gql_str = attributes.map{|k,v| "#{k}: #{v.inspect}"}.join(", ")
" { #{attr_gql_str} } "
end
然后假设属性是您的示例中的哈希值,您可以
def mutation_params(name, attributes:, return_types:)
{
query:
<<~GQL
mutation {
#{name}(
input: { attributes: #{hash_to_gql(attributes)} })
#{return_types}
}
GQL
}
end
推荐阅读
- kotlin - Testing Kotlin Flow.combine with unending flows
- git - Git svn 目录 .git/logs/refs/... 和 .git/refs/ 之间的区别
- type-conversion - 在datastage中将datastage时间戳转换为salesforce时间戳格式
- sql - sql 预留产品的发票总数
- java - 在 Spring Data JDBC 中使用 @Id 注释的复合实体有什么影响?
- java - 如何在 Java 中创建已知数量的对象数组?
- android - 如何在 androidx.biometric 中仅使用人脸 ID?
- android - React Native,任务':app:mergeDexDebug'的执行失败
- postgresql - 获取所有具有外键约束的列名
- azure-sql-database - 如何在 Azure 中 SQL Manage 实例的只读节点上运行 sql profiler?