Reputation: 10722
I'm parsing a URL in my Rails application. I want to get the domain example.com
stripped of any protocol, subdomain, directories, etc.
My method:
def clean_host(url)
uri = URI.parse(url)
return uri
end
What I actually get for example.com/
is:
scheme:
user:
password:
host:
port:
path: example.com/
query:
opaque:
registry:
fragment:
parser:
What I eventually want is to get the domain example.com stripped of any protocol, subdomain, directories, etc.
I've looked into domainatrix but it wont bundle with my project. Is there a way to do this with Ruby's URI.parse
? Or will I have to look into other avenues?
Upvotes: 1
Views: 1612
Reputation: 195
You should just be able to do request.domain assuming you are doing this in a controller.
You can also use request.path and request.subdomain
For example: http://www.domain.com/users/123
request.subdomain => 'www'
request.domain => 'domain.com'
request.path => '/users/123'
Upvotes: 0
Reputation: 19879
The problem is that example.com/
isn't a full URL. URI rightly assumes it's a path. If it were me and you're going to have a lot of these fragments I'd just brute force it.
> "example.com/".sub(%r{^.*?://}, '').sub(%r{/.*$}, '')
=> "example.com"
> "http://subdomain.example.com/path/here".sub(%r{^.*?://}, '').sub(%r{/.*$}, '')
=> "subdomain.example.com"
Stripping the subdomain off is another ball of wax as you'd need to example the TLD to determine what is appropriate so you don't end up with say "com.uk"
Upvotes: 1