Rails : Validate availablity of a distant ressource over HTTP

Posted by Antonin AMAND Wed, 18 Jul 2007 22:39:00 GMT

Sometimes you may host some ressources on a different website and you may want to validate the availability of it when creating a Rails model object (ActiveRecord::Base).

It would be dramatically unefficient to download the full media with a GET request. So, to achieve this we will use the HEAD http request that act as the GET request but return only the HTTP header without the body.

Here is a exemple of an ActiveRecord::Base object that validates the presence of the ressource among the Internet.


require 'net/http'

# the class is supposed to have a "media" attribute
# that is a relative url to a ressource hosted an a different
# website
class Article < ActiveRecord::Base

  RESOURCE_HOST = "flickr.com"
  RESOURCE_PORT = 80

  validate :validates_presence_of_external_media

  protected

  def validates_presence_of_external_media
    response = nil
    # initiating the HTTP connection
    Net::HTTP.start(RESOURCE_HOST, RESOURCE_PORT) do |http|
      # doing the HEAD request
      response = http.head(media)
    end
    # add an error if the request is not successful
    errors.add :media, "ressource unavailable : #{response.code} #{response.msg}" unless
      responce.kind_of?(Net::HTTPSuccess)
  end

end

This is a very minimalist example, but this kind of technic may have a lot of uses.

Comments

Leave a comment

Comments