代码如下:
http_adapter = ::GraphQL::Client::HTTP.new(schema_url) do
def headers(context)
{
'Authorization': "Bearer #{}",
'Content-Type': 'application/json'
}
end
end
我需要的是将一个变量从http_adapter
级别上下文传递给内部Bearer #{}
。此外,由于令牌每隔几个小时到期,因此无法传递常量或环境变量。那么如何正确传递令牌呢?谢谢。
顺便说一句,上面的代码是实例方法的一部分。
有人可能会使用Module#define_method
来保留范围:
http_adapter = ::GraphQL::Client::HTTP.new(schema_url) do
define_method :headers do |context|
{
'Authorization': "Bearer #{}", # outer context is available here
'Content-Type': 'application/json'
}
end
end
或者,可以在::GraphQL::Client::HTTP
中使用专用的实例变量:
::GraphQL::Client::HTTP.instance_variable_set(:@bearer, ...)
http_adapter = ::GraphQL::Client::HTTP.new(schema_url) do
def headers(context)
{
'Authorization': "Bearer #{self.class.instance_variable_get(:@bearer)}",
'Content-Type': 'application/json'
}
end
end
或者,也可以自己执行the initialization:
http_adapter = ::GraphQL::Client::HTTP.new(schema_url)
http_adapter.class.send(:attr_writer, :bearer)
http_adapter.bearer = ...
http_adapter.extend(Module.new do
def headers(context)
{
'Authorization': "Bearer #{@bearer}",
'Content-Type': 'application/json'
}
end
end)