Blankman Blankman - 7 months ago 24
Ruby Question

My Rails API endpoint takes a Host value, want to be able to get domain, subdomain

My controller action receives a hostname like:

/customer?hostname=hello.example.com


Now in my action I have this:

def customer
hostname = params[:hostname]
end


I want to be somehow parse this hostname the same way Rails does, so I can do something like:

request.domain
request.subdomain
request.host


It seems the the ActionDispatch Url.rb is the module that does the logic aroudn this, but not sure how I can tap into this?

I would want something like this:

url = ActionDispatch::abc(hostname)

url.domain
url.subdomain
url.host


What class/methods should I be using here?

Reference:
https://github.com/rails/rails/blob/master/actionpack/lib/action_dispatch/http/url.rb

Answer

Here you go:

class UrlParser
  include ActionDispatch::Http::URL

  def initialize(url)
    @_url = url
  end

  # Don't forget to override this method!
  def raw_host_with_port
    @_url
  end
end

## Example usage:

url = UrlParser.new 'sub.example.com:8080'

url.subdomain     # => 'sub'
url.domain        # => 'example.com'
url.port          # => '8080'