Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby Sinatra和Grape API在一起?_Ruby_Heroku_Rubygems_Sinatra_Grape Api - Fatal编程技术网

Ruby Sinatra和Grape API在一起?

Ruby Sinatra和Grape API在一起?,ruby,heroku,rubygems,sinatra,grape-api,Ruby,Heroku,Rubygems,Sinatra,Grape Api,我一直在四处阅读,我为ruby找到了这个。我目前正在使用Grape来处理web界面,但我也想实现Grape来处理应用程序的API方面。我找不到任何关于这个话题的有用建议。grape文档说“grape是Ruby的一个REST-like API微框架。它旨在通过提供一个简单的DSL来轻松开发REST-ful API,从而在机架上运行或补充现有的web应用程序框架,如Rails和Sinatra。”所以听起来应该有一种官方方式将两者结合起来,对吗?此应用程序也将在Heroku上运行。您要查找的短语包括:

我一直在四处阅读,我为ruby找到了这个。我目前正在使用Grape来处理web界面,但我也想实现Grape来处理应用程序的API方面。我找不到任何关于这个话题的有用建议。grape文档说“grape是Ruby的一个REST-like API微框架。它旨在通过提供一个简单的DSL来轻松开发REST-ful API,从而在机架上运行或补充现有的web应用程序框架,如Rails和Sinatra。”所以听起来应该有一种官方方式将两者结合起来,对吗?此应用程序也将在Heroku上运行。

您要查找的短语包括:

  • 多机架应用程序
  • 机架中间件
  • 映射URL到sinatra
那种事。Grape、Sinatra和Rails都是应用程序。这意味着你可以构建你的Grape应用程序、Sinatra应用程序和Rails应用程序,然后你可以使用Rack运行它们,因为它们都与机架兼容,因为它们共享一个界面

这在实践中意味着编写应用程序,然后将它们放入一个机架文件中运行。一个使用2个Sinatra应用程序的简短示例(但它们可以是任意数量的任何机架应用程序):

希望这足以让你开始。一旦你知道去哪里找,就会有很多例子。您还可以使用
use
(请参阅)在Sinatra应用程序中运行其他应用程序,我发现Grape也提供了
mount
关键字。有很多方法可以使用,一开始可能有点混乱,但只要尝试一下,看看它们做什么,你最喜欢什么。这其中很大一部分是偏好,所以不要害怕选择感觉正确的。Ruby更适合人类而不是计算机:)


编辑:一个Sinatra应用程序和一个葡萄应用程序“内部”

class-App

我相信会是这样的。

我偶然发现,也许会有点用处。谢谢你的回答。我怎样才能使用这个方法,但却让我的API从根/也运行掉呢?@CristianRivera我已经添加了一个例子,我相信这将是如何做到的。这是它与其他机架应用程序和Sinatra的工作方式。您好,我尝试了您的建议,在我的浏览器中出现了“内部服务器错误”,在服务器日志中,我得到了“!!处理请求时出现意外错误:参数数目错误(1代表0)”@CristianRivera您需要概述您的具体操作,以及错误消息的确切内容,在你的问题中,作为一个编辑,或者很难通过评论来修复。嗨,我确实让你的方法起作用了,但我最终使用了另一种方法,并将它们作为两个单独的heroku应用程序运行。我也会将此标记为答案。
# 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) 
# 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)
class App < Sinatra::Base
  use Twitter::API
  # other stuff…
end

# config.ru
# instead of URLMap…
map "/" do
  run App
end