How to mount a Sinatra application inside another Sinatra app?

前端 未结 1 1768
渐次进展
渐次进展 2021-02-14 21:46

I am trying to write a Sinatra application that groups components together (sort of like controllers). So for the \"blog\" related things, I want an app called Blog

相关标签:
1条回答
  • 2021-02-14 22:31

    Take a look at https://stackoverflow.com/a/15699791/335847 which has some ideas about namespacing.

    Personally, I would use the config.ru with mapped routes. If you're really in that space between "should this be a separate app or is it just helpful to organize it like this" it allows that, and then later you can still farm off one of the apps on its own without changing the code (or only a little). If you're finding that there's a lot of duplicated set up code, I'd do something like this:

    # base_controller.rb
    
    require 'sinatra/base'
    require "haml"
    # now come some shameless plugs for extensions I maintain :)
    require "sinatra/partial"
    require "sinatra/exstatic_assets"
    
    module MyAmazingApp
      class BaseController < Sinatra::Base
        register Sinatra::Partial
        register Sinatra::Exstatic
    
      end
    
      class Blog < BaseController
        # this gets all the stuff already registered.
      end
    
      class Foo < BaseController
        # this does too!
      end
    end
    
    # config.ru
    
    # this is just me being lazy
    # it'd add in the /base_controller route too, so you
    # may want to change it slightly :)
    MyAmazingApp.constants.each do |const|
      map "/#{const.name.downcase}" do
        run const
      end
    end
    

    Here's a quote from Sinatra Up and Running:

    Not only settings, but every aspect of a Sinatra class will be inherited by its subclasses. This includes defined routes, all the error handlers, extensions, middleware, and so on.

    It has some good examples of using this technique (and others). Since I'm in shameless plug mode I recommend it, even though I've nothing to do with it! :)

    0 讨论(0)
提交回复
热议问题