0

我正在编写一个 gem,它将作为我公司提供的服务的 REST API 客户端。

为此,我有一个Channel类将用作与/channelsAPI 路径交互的一种方式。它HTTParty用于实际的 HTTP 调用。此类有一个名为 create 的方法,该方法发布具有所需属性的 Channel 实例。

这是该方法的样子:

def create
  body = { external_id: external_id,
           name:        name,
           description: description }
  action = post "/", body
  case action.response.class
  when Net::HTTPAccepted      then return action
  when Net::HTTPNotAcceptable then raise HTTPNotAcceptable
  else raise "Server responded with " + Net::HTTPResponse::CODE_TO_OBJ[action.response.code].to_s
  end
end

post方法是将主体哈希转换为 JSON 并将身份验证和其他属性附加到实际HTTParty调用的抽象。

这不起作用。即使响应是 a 202,此case语句也始终符合else条件。我在通话pry后附加了一个会话post以验证响应是否正确:

    38: def create
    39:   body = { external_id: external_id,
    40:            name:        name,
    41:            description: description }
    42:   action = post "/", body
 => 43:   case action.response.class
    44:   when Net::HTTPAccepted      then return action
    45:   when Net::HTTPNotAcceptable then raise HTTPNotAcceptable
    46:   else raise "Server responded with " + Net::HTTPResponse::CODE_TO_OBJ[action.response.code].to_s
    47:   end
    48: end

[1] (pry) #<ZynkApi::Channel>: 0> action.response.class
=> Net::HTTPAccepted

但它仍然落在else

[1] (pry) #<ZynkApi::Channel>: 0> action.response.class
=> Net::HTTPAccepted
[2] (pry) #<ZynkApi::Channel>: 0> n

From: /Users/cassiano/projects/Zynk/src/zynk_api/lib/zynk_api/channel.rb @ line 38 ZynkApi::Channel#create:

    38: def create
    39:   body = { external_id: external_id,
    40:            name:        name,
    41:            description: description }
    42:   action = post "/", body
    43:   case action.response.class
    44:   when Net::HTTPAccepted      then return action
    45:   when Net::HTTPNotAcceptable then raise HTTPNotAcceptable
 => 46:   else raise "Server responded with " + Net::HTTPResponse::CODE_TO_OBJ[action.response.code].to_s
    47:   end
    48: end
4

1 回答 1

2

考虑 case 语句,就像它使用===方法一样:

if Net::HTTPAccepted === action.response.class
  puts 'accepted'
elsif Net::HTTPNotAcceptable === action.response.class
  puts 'not acceptable'
else
  puts 'unknown status'
end

但是,正如你所知 - 大多数类的类是一个类,所以你应该像这样重写你的案例(不要在响应时调用类方法):

case action.response
  when Net::HTTPAccepted
    return action
  when Net::HTTPNotAcceptable
    raise HTTPNotAcceptable
  else
    raise "Server responded with " + Net::HTTPResponse::CODE_TO_OBJ[action.response.code].to_s
end
于 2012-08-07T11:57:17.743 回答