2011-09-01 31 views
10

我的工作,它包含的功能,約10個不同組件的應用程序西納特拉。我們希望能夠混合搭配這些組件到應用程序的不同實例,完全由config.yaml文件進行配置,看起來像:架構模塊化的,基於組件的應用西納特拉

components: 

- route: '/chunky' 
    component_type: FoodLister 
    component_settings: 
    food_type: bacon 
    max_items: 400 

- route: 'places/paris' 
    component_type: Mapper 
    component_settings: 
    latitude: 48.85387273165654 
    longitude: 2.340087890625 

- route: 'places/losangeles' 
    component_type: Mapper 
    component_settings: 
    latitude: 34.043556504127466 
    longitude: -118.23486328125 

正如你所看到的,組件可以被實例化更多每次都有自己的上下文設置。

每個組件包括至少一個路由的,從用於基本配置文件中的「路徑」屬性。

什麼是組織和實例化模塊代碼的最佳方式?

回答

10

這類似於包含的建議,但它並不需要訪問rackup文件。

寫您的各種處理程序,如:

class FoodHandler < Sinatra::Base 
    get '/chunky/:food' do 
    "Chunky #{params[:food]}!" 
    end 
end 

然後在你的主應用程序文件:

require './lib/handlers/food_handler.rb' 

class Main < Sinatra::Base 
    enable :sessions 
    ... bla bla bla 
    use FoodHandler 
end 

我用這種結構建立一些相當複雜的西納特拉應用。它的規模和Rails一樣好。

編輯

爲了使您的配置文件中定義的路由,你可以做這樣的事情:

class PlacesHandler < Sinatra::Base 
    # Given your example, this would define 'places/paris' and 'places/losangeles' 
    CONFIG['components'].select { |c| c['compontent_type'] == 'Mapper' }.each do |c| 
    get c['route'] do 
     @latitude = c['component_settings']['latitude'] 
     @longitude = c['component_settings']['longitude'] 
    end 
    end 
end 
+0

這很接近,但沒有考慮問題中提到的動態路由。即'/ chunky'不能被硬編碼。 –

+0

好點。查看關於編輯。 – bioneuralnet

+0

不錯!沒有想過在擴展代碼中迭代。最後一點:你的意思是'extend'而不是'use'?我似乎無法找到'use'的文檔。 –

2

TIMTOWTDI - There's_more_than_one_way_to_do_it :),這是一個。但實際上我用另一種方式。我使用Sinatra/Base來開發模塊化應用程序。

我simgle路線給各應用。

# config.ru file 

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

require File.dirname(__FILE__) + "/main.rb" 

map "/" { run BONES::Main } 

map "/dashboard" { run BONES::Dashboard } 

map "/app1" { run BONES::App1 } 

您可以爲每個實例設置變量集。 您可以在其模塊上開發每個「組件」。

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

module BONES 

    class Main < Sinatra::Base 
    helpers XIXA::Helpers 

    configure :development do 
     enable :sessions, :clean_trace, :inline_templates 
     disable :logging, :dump_errors 
     set :static, true 
     set :public, 'public' 
    end 

    enable :static, :session 
    set :root, File.dirname(__FILE__) 
    set :custom_option, 'hello' 

    set :haml, { :format => :html5 } 

    #... 

那看一下這裏。 http://codex.heroku.com/

玩得開心:)

+0

Drats!我想這個解決方案會出現,並且幾乎考慮將其添加到問題中,因爲在我們的情況下這是不可能的(機架文件不可用)。如果沒有其他解決方案出現,我會選擇這個! –