HTTP 代码范围签入 Ruby

HTTP code range check in Ruby

我希望能够在 Ruby 中执行以下操作:

目前我只能在 PHP 代码中描述我需​​要做的事情:

$handle = curl_init($url);
curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);
$httpResponse = curl_getinfo($handle, CURLINFO_HTTP_CODE);

if ($httpResponse >= 200 && $httpResponse < 300 || $httpResponse == 302) {
     do some action;
}

我知道 Net::HTTP 我从中获得了以下代码:

require 'net/http'

def check_status(uri_str, limit = 10)
  # You should choose a better exception.
  raise ArgumentError, 'too many HTTP redirects' if limit == 0

  response = Net::HTTP.get_response(URI(uri_str))

  case response
  when Net::HTTPSuccess then #if 200 then do action
    puts "It works!"
    response.code
    #response
  when Net::HTTPRedirection then #if 3xx then check where it goes
    location = response['location']
    check_status(location, limit - 1)
  else
    response.value
  end
end

print check_status('https://git.company.com')

但我不确定如何检查 HTTP 响应是 >= 200< 300 还是 302

我是否必须为所有 HTTP responses 开一张支票?或者有没有像上面 PHP 代码那样更简单的方法?

好的,感谢 (for pointing out my obvious mistake.. xD) and for ,我已将代码更改为以下内容,它按预期工作

require 'rest-client'

def check_status(uri_str)

    response = RestClient.get "#{uri_str}"

    case response.code
    when 200...300 || 302
        puts "It works!"
    else
        puts "It doesn't work!"
        puts "#{response.code}"
    end
end

print check_status('https://git.company.com')

注意:您需要安装 rest-client gem,方法是:gem install rest-client