[英]Architecture for a modular, component-based Sinatra Application
我正在研究一個包含大約10個不同功能組件的Sinatra應用程序。 我們希望能夠將這些組件混合並匹配到應用程序的單獨實例中,完全由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
如您所見,組件可以多次實例化,每個組件都有自己的上下文設置。
每個組件至少包含一個路由,其中“route”屬性來自用於基礎的配置文件。
組織和實例化模塊代碼的最佳方法是什么?
這類似於include的提議,但它不需要訪問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
我已經使用這種結構來構建一些相當復雜的Sinatra應用程序。 它的擴展與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
TIMTOWTDI - 有更多_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/
玩得開心 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.