如何访问块内的实例变量

问题描述 投票:0回答:1

我正在使用 gem graphql-client 并希望使其针对不同的 URL 和令牌是动态的。

gem 文档和其他地方给出的示例具有硬编码的 URL 和令牌。

我正在尝试访问

@shop.token
def headers
 块内的 
GraphQL::Client::HTTP

class Graphql

  def initialize(shop_id)
    @shop = Shop.find_by(shop_id)
  end

  def http
    GraphQL::Client::HTTP.new("http://graphql-swapi.parseapp.com/") do
      def headers(context)
        { 
          "User-Agent": "My Client",
          "Token" : @shop.token
        }
      end
    end
  end

  def client
      schema = GraphQL::Client.load_schema(http{@shop})
      
      @client ||= GraphQL::Client.new(schema: schema, execute: http{@shop}).tap do |client|
        client.allow_dynamic_queries = true
      end
  end

end

Rails 可以通过

yield
self.instance_eval(&block)
提供访问块内的实例变量 但是我们可以在 headers 方法中访问 @shop 来使令牌动态化吗?

graphql-client http 类定义于here

ruby-on-rails ruby graphql block
1个回答
0
投票

您可以将其设置为访问器,而不是依赖这样的变量,例如:

class Graphql
  attr_reader :shop

  def initialize(shop_id)
    @shop = Shop.find_by(shop_id)
  end

  def http
    GraphQL::Client::HTTP.new("http://graphql-swapi.parseapp.com/") do
      def headers(context)
        { 
          "User-Agent": "My Client",
          "Token" : shop.token
        }
      end
    end
  end

  def client
      schema = GraphQL::Client.load_schema(http{shop})
      
      @client ||= GraphQL::Client.new(schema: schema, execute: http{shop}).tap do |client|
        client.allow_dynamic_queries = true
      end
  end

end
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.