为什么尝试在 Rails 中使用 Grape 会因“未初始化的常量 API"而失败? [英] Why does trying to use Grape with Rails fail with "uninitialized constant API"?
问题描述
我希望有人解释为什么在使用 Grape (0.10.1) 的 Rails (4.1.8) 中会发生这种情况
I would like someone to explain why this is happening in Rails (4.1.8) with Grape (0.10.1)
这是我的 API:
app/api/root.rb
:
module API
class Root < Grape::API
prefix 'api'
mount API::V1::Root
end
end
app/api/v1/root.rb
:
module API::V1
class Root < Grape::API
version 'v1'
mount API::V1::Users
end
end
app/api/v1/users.rb
:
module API::V1
class Users < Grape::API
format 'json'
resource :users do
desc "Return list of users"
get '/' do
User.all
end
end
end
end
config/routes.rb
:
Rails.application.routes.draw do
mount API::Root => '/'
end
并在我的 application.rb
中添加:
config.paths.add "app/api", glob: "**/*.rb"
config.autoload_paths += Dir["#{Rails.root}/app/api/*"]
在那种情况下我得到错误:NameError: uninitialized constant API
and in that case I get the error: NameError: uninitialized constant API
但如果我的代码如下:
app/api/root.rb
同上
然后app/api/v1/root.rb
:
class Root < Grape::API
version 'v1'
mount Users
end
app/api/v1/users.rb
:
class Users < Grape::API
format 'json'
resource :users do
desc "Return list of users"
get '/' do
User.all
end
end
end
config/routes.rb
:
Rails.application.routes.draw do
mount Root => '/'
end
和config/application.rb
同上
然后一切正常.
我的问题是为什么我不需要在 v1/root.rb
和 v1/users
中指定模块,以及为什么我不需要使用 API::Root =>
?config/routes.rb
中的'/'
My question is why don't I need to specify modules inside v1/root.rb
and also inside v1/users
and also why I don't need to use API::Root => '/'
in config/routes.rb
?
推荐答案
这是因为 app/api
是 API 类的顶级文件夹,而不是 app
.
It's because app/api
is the top-level folder for your API classes, not app
.
来自 Grape 的文档:
将 API 文件放入 app/api
.Rails 需要一个与 Ruby 模块名称匹配的子目录和一个与类名称匹配的文件名.在我们的示例中,Twitter::API
的文件名位置和目录应为 app/api/twitter/api.rb
.
Place API files into
app/api
. Rails expects a subdirectory that matches the name of the Ruby module and a file name that matches the name of the class. In our example, the file name location and directory forTwitter::API
should beapp/api/twitter/api.rb
.
因此,API::Root
类的正确位置实际上是 app/api/api/root.rb
,而不是 /app/api/root.rb
—尽管 是顶级命名空间中类的正确位置,这就是您给出的第二个示例的原因(从 API 中删除了类
模块)工作.
Therefore the correct location for an API::Root
class would actually be app/api/api/root.rb
, not /app/api/root.rb
—though that is the correct location for a class in the top-level namespace, which is why the second example you give (with classes removed from the API
module) works.
不过,我建议您将 API 类放在它们自己的模块中,并将它们移动到 app/api
下的匹配子文件夹中.
I recommend you keep your API classes together in their own module, though, and move them to a matching subfolder beneath app/api
.
这篇关于为什么尝试在 Rails 中使用 Grape 会因“未初始化的常量 API"而失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!