Architecture for a modular, component-based Sinatra Application

前端 未结 2 1772
时光说笑
时光说笑 2021-02-04 12:49

I\'m working on a Sinatra app that contains about 10 different components of functionality. We\'d like to be able to mix and match these components into separate instances of t

2条回答
  •  眼角桃花
    2021-02-04 13:20

    This is similar to include's proposal, but it doesn't require access to the rackup file.

    Write your various Handlers like:

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

    Then in your main application file:

    require './lib/handlers/food_handler.rb'
    
    class Main < Sinatra::Base
      enable :sessions
      ... bla bla bla
      use FoodHandler
    end
    

    I've used this kind of structure to build some fairly complex Sinatra apps. It scales just as well as Rails.

    EDIT

    To have your config file define the routes, you could do something like this:

    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
    

提交回复
热议问题