Fadi Fadi - 1 month ago 23
HTTP Question

HTTP code range check in Ruby

I want to be able to do the following in Ruby:

I can only describe what I need to do in PHP code as of now:

$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;
}


I know about
Net::HTTP
which I got the following code from:

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')


But I'm not sure how to check if the HTTP response is
>= 200
and
< 300
or
302
.

Do I have to write a check for all of the HTTP responses? Or is there an easier way like that PHP code above?

Answer

Okay, so thanks to tadman's comment (for pointing out my obvious mistake.. xD) and for the Tin Man's suggestion, I've changed the code to the following and it works as expected

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')

NOTE: You will need to have the rest-client gem installed, by doing: gem install rest-client