Fadi Fadi - 1 year ago 110
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
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!"
when Net::HTTPRedirection then #if 3xx then check where it goes
location = response['location']
check_status(location, limit - 1)

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

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

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 Source

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!"
        puts "It doesn't work!"
        puts "#{response.code}"

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download