如何正确制作ShopifyAPI::GraphQLRails 中的方法。
尝试下面的代码rails console
工作正常。
但是当我尝试将该代码放入 Rails 控制器/模型中并创建一个方法时,我得到:
GraphQL::Client::DynamicQueryError Expected definition to be assigned to a static constant
shopify_client
client = ShopifyAPI::GraphQL.new
SHOP_NAME_QUERY = client.parse <<-'GRAPHQL'
{
shop {
name
}
}
GRAPHQL
result = client.query(SHOP_NAME_QUERY)
我试着玩弄variables
下列的https://github.com/github/graphql-client/blob/master/guides/dynamic-query-error.md
但没有成功.
如何使用上述函数创建一个不会返回上述错误的方法。
样本模型法:
def trial
shopify_client
client = ShopifyAPI::GraphQL.new
shop_query = client.parse <<-'GRAPHQL'
{
shop {
name
}
}
GRAPHQL
client.query(shop_query)
end
In Gemfile: gem 'shopify_api', git: 'https://github.com/Shopify/shopify_api', branch: 'graphql-support'
几天前我遇到了类似的问题,我不得不使用const_set
用于动态设置常数。所以,使用你的例子可以翻译成
class Foo
def trial
#code to initialize shopify session here
set_query
client.query(ProductQuery)
end
private
def set_query
query = <<-GRAPHQL
{
shop {
name
}
}
GRAPHQL
Kernel.const_set(:ProductQuery, client.parse(query))
end
def client
ShopifyAPI::GraphQL.new
end
end
Shopify 的 GraphQL 功能依赖于Github GraphQL ruby 客户端,它要求在常量中定义查询。另外,shopify_api gem
强制要求存在 Shopify 会话,然后您才能使用此方法,根据您的设置,如果常量位于类主体上,则可能没有定义会话,因为该常量首先由 ruby 解释器执行。解决这个问题的方法是动态设置常量
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)