5

有没有办法一起使用地图和(莲花)路由器命名空间?下面是config.ru我试图作为演示运行的示例。

require 'bundler'
Bundler.require

module Demo

  class Application

    def initialize
      @app = Rack::Builder.new do
        map '/this_works' do
          run  Proc.new {|env| [200, {"Content-Type" => "text/html"}, ["this_works"]]}
        end
        map '/api' do
          run Lotus::Router.new do
            get '/api/', to: ->(env) { [200, {}, ['Welcome to Lotus::Router!']] }
            get '/*', to: ->(env) { [200, {}, ["This is catch all: #{ env['router.params'].inspect }!"]] }
          end
        end
      end
    end

    def call(env)
      @app.call(env)
    end
  end  
end

run Demo::Application.new
4

1 回答 1

7

您的问题是由于do..endin 方法调用的优先级。在您的代码中,该部分

run Lotus::Router.new do
  get '/api/', to: ->(env) { [200, {}, ['Welcome to Lotus::Router!']] }
  get '/*', to: ->(env) { [200, {}, ["This is catch all: #{ env['router.params'].inspect }!"]] }
end

由 Ruby 解析为

run(Lotus::Router.new) do
  get '/api/', to: ->(env) { [200, {}, ['Welcome to Lotus::Router!']] }
  get '/*', to: ->(env) { [200, {}, ["This is catch all: #{ env['router.params'].inspect }!"]] }
end

换句话说,该块被传递给run,而不是Lotus::Router.new您想要的,并且run只是忽略该块。

要修复它,您需要确保该块与路由器的构造函数相关联,而不是调用run. 有几种方法可以做到这一点。您可以使用{...}而不是do...end,因为它具有更高的优先级:

run Lotus::Router.new {
  #...
}

另一种方法是将路由器分配给局部变量,并将其用作以下参数run

router = Lotus::Router.new do
  #...
end
run router
于 2014-03-13T02:24:38.497 回答