Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error When Trying to Open a URL in Ruby on Rails

Environment: Ruby 1.9.2, Rails 3.0.3, Ubuntu

When I try to open a URL using:

open("http://www.cnn.com")

I get the following error:

Errno::ENOENT: No such file or directory - http://www.cnn.com
    from (irb):9:in `initialize'
    from (irb):9:in `open'
    from (irb):9

(It's a difficult topic to search). This is happening in both irb and in my app. It used to work under Ruby 1.8.7 and Rails 2.3.4 but it appears that something has changed.

like image 355
Andy Avatar asked Feb 10 '11 01:02

Andy


People also ask

How do I get the URL in Ruby?

You can write request. url instead of request. request_uri . This combines the protocol (usually http://) with the host, and request_uri to give you the full address.

What is the best way to get the current request URL in Rails?

What is the best way to get the current request URL in Rails? You should use request. original_url to get the current URL.

What is Open Uri?

OpenURI is an easy-to-use wrapper for Net::HTTP, Net::HTTPS and Net::FTP.


3 Answers

I can reproduce the error if I try

open('http://www.google.com')

I'll get this error: `initialize': No such file or directory - http://www.google.com (Errno::ENOENT)

Instead, I required 'open-uri' in ruby 1.9.2 and it worked -

require 'open-uri'

url = URI.parse('http://www.google.com')
open(url) do |http|
  response = http.read
  puts "response: #{response.inspect}"
end
like image 137
blooberr Avatar answered Nov 10 '22 18:11

blooberr


I tried something like this in Codecademy's exercise section. Turns out that the request wanted a closing backslash. Evidently open('http://google.com/') went through fine where open('http://google.com') did not.

like image 25
Kenneth Westervelt Avatar answered Nov 10 '22 18:11

Kenneth Westervelt


I can't reproduce the error, in 1.8.7 I get a File object and in 1.9.2 I get a StringIO object. My guess is that some other code is overriding that functionality. Maybe you can try using the Net::HTTP object instead:

require 'net/http'
require 'uri'
Net::HTTP.get_print URI.parse('http://www.cnn.com')

or

require 'net/http'
require 'uri'

url = URI.parse('http://www.cnn.com')
res = Net::HTTP.start(url.host, url.port) {|http|
  http.get('/')
}
puts res.body
like image 28
Pan Thomakos Avatar answered Nov 10 '22 17:11

Pan Thomakos