Created
August 24, 2011 16:51
-
-
Save murdoch/1168520 to your computer and use it in GitHub Desktop.
Check if uri exists
This file contains 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
## just some ways to check if a url exists | |
# method 1 - from Simone Carletti | |
require "net/http" | |
url = URI.parse("http://www.google.com/") | |
req = Net::HTTP.new(url.host, url.port) | |
res = req.request_head(url.path) | |
# method 2 - from some kid on the internet | |
require 'open-uri' | |
require 'net/http' | |
def remote_file_exists?(url) | |
url = URI.parse(url) | |
Net::HTTP.start(url.host, url.port) do |http| | |
return http.head(url.request_uri).code == "200" | |
end | |
end | |
# method 3 - from another kid on the internet in response method 2 | |
require 'rubygems' | |
require 'rest-open-uri' | |
def remote_file_exist?(url) | |
open( url , :method => :head).status rescue false | |
end | |
# method 4 - from http://rawsyntax.com/post/4544397323/url-validation-in-rails-3-and-ruby-in-general | |
require 'addressable/uri' | |
class Example | |
include ActiveModel::Validations | |
## | |
# Validates a URL | |
# | |
# If the URI library can parse the value, and the scheme is valid | |
# then we assume the url is valid | |
# | |
class UrlValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
begin | |
uri = Addressable::URI.parse(value) | |
if !["http","https","ftp"].include?(uri.scheme) | |
raise Addressable::URI::InvalidURIError | |
end | |
rescue Addressable::URI::InvalidURIError | |
record.errors[attribute] << "Invalid URL" | |
end | |
end | |
end | |
validates :field, :url => true | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This work for me: