在Sinatra中获取绝对(基本)URL [英] Get absolute (base) url in sinatra

查看:80
本文介绍了在Sinatra中获取绝对(基本)URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我要做

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

以便能够使用HAML index.haml中的options.base_url. 但是我敢肯定,还有一种更好的,干的方式来做到这一点.但是我看不到,也找不到. (我是Sinatra的新手:))

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 :))

以某种方式,在 get 之外,我没有request.env可用,或者看来.因此,将其放在包含项中是行不通的.

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

如何获取基本网址?

推荐答案

几件事.

  1. set是一个类级别的方法,这意味着您将根据每个请求修改整个应用程序的状态
  2. 上述是一个问题,因为在不同的请求(例如http://foo.comhttps://foo.com)上,或者如果您有多个使用DNS指向同一应用服务器的域,则基本URL可能会有所不同
  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

如果您需要在响应查询之外的基本网址(而不是在get/post/put/delete块或视图中),最好在某个位置手动设置.

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.

这篇关于在Sinatra中获取绝对(基本)URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆