2014-03-13 28 views
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 
+0

upvoted讓你到你的1500點儘快:) – Rahul

+0

@Rahul thx,我通知項目業主,他們得到了標籤添加https://github.com/lotus/router/issues/5 – Krut

回答

6

你的問題是由於在方法調用中的優先級爲do..end。在你的代碼段

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) 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 
+1

這是要走的路。我在本地嘗試過,可以確認它對我有用。 –

+0

是的,它能夠工作,仍然不確定使用機架製造商地圖的蓮花路由器的最佳方式,在單機架應用中可以使用多個路由器(這是我們目前構建更大的Sinatra應用程序的方式) – Krut