Reputation: 517
I am making rails app and I need to get just hostname of my URL from my one of Rails controllers.
If my URL is http://www.example.com/path/0
,then I just want to extract www.example.com
part. How can I do this? I found request.base_url
but this returns http://www.example.com
which I do not want.
In javascript there is a function, window.location.hostname
. I wonder there is a equivalent in Ruby on Rails.
Upvotes: 2
Views: 6676
Reputation: 121
Based on URI module, we can also use #authority method in case you need the port as well.
uri = URI("http://lvh.me:3000/path/0")
uri.authority # => "lvh.me:3000"
Check more about URI #authority method
Upvotes: 0
Reputation: 3611
I am using Rails 4.2
We can get host and port with one method
request.host_with_port
=> "localhost:3002"
Upvotes: 1
Reputation: 3161
The URI
module can do this for you.
uri = URI("http://www.example.com/path/0")
uri.host # => "www.example.com"
Upvotes: 2
Reputation: 2973
You can use request.host
to get exact your URL which you want.
And you can use request.port
to get your port from url
Upvotes: 2