为什么要使用葡萄用Rails失败,"未初始化不断API"? [英] Why does trying to use Grape with Rails fail with "uninitialized constant API"?

查看:179
本文介绍了为什么要使用葡萄用Rails失败,"未初始化不断API"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想有人解释这是在铁轨(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

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 for Twitter::API should be app/api/twitter/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;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆