如何更改URI对象的path属性?

时间:2019-12-08 16:10:36

标签: ruby net-http

我只想使用略有不同的URI来调用API。该代码段符合我的要求,但是我想知道是否有更有效的方法来实现它。

require 'net/http'
require 'json'

# These URIs differ only in the path
orders = URI('https://hft-api.lykke.com/api/Orders?orderType=Unknown')
asset_pairs = URI('https://hft-api.lykke.com/api/AssetPairs')

lykke_req = Net::HTTP::Get.new(orders)
lykke_req['User-Agent'] = 'curl/7.67.0'
lykke_req['api-key'] = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
lykke_req['Accept'] = 'application/json'

response = Net::HTTP.start(orders.hostname,
                           orders.port,
                           :use_ssl => true) {|http| http.request(lykke_req)}

puts JSON.parse(response.body)

lykke_req = Net::HTTP::Get.new(asset_pairs)
lykke_req['User-Agent'] = 'curl/7.67.0'
lykke_req['Accept'] = 'application/json'

response = Net::HTTP.start(asset_pairs.hostname,
                           asset_pairs.port,
                           :use_ssl => true) {|http| http.request(lykke_req)}

puts JSON.parse(response.body)

我要做的就是重用相同的代码,但URI稍有不同。

对于我的lykke_req对象,我可以写

puts lykke_req
puts lykke_req.path

这给了我

#<Net::HTTP::Get:0x00007f947f1fdce8>
/api/Orders?orderType=Unknown

所以在我看来,我要做的就是更改lykke_req.path的值。但是我不知道该怎么做。我正在寻找这样的东西

lykke_req.path = "/api/AssetPairs"

失败

undefined method `path=' for #<Net::HTTP::Get GET> (NoMethodError)

我在official documentation page上找到了它,但是我找不到[R]的含义。它是只读的吗?我真的必须经历每次创建一个新的URI对象然后每次创建一个新的Net :: HTTP :: Get对象的麻烦吗?

  

路径[R]

2 个答案:

答案 0 :(得分:1)

这里的问题是您试图更改网络请求对象而不是uri对象:

irb(main):001:0> uri = URI('https://hft-api.lykke.com/api/Orders?orderType=Unknown')
=> #<URI::HTTPS https://hft-api.lykke.com/api/Orders?orderType=Unknown>
irb(main):002:0> uri.path = '/foo'
=> "/foo"
irb(main):003:0> uri.to_s
=> "https://hft-api.lykke.com/foo?orderType=Unknown"

但是我真的只是将其包装在一个类中,以便您可以封装和结构化代码并避免重复:

class LykkeAPIClient
  BASE_URI = URI('https://hft-api.lykke.com/api')

  def initalize(api_key:)
    @api_key = api_key
  end

  def get_orders
    get '/Orders?orderType=Unknown'
  end

  def get_asset_pairs
    get '/AssetPairs'
  end

  def get(path)
    req = Net::HTTP::Get.new(BASE_URI.join(path))
    req['User-Agent'] = 'curl/7.67.0'
    req['Accept'] = 'application/json'
    req['api-key'] = @api_key
    response = Net::HTTP.start(req.hostname, req.port, use_ssl: true) do |http|
      http.request(uri)
    end
    # @todo check response status!
    JSON.parse(response.body)
  end
end

@client = LykkeAPIClient.new(api_key: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
@orders = @client.get_orders

答案 1 :(得分:0)