Skip to content

Instantly share code, notes, and snippets.

@stevenberg
Created December 14, 2012 14:09
Show Gist options
  • Save stevenberg/4285698 to your computer and use it in GitHub Desktop.
Save stevenberg/4285698 to your computer and use it in GitHub Desktop.
Quick and Dirty URL Validation in Rails
# http://almosteffortless.com/2009/02/09/quick-and-dirty-url-validation/
class Link < ActiveRecord::Base
attr_accessible :url
validate :validate_url
private
def validate_url
unless %w(200 301 302).include?(self.class.status_code(url))
errors.add :url
end
end
def self.status_code(url)
regexp = url.match(%r{https?://([^/]+)(.*)})
path = regexp[2].blank? ? '/' : regexp[2]
Net::HTTP.start(regexp[1]) { |http| http.head(path).code }
rescue
nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment