为什么我得到“无法自动加载常量"?用 Rails 和葡萄? [英] Why am I getting "Unable to autoload constant" with Rails and grape?

查看:49
本文介绍了为什么我得到“无法自动加载常量"?用 Rails 和葡萄?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为 Android 应用编写 API.搜索时,我找到了{grape}.我正在关注本教程,但启动时遇到问题Rails 服务器:

I want to do an API for an Android app. When searching, I found {grape}. I'm following this tutorial, but I have a problem launching the Rails server:

=> Booting WEBrick
=> Rails 4.0.2 application starting in development on http://0.0.0.0:80
=> Run `rails server -h` for more startup options
=> Ctrl-C to shutdown server
Exiting
C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-4.0.2/lib/act
ive_support/dependencies.rb:464:in `load_missing_constant': Unable to autoload c
onstant Usuarios, expected C:/Sites/appCerca/app/api/v1/usuarios.rb to define it
 (LoadError)

我的目录:

app
..api
....api.rb
....v1
......root.rb
......usuarios.rb

和文件:

#application.rb
module AppCerca
  class Application < Rails::Application
      config.paths.add "app/api", glob: "**/*.rb"
       config.autoload_paths += Dir["#{Rails.root}/app/api/*"]
  end
end

#routes.rb
AppCerca::Application.routes.draw do
  mount API::Root => '/'
  [...]

#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
    module V1
        class Root < Grape::API
            mount API::V1::Usuarios
        end
    end
end

# app/api/v1/usuarios.rb
module API
    module V1
        class Usuarios < Grape::API
            version 'v1'
            format :json

            resource :usuarios do
                desc "Return list of authors"
                get do
                    Usuario.all
                end
            end
        end
    end
end

为什么我会收到这个错误?我使用的是 Ruby 1.9.3p484 和 Rails-4.0.2.

Why am I getting this error? I am using Ruby 1.9.3p484 and Rails-4.0.2.

推荐答案

尝试其中一个

  • 将您的 API 代码文件从 app/api 移动到 app/api/api,或

将您的 API 类移出API 模块(即删除所有 module API 行及其相应的 end 语句).

Moving your API classes outside the API module (i.e. deleting all the module API lines and their corresponding end statements).

来自 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 for Twitter::API should be app/api/twitter/api.rb.

因此,API::Root 类的正确位置实际上是 app/api/api/root.rb.

Thus the correct location for your API::Root class would actually be app/api/api/root.rb.

通过此更改,您的代码可以在 Rails 4.0.2 上正常运行.

With this change your code starts and works fine for me on Rails 4.0.2.

这篇关于为什么我得到“无法自动加载常量"?用 Rails 和葡萄?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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