I want to be able to parse any URL with Ruby to get the main part of the domain without the www (just the example.com)
I want to be able to parse any URL with Ruby to get the main part of the domain without the www (just the example.com)
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.
Well you can write this method:
require 'URI'
def domain_name(url, arg={:with_dot_principal=>false})
arg[:with_dot_principal] ? URI(url).hostname.split('.').last(2).join('.') : URI(url).hostname.split('.').last(2).first
end
And using:
domain_name("https://www.google.com/?gws_rd=ssl&safe=active&ssui=on")
# => "google"
domain_name("http://google.com", with_dot_principal: true)
# => "google.com"
Edit:Warning: This method is a basic answer, this have some observations by the community