5

Is there an easy way to check the status code of another website (e.g. http://google.com) in Ruby on Rails?

Ideally, the list of URLs to check would be pulled from a DB and processed via CRON (or equivalent).

2 Answers 2

9
require 'net/http'

http = Net::HTTP.new('www.google.com',80)
response = http.request_get('/')
p response.status

Slightly more efficient (traffic wise) might be:

response = http.request_head('/')
p response.status

Source: http://ruby-doc.org/stdlib/libdoc/net/http/rdoc/classes/Net/HTTP.html#M001403

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Where is the best place to put this to automate it (e.g. via CRON)? Does it belong in a Ruby file of its own?
If it is using the database, and activerecord makes sense, you could put it in a rails project and the stub that loads everything in a file in /script. Have the stub use require to load your worker and start it running. The files I usually put into app/workers/someworker. I launch this type of thing with a call from cron setup via crontab -e.
It is not response.status but response.code, see ruby-doc.org/stdlib-1.8.7/libdoc/net/http/rdoc/Net/…
1

You can access the request env by calling :

def index
  @req = (request.env).inspect 
end

# index.html.erb
<%= @req %>

1 Comment

The question is about checking the response code of an external website not about getting the env for a local request

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.