您要查找的短语是:
- 多个机架应用程序
- 机架中间件
- 映射 url 机架 sinatra
那种东西。 Grape、Sinatra 和 Rails 都是Rack 应用程序。这意味着您可以构建您的 Grape 应用程序、您的 Sinatra 应用程序和您的 Rails 应用程序,然后您可以使用 Rack 运行它们,因为它们都 Rack 兼容,因为它们共享一个 界面。
这实际上意味着您编写应用程序,然后将它们放入 rackup 文件中以运行它们。一个使用 2 个 Sinatra 应用程序的简短示例(但它们可以是任意数量的任何类型的 Rack 应用程序):
# app/frontend.rb
require 'sinatra/base'
# This is a rack app.
class Frontend < Sinatra::Base
get "/"
haml :index
end
end
__END__
@@ layout
%html
= yield
@@ index
%div.title This is the frontend.
# app/api.rb
# This is also a rack app.
class API < Sinatra::Base
# when this is mapped below,
# it will mean it gets called via "/api/"
get "/" do
"This is the API"
end
end
# config.ru
require_relative "./app/frontend.rb"
require_relative "./app/api.rb"
# Here base URL's are mapped to rack apps.
run Rack::URLMap.new("/" => Frontend.new,
"/api" => Api.new)
如果您想从 Grape README 添加 Twitter API 示例:
# app/twitter_api.rb
module Twitter
# more code follows
# config.ru
require_relative "./app/twitter_api.rb" # add this
# change this to:
run Rack::URLMap.new("/" => Frontend,
"/api" => API,
"/twitter" => Twitter::API)
希望这足以让您入门。一旦你知道在哪里看,就会有很多例子。您还可以使用use(参见http://www.sinatrarb.com/intro#Rack%20Middleware)在Sinatra 应用程序中运行其他应用程序,我看到Grape 也提供了mount 关键字。有很多可用的方法,一开始可能会有点混乱,但只要尝试一下,看看它们的作用和你最喜欢的方法。其中很大一部分是偏好,所以不要害怕选择合适的方式。 Ruby 更适合人类而不是计算机 :)
编辑:Sinatra 应用程序“内部”有 Grape 应用程序
class App < Sinatra::Base
use Twitter::API
# other stuff…
end
# config.ru
# instead of URLMap…
map "/" do
run App
end
我相信会是这样的。