20

Right now, I do a

get '/' do
  set :base_url, "#{request.env['rack.url_scheme']}://#{request.env['HTTP_HOST']}"
  # ...
  haml :index
end

to be able to use options.base_url in the HAML index.haml. But I am sure there is a far better, DRY, way of doing this. Yet I cannot see, nor find it. (I am new to Sinatra :))

Somehow, outside of get, I don't have request.env available, or so it seems. So putting it in an include did not work.

How do you get your base url?

berkes
  • 26,996
  • 27
  • 115
  • 206

2 Answers2

40

You can get it using request.base_url too =D (take a look at rack/request.rb)

epidemian
  • 18,817
  • 3
  • 62
  • 71
  • 3
    This looks like the best way, since source code as basically does what the other answer suggests doing manually and IMPORTANTLY includes the port optionally if it's non-default – stujo Oct 14 '15 at 22:57
26

A couple things.

  1. set is a class level method, which means you are modifying the whole app's state with each request
  2. The above is a problem because potentially, the base url could be different on different requests eg http://foo.com and https://foo.com or if you have multiple domains pointed at the same app server using DNS

A better tactic might be to define a helper

helpers do
  def base_url
    @base_url ||= "#{request.env['rack.url_scheme']}://#{request.env['HTTP_HOST']}"
  end
end

If you need the base url outside of responding to queries(not in a get/post/put/delete block or a view), it would be better to set it manually somewhere.

BaroqueBobcat
  • 10,090
  • 1
  • 31
  • 37
  • Thanks. I read about helpers, but did not get far enough to dive into that deeply. Thanks. It seems that the answer was there :) – berkes Jun 02 '10 at 12:55
  • 1
    `@base_url ||= "#{request.scheme}://#{request.host}"` – Constantine Oct 02 '19 at 19:37
  • Might need to add `#{request.port}` if you are not running your httpd on the standard ports (like 443 for https) – Chris Dec 16 '19 at 14:59