Get absolute (base) url in sinatra

血红的双手。 提交于 2019-12-29 03:39:08

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/2950234/get-absolute-base-url-in-sinatra

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!