Over a million developers have joined DZone.

Validate URIs By Pinging The Server

·

require 'open-uri'

class ActiveRecord::Base
  def self.validates_uri_existence_of(*attr_names)
    configuration = { :message => "is not a valid web address" }
    configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
    validates_each attr_names do |m, a, v|
      begin
        # Try to open the URI
        open v
      rescue
        # Report the error if it throws an exception
        m.errors.add(a, configuration[:message])
      end
    end
  end
end


Details on my blog.
Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}