问题描述
我想有人解释这是在铁轨(4.1.8)与葡萄发生的事情(0.10.1)
I would like someone to explain why this is happening in Rails (4.1.8) with Grape (0.10.1)
所以这是我的API:
应用程序/ API / root.rb
:
module API
class Root < Grape::API
prefix 'api'
mount API::V1::Root
end
end
应用程序/ API / V1 / root.rb
:
module API::V1
class Root < Grape::API
version 'v1'
mount API::V1::Users
end
end
应用程序/ 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:未初始化不断API
and in that case I get the error: NameError: uninitialized constant API
但如果我的code是这样的:
应用程序/ API / root.rb
:同上。
然后应用程序/ API / V1 / root.rb
:
class Root < Grape::API
version 'v1'
mount Users
end
应用程序/ 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 /用户
,也是为什么我不需要使用 API ::根=&GT; /
在的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
?
推荐答案
这是因为应用程序/ API
是API类的顶层文件夹,而不是应用
。
It's because app/api
is the top-level folder for your API classes, not app
.
的文档:
将API文件放到应用程序/ API
。 Rails的预计,红宝石模块和类的名称相匹配的文件名的名称相匹配的子目录。在我们的例子中,为文件名的位置和目录微博:: API
应应用程序/ API /微博/ api.rb
。
因此,对于一个 API ::根
类中的正确位置实际上是应用程序/ API / API / root.rb
,不是 /app/api/root.rb
&MDASH;虽然说的是的在顶级命名空间的正确位置的一类,这就是为什么你给第二个示例(从 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类一起在自己的模块,但是,并将其移动到一个匹配的子文件夹应用程序/ 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失败,&QUOT;未初始化不断API&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!