Why am I getting “Unable to autoload constant” with Rails and grape?

核能气质少年 提交于 2019-12-04 17:25:37

问题


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)

My directory:

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

and the files:

#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

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


回答1:


Try either

  • Moving your API code's files from app/api to app/api/api, or

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

From Grape's documentation:

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.

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

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



来源:https://stackoverflow.com/questions/24319681/why-am-i-getting-unable-to-autoload-constant-with-rails-and-grape

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!