Created
December 14, 2012 14:09
-
-
Save stevenberg/4285698 to your computer and use it in GitHub Desktop.
Quick and Dirty URL Validation in Rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 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