DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Ilya has posted 1 posts at DZone. View Full User Profile

URL/URI Validations In Rails

  • submit to reddit
        Here is a quick/basic URI validation library for your Rails app: 

require 'net/http'

# Original credits:
# HTTP Codes:

class ActiveRecord::Base
  def self.validates_uri_existence_of(*attr_names)
    configuration = { :message => "is not valid or not responding", :on => :save, :with => nil }
    configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
    raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)
    validates_each(attr_names, configuration) do |r, a, v|
        if v.to_s =~ configuration[:with] # check RegExp
              begin # check header response
                  case Net::HTTP.get_response(URI.parse(v))
                    when Net::HTTPSuccess then true
                    else r.errors.add(a, configuration[:message]) and false
              rescue # Recover on DNS failures.. 
                  r.errors.add(a, configuration[:message]) and false
          r.errors.add(a, configuration[:message]) and false

Save the code above into a file in your 'lib' directory. ex: validates_uri_existence_of.rb. Include the file in your environment.rb (ex: require 'validates_uri_existence_of'). 

And now you can use the validator in any model by calling:
validates_uri_existence_of :url, :with =>
        /(^$)|(^(http|https)://[a-z0-9] ([-.]{1}[a-z0-9] )*.[a-z]{2,5}(([0-9]{1,5})?/.*)?$)/ix

Above code validates the URI/URL against a regular expression first, and then does a HEAD query to confirm that the page is alive (HTTPSuccess code is returned). You could easily modify the code to extend the functionality as you wish. 

More info in <a href=""> this post.</a>