Mohamed Yakout
Mohamed Yakout

Reputation: 3046

Check on the status code of url before redirect_to in controller rails

I have action check_status in instances_controller, and I want to check on status code of URL before redirect_to it.

if status_code is 200 redirect_to it, else go to view page.

This is the pseudo-code of check_status action:

def check_status
  if "http://www.web.com".status_code == 200
    redirect_to "http://www.web.com"
  else
    #DO Nothing, and go to its view
  end
end

For example get '/about' => 'instances#check_status', and i want to check if (web.com) get status=200 visit (web.com)

Upvotes: 3

Views: 2108

Answers (3)

Markus Andreas
Markus Andreas

Reputation: 993

For me just this one is working to check the response

The == one gets no match...

response.is_a? Net::HTTPSuccess

Upvotes: 0

Alex P
Alex P

Reputation: 6072

You can do this - but beware:

  1. Your user will have to wait for your response check to complete before they get redirected. If you're checking a slow server, that could be up to 30 seconds before they get sent somewhere else.
  2. There's no guarantee that the user will get the same result you got when you checked.

Here's some code that uses Ruby's Net::HTTP module to perform that web request:

require 'net/http'

def check_status(url)
  uri = URI(url)
  Net::HTTP.start(uri.host, uri.port) do |http|
    request = Net::HTTP::Head.new uri.request_uri
    response = http.request request

    if response == Net::HTTPSuccess
      redirect_to url and return
    end
  end
end

Make sure you're passing in full URLs to this method, complete with an http:// or https:// prefix, or this won't work.

If you were worried about that performance hit, you could cache the results for a short while and check those before returning. That is, when you look up a URL you can save the time of the lookup & the status code retrieved. Then, on the next lookup, if you've checked that domain in the past 24 hours, return the redirect immediately rather than checking it again.

Upvotes: 2

M.ElSaka
M.ElSaka

Reputation: 1294

In addition to Alex's answer, you can use curl tool instead of Net::HTTP module.

system('curl www.google.com') # => true

system('curl www.google_not_valid.com') # => false

Upvotes: -1

Related Questions