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.
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? You should use request. original_url to get the current URL.
OpenURI is an easy-to-use wrapper for Net::HTTP, Net::HTTPS and Net::FTP.
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With