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.

Revisions

  1. stevenberg revised this gist Dec 14, 2012. No changes.
  2. stevenberg revised this gist Dec 14, 2012. No changes.
  3. stevenberg created this gist Dec 14, 2012.
    23 changes: 23 additions & 0 deletions quick_and_dirty_url_validation.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    # 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