继承HTTParty模块

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

我如何继承HTTParty模块来设置一些默认值?

module SuperClient
  include HTTParty

  headers 'Auth' => 'Basic'
end

class ServiceApiClient
  include SuperClient

  headers 'X-Prop' => 'Some specific data'
  base_uri 'https://example.com'

  def posts
    self.class.get '/posts'
    # Expected to send headers Auth and X-Prop
  end
end

我需要有一些定制的模块,可以将其包含在客户端类中,并且表现得像本机HTTParty模块。

ruby metaprogramming httparty
1个回答
0
投票

您可以将SuperClient保留为类,并从中继承其他客户端。这样的事情。标头'Auth'和'X-Prop'将包含在请求中。

require 'httparty'

class SuperClient 
    include HTTParty

    headers 'Auth' => 'Basic'
    # Uncomment below line to print logs in terminal
    # debug_output STDOUT
end

class ServiceApiClient < SuperClient

    headers 'X-Prop' => 'Some specific data'
    base_uri 'https://example.com'

    def posts
        self.class.get '/posts'
        # Expected to send headers Auth and X-Prop
  end
end         

client = ServiceApiClient.new

client.posts()
© www.soinside.com 2019 - 2024. All rights reserved.