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

前端 未结 7 645
没有蜡笔的小新
没有蜡笔的小新 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:23

    Addressable is probably the right answer in 2018, especially uses the PublicSuffix gem to parse domains.

    However, I need to do this kind of parsing in multiple places, from various data sources, and found it a bit verbose to use repeatedly. So I created a wrapper around it, Adomain:

    require 'adomain'
    
    Adomain["https://toolbar.google.com"]
    # => "toolbar.google.com"
    
    Adomain["https://www.google.com"]
    # => "google.com"
    
    Adomain["stackoverflow.com"]
    # => "stackoverflow.com"
    

    I hope this helps others.

提交回复
热议问题