Hulihan Applications
about projects portfolio services contact_us
Ruby Domain Check

    Checking HTTP Response codes in Ruby is easy to do, and very useful. A normal, working webpage will usually return a 200 response code, which means everything's okay. We all know about 404s(file not found). Also, 500 errors are pretty prevalent, they usually tell you if something strange or buggy is going with the code of a dynamic website or script. Most rails applications throw a 500 Error when they're not working.

Using Ruby's Net::HTTP library, you can check these HTTP response codes to see if one of your websites are down, or if one of your ruby on rails applications are acting insane. I like to use these with lists of domains that I monitor for downtime or status. Here's an easy way to do it in ruby:
require "net/http" 
@uri = "http://www.hulihanapplications.com"
@request = Net::HTTP.get_response(URI.parse(@uri))  # returns an Net::HTTPResponse Object
puts "Code: #{@request.code} Message: #{@request.message}" # print the HTTP Response code and Message
This should return:
Code: 200 Message: OK

Integrate this into your Rails Application

You can also work this into a ruby on rails application, as a view helper, to make it look pretty and color coded, just add this to app/helpers/application_helper.rb:
module ApplicationHelper
  require "net/http"
  def print_response(url) # print out HTTP response code and message
	 @req = Net::HTTP.get_response(URI.parse(url)) 
	 color = "black"
	 color_hash = Hash.new # create a hash indexed by response code, contains color
	 # Assign color codes by response code
	 color_hash["200"] = "green"
	 color_hash["302"] = "yellow"
	 color_hash["404"] = "red"
	 color_hash["500"] = "red"
	 
	 #if @req.code == 200
	 #   color = "green"
	 #end
	 return "#{@req.code} #{@req.message}"
  end
end

Then you would call this from any view:
www.hulihanapplications.com - <%= print_response("http://www.hulihanapplications.com") %>
This would end up looking like this:
www.hulihanapplications.com - 200 OK

or, if the site is down
www.hulihanapplications.com - 404 Not Found
That's it! This is a good way to check if a website or domain is down from any script or application.

You can learn more about what attributes a Net:HTTPResponse object has here.

You can also read more about the Ruby Net::HTTP library here.


0 Comments


Add A Comment



simple_captcha.jpg



Hulihan Applications © 2007-2009
No portion of this site may be copied, altered, duplicated or otherwise used without the express written approval of Hulihan Applications.