代码类似于:
http_adapter = ::GraphQL::Client::HTTP.new(schema_url) do
def headers(context)
{
'Authorization': "Bearer #{}",
'Content-Type': 'application/json'
}
end
end
我需要的是将变量从http_adapter
级别上下文传递到内部Bearer #{}
。另外,由于令牌每隔几个小时过期一次,因此我无法传递常量或环境变量。那么如何正确传递令牌?谢谢。
顺便说一下,上面的代码是实例方法的一部分。
答案 0 :(得分:1)
一个人可能使用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)