Sahil Dhankhar Sahil Dhankhar - 1 year ago 44
Ruby Question

Converting to valid urls which can be opened by open-uri

I need to open some webpages using open-uri in ruby and then parse the content of those pages using Nokogori.
I just did:

require 'open-uri'
content_file = open(user_input_url)

This worked for:
but fails when user give inputs like

One thing i can do for such inputs i can append
and return the content of the page that opens. But this seems like a big hack to me.
Is there any better way to achieve this in ruby(i.e converting these user_inputs to valid open_uri urls).

Answer Source
uri = URI("")
if uri.instance_of?(URI::Generic)
    uri ={:host => uri.to_s}) 
content_file = open(uri)

There are other ways as well see ref: