Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Ruby, what is the most efficient way to get the content type of a given URL?

What is the most efficient way to get the content-type of a given URL using Ruby?

like image 279
deruse Avatar asked Dec 04 '22 08:12

deruse


2 Answers

This is what I'd do if I want simple code:

require 'open-uri'
str = open('http://example.com')
str.content_type #=> "text/html"

The big advantage is it follows redirects.

If you're checking a bunch of URLs you might want to call close on the handles after you've found what you want.

like image 69
the Tin Man Avatar answered Dec 29 '22 14:12

the Tin Man


Take a look at the Net::HTTP library.

require 'net/http'

response = nil
uri, path = 'google.com', '/'
Net::HTTP.start(uri, 80) { |http| response = http.head(path) }
p response['content-type']
like image 41
Chris Avatar answered Dec 29 '22 16:12

Chris