Reputation: 3046
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
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
Reputation: 6072
You can do this - but beware:
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
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