How to judge web exists or not with open-uri?

would you mind to tell me how to fix it, to make the following program
to run?
require ‘rubygems’
require ‘open-uri’
url=“www.123.com
open(url){|file| if url don’t exists then puts “url don’t exists”
else puts “url exists”}
thiks

2010/7/20 Pen T. [email protected]:

would you mind to tell me how to fix it, to make the following program
to run?
require ‘rubygems’
require ‘open-uri’
url=“www.123.com
open(url){|file| if url don’t exists then puts “url don’t exists”
else puts “url exists”}

You better use Net::HTTP for this
http://www.ruby-doc.org/stdlib/libdoc/net/http/rdoc/index.html

url = URI.parse(‘www.123.com’)
status = Net::HTTP.start(url.host, url.port) {|http|
http.head(url.path)
}

puts( /^2/ =~ status.code ? “ok” : “nok” )

Kind regards

robert

irb(main):001:0> require ‘rubygems’
=> true
irb(main):002:0> require ‘open-uri’
=> true
irb(main):003:0> url = URI.parse(‘www.123.com’)
=> #<URI::Generic:0xb764ff84 URL:www.123.com>
irb(main):004:0> status = Net::HTTP.start(url.host, url.port) {|http|
irb(main):005:1* http.head(url.path)
irb(main):006:1> }
NameError: uninitialized constant Net
from (irb):4
from :0
irb(main):007:0> puts( /^2/ =~ status.code ? “ok” : “nok” )
NoMethodError: undefined method `code’ for nil:NilClass
from (irb):7
from :0
??

irb(main):017:0> def getURL(u)
irb(main):018:1> begin
irb(main):019:2* x = open(u)
irb(main):020:2> rescue
irb(main):021:2> puts “url does not exist”
irb(main):022:2> end
irb(main):023:1> end
=> nil
irb(main):025:0> getURL(“http://www.awqes.com”)
url does not exist
=> nil
irb(main):026:0> getURL(“http://www.google.com”)
=> #StringIO:0x15bd550
irb(main):027:0>

Not the string “url does not exist” is for visual confirmation.

Though the x is returned as nil on a non-existent URL.

`

NameError: uninitialized constant Net

require ‘net/http’

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs