27

I'm trying to get the domain name in my Sinatra app but as a newbie I really am struggling to figure out how to do this, and I know it must be possible!

Rack::Request#host_with_port looks promising, but I don't know how to get this from my app - how do I get stuff from Rack in my Ruby code?

Or is there another way - I'm thinking I don't really want to do this every time a request happens (although it's not too bad), but I thought it'd be better if I could just do it once when the application loads up.

Any hints?

Facundo Casco
  • 10,065
  • 8
  • 42
  • 63
Louis Sayers
  • 2,162
  • 3
  • 30
  • 53

2 Answers2

50

simply use request.host inside your code.

get  "/" do
  puts request.host #=> localhost
end
intellidiot
  • 11,108
  • 4
  • 34
  • 41
  • 4
    Thanks :) this will definitely work - I'd probably use request.host_with_port, as I need the port number too - I'm still wondering though if I need to do this for every request - is there no way that I can do it once in the application? – Louis Sayers May 16 '11 at 13:33
  • 1
    AFAIK, the request object is generated with each request. So, do it once for the whole application is not possible. Although, you can use a before filter to save repeated coding. You can use `before { $Host_with_port = request.host_with_port }` for a before filter. – intellidiot May 16 '11 at 18:14
10

Take a look at:

request.env.inspect

so you can see all the request environment variables.

I think that you are looking for

request.env["SERVER_NAME"]
makevoid
  • 3,276
  • 2
  • 33
  • 29
  • 2
    Cool :) thanks, this helped and let me learn something about request - I didn't realise that the Sinatra Request class inherits from the Rack request - I was wondering where the env attribute came from! – Louis Sayers May 16 '11 at 13:31
  • You can also use request.env["SERVER_PORT"] and request.env["PATH_INFO"] to get the port number and path, or request.env["REQUEST_URI"] for the whole URI. – Guilherme Garnier Nov 12 '13 at 15:43