如何在 ruby Sinatra class 上下文中获取请求 url?

How to get request url in ruby Sinatra class context?

在 Sinatra 中,您可以使用以下行获取请求的完整路径:

get '/hello-world' do
  request.path_info   # => '/hello-world'
  request.fullpath    # => '/hello-world?foo=bar'
  request.url         # => 'http://example.com/hello-world?foo=bar'
end

我在我的应用程序中使用了几个 classes。在这个特别的 class 中,我喜欢将 request.path_info 与字符串进行比较。

class foo
  def build_menu
    if request.path_info == "/hello-world"
      highlight_menu_entry
    end
  end
end

但是 request-Object 在这个 class 上下文中是未知的并且会抛出一个错误。我虽然这是一个 SUPER-GLOBAL,比如 PHP $_POST$_GET,如果 Ruby/Sinatra.

中有的话

那么如何在 class 上下文中检查 request.path

您可以将值传递给您的 class:

class Foo
  attr_accessor :request_path_info, :request_fullpath, :request_url
  def build_menu
    highlight_menu_entry if request_path_info == '/hello-world'
  end
end

foo = Foo.new

get '/hello-world' do
  foo.request_path_info = request.path_info
  foo.request_fullpath = request.fullpath
  foo.request_url = request.url
end

foo.build_menu

我自己找到了答案。我使用一个自定义的全局变量 $PATHNAME,我可以在任何上下文中使用它。结合我的主应用程序中的 before do-预处理器,我可以使用变量填充。

before do
  $PATHNAME=request.path_info
end

class Foo
  def build_menu
    highlight_menu_entry if $PATHNAME == '/hello-world'
  end
end