How would you parse a url in Ruby to get the main domain?

前端 未结 7 639
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 02:03

I want to be able to parse any url with ruby to get the main part of the domain without the www (just the XXXX.com)

7条回答
  •  再見小時候
    2020-11-30 02:25

    Just a short note: to overcome the second parsing of the url from Mischas second example, you could make a string comparison instead of URI.parse.

    # Only parses once
    def get_host_without_www(url)
      url = "http://#{url}" unless url.start_with?('http')
      uri = URI.parse(url)
      host = uri.host.downcase
      host.start_with?('www.') ? host[4..-1] : host
    end
    

    The downside of this approach is, that it is limiting the url to http(s) based urls, which is widely the standard. But if you will use it more general (f.e. for ftp links) you have to adjust accordingly.

提交回复
热议问题