Politics, Programming and Possibilities
13 Apr
Here’s a way to validate a url if you really want to make sure it’s real (i.e. this goes above and beyond merely checking that a regexp says it’s ok–instead, it goes out and pings the server.)
Create a file, validates_uri_existence_of.rb in your app’s lib folder:
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
Add ” require ‘validates_uri_existence_of’ ” to your environment.rb. Then in your model:
class Repository < ActiveRecord::Base
validates_uri_existence_of :url
end
One Response for "Simple URI Validation"
How about using a HEAD request to test for the existence of a URI rather than a GET?