Why does mounting a route in Rails fail with “uninitialized constant API”?

心已入冬 提交于 2019-12-22 06:56:46

问题


I am working on an app that includes an API that is using the grape gem.

Here is my Root Class:

module API
  class Root < Grape::API
    rescue_from :all do |e|
      Rack::Response.new(
        [ "Error: #{e.message}" ],
        500,
        { "Content-type" => "text/error" }
      ).finish
    end

    prefix "api"
    version 'v1', using: :path
    format :json
    error_format :json

    mount ::API::ServiceRequests
  end
end

Here is how I am mounting it in routes:

mount API::Root => '/'

The error I am receiving is: routes.rb:45:inblock in ': uninitialized constant API (NameError)`

The files are structured like app/api/root.rb and I have this bit of code in my application.rb to load in the files:

config.paths.add File.join('app', 'api'), glob: File.join('**', '*.rb')
config.autoload_paths += Dir[Rails.root.join('app', 'api', '*')]

回答1:


Try moving your API code's files from app/api to app/api/api.

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.



来源:https://stackoverflow.com/questions/24833131/why-does-mounting-a-route-in-rails-fail-with-uninitialized-constant-api

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