首页 > 解决方案 > 如何从 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-on-railsgraphql

解决方案


您正在寻找 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  

推荐阅读