Xenyal Xenyal - 6 months ago 21
Ruby Question

Ruby uri module parsing produces nil

My ruby file is using the Ruby

uri
module as such:

require 'uri'

def parse_uri(uri) # uri => www.google.com
uriParsed = URI(uri) # uriParsed => <URI::Generic 0x000000000 URL:www.google.com>
uriHost = uriParsed.host # uriHost => nil


Expected behavior as per stated in the documentation should produce
google.com
for
uriHost
. However, that is not the case; I've tried restarting my Rails server, running
bundle install
, and requiring
uri/http
but to no avail. Any ideas?




Ruby version is 2.1.4, rails version is 4.0.1

Answer

You forgot to call .path on URI:

require 'uri'

def parse_uri(uri)           # uri       => www.google.com
    uriParsed = URI.parse(uri)     # uriParsed => <URI::Generic 0x000000000 URL:www.google.com>
    uriHost = uriParsed.path# uriHost   => nil

OR.

def parse_uri(uri)           # uri       => www.google.com
    uriParsed = URI.parse(uri).path

Actually URI(uri) returns the same object than calling it with .parse so it seem a little redundant. Here is your original approach with .path instead of .host:

def parse_uri(uri)           # uri       => www.google.com
    uriParsed = URI(uri)     # uriParsed => <URI::Generic 0x000000000 URL:www.google.com>
    uriHost = uriParsed.path# uriHost   => nil

Lastly, if you want to omit the www. prefix if the url contains it you can do something like this:

require 'uri'

def parse_uri(uri)           # uri       => www.google.com
    uriParsed = URI(uri)     # uriParsed => <URI::Generic 0x000000000 URL:www.google.com>
    uriHost = uriParsed.path# uriHost   => nil
    uriHost.start_with?('www.') ? uriHost[4..-1] : uriHost

end