如何在另一个Sinatra应用程序中挂载Sinatra应用程序? [英] How to mount a Sinatra application inside another Sinatra app?
本文介绍了如何在另一个Sinatra应用程序中挂载Sinatra应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个Sinatra应用程序,它将组件组合在一起(有点像控制器)。所以对于"博客"相关的东西,我想要一个名为Blog
的应用程序安装在/blog
上。Blog
应用程序中包含的所有路由都是相对于其挂载路径的,因此我可以简单地定义index
路由,而不必在路由中指定挂载路径。
map
指定不同应用程序的路径来处理这一问题的。我遇到的问题是,我使用的是需要包含在所有应用程序中的各种Sinatra gem/扩展/助手,所以有很多重复的代码。
如何将一个Sinatra应用程序安装在另一个应用程序中,以便该应用程序中定义的路线相对于该应用程序的安装位置?如果开箱即用不可能做到这一点,您能展示一个代码示例来说明如何做到这一点吗?
这里有一个简化的示例,说明它可能是什么样子:
class App
mount Blog, at: '/blog'
mount Foo, at: '/bar'
end
class Blog
get '/' do
# index action
end
end
class Foo
get '/' do
# index action
end
end
推荐答案
查看https://stackoverflow.com/a/15699791/335847,其中介绍了一些有关命名空间的概念。
就我个人而言,我会使用带有映射路由的config.ru。如果你真的处于"这应该是一个独立的应用程序还是像这样组织它是有帮助的"之间的空隙,它允许这样做,然后你仍然可以在不更改代码的情况下(或者只有很小的改变)独立地从一个应用程序中分离出来。如果您发现有很多重复的设置代码,我会这样做:
# 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
不仅设置,而且Sinatra类的每个方面都将由其子类继承。这包括定义的路由、所有错误处理程序、扩展、中间件等。
它有一些使用这种技术(和其他技术)的很好的例子。因为我处于无耻的插拔模式,所以我推荐它,尽管我和它没有任何关系!:)
这篇关于如何在另一个Sinatra应用程序中挂载Sinatra应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文