How to mount a Sinatra application inside another Sinatra app?

主宰稳场 提交于 2019-12-03 12:23:00
iain

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! :)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!