2012-03-08 83 views
6

我試圖使用子類風格西納特拉應用。所以,我有一個這樣的主要應用程序。如何在模塊化Sinatra應用程序中正確配置。

class MyApp < Sinatra::Base 
    get '/' 
    end 

    ... 
end 

class AnotherRoute < MyApp 
    get '/another' 
    end 

    post '/another' 
    end 
end 
run Rack::URLMap.new \ 
    "/"  => MyApp.new, 
    "/another" => AnotherRoute.new 

在config.ru我明白,這只是對 「GET」 怎麼樣其他資源(例如, 「PUT」, 「POST」)?我不確定我是否錯過了某些明顯的東西。而且如果我有十個路徑(/ PATH1,/路徑,...)我必須配置他們都在config.ru即使他們是在同一個班?

+0

爲什麼你想有每個路徑不同類config.ru?爲什麼你不能在MyApp中擁有所有的URL映射? – ch4nd4n 2012-03-08 09:13:51

+0

我只是想讓它更容易分離,因爲我的應用程序越來越大,而且我不想一直往上滾動。 – toy 2012-03-08 21:21:52

+0

你看過[padrino](http://www.padrinorb.com/)嗎?這在Sinatra上非常靈活**。 – ch4nd4n 2012-03-09 05:41:16

回答

4

參考文檔隨着URLMap您指定應該安裝應用程序的基本URL。確定在應用程序中使用哪條路線時,不會使用地圖中指定的路徑。換句話說,應用程序的行爲,就好像它的根是URLMap使用的路徑之後。

例如,您的代碼將以下路徑響應:

  • /:將被路由到/路線MyApp

  • /another:會去/路線AnotherRoute。由於AnotherRoute延伸MyApp這將是相同/MyApp(但在不同的實例)。

    URLMap看到/another並使用它映射到AnotherRoute,從路徑中剝離這部分請求。 AnotherRoute然後只看到/

  • /another/another:將被路由到兩個/another航線AnotherRoute。再次,第一another使用由URLMap將請求路由到AnotherRouteAnotherRoute然後只看到第二another作爲路徑。

    注意,這條道路將雙方GETPOST響應請求,分別由相應的模塊進行處理。

目前尚不清楚你想要做什麼,但我認爲你可以通過運行AnotherRoute實例達到你想要什麼,用config.ru那就是:

run AnotherRoute.new 

由於AnotherRoute延伸MyApp,將爲其定義/路線。

如果您正在尋找將路線添加到現有Sinatra應用程序的方法,您可以使用create a module with an included method that adds the routes,而不是使用繼承。

15

app.rb

class MyApp < Sinatra::Base 
    get '/' 
    end 
end 

app2.rb如果你想兩個單獨的文件。注意這從Sinatra :: Base繼承而不是MyApp。

class AnotherRoute < Sinatra::Base 
    get '/' 
    end 

    post '/' 
    end 
end 

require 'bundler/setup' 
Bundler.require(:default) 

require File.dirname(__FILE__) + "/lib/app.rb" 
require File.dirname(__FILE__) + "/lib/app2.rb" 


map "/" do 
    run MyApp 
end 

map "/another" do 
    run AnotherRoute 
end 
相關問題