AustintheCleric
AustintheCleric

Reputation: 359

How to pass variables across different contexts

The code is like:

http_adapter = ::GraphQL::Client::HTTP.new(schema_url) do
  def headers(context)
    {
      'Authorization': "Bearer #{}",
      'Content-Type': 'application/json'
    }
  end
end

What I need is to pass a variable from http_adapter level context to the inner Bearer #{}. Also I cannot pass a constant or an environment varible since the token expires every several hours. So how can I pass in the token properly? Thanks.

The code above is part of an instance method by the way.

Upvotes: 0

Views: 74

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

One might use Module#define_method to preserve a scope:

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

Or, one might use a dedicated instance variable in ::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

Or, alternatively, one might perform the initialization themselves:

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)

Upvotes: 1

Related Questions