【问题标题】:Grape::API – Unable to autoload constant Base, expected /app/api/v1/base.rb to define it (LoadError)Grape::API – 无法自动加载常量 Base,需要 /app/api/v1/base.rb 来定义它(LoadError)
【发布时间】:2014-09-10 11:29:10
【问题描述】:

我需要一些帮助来启动 Grape::API 并使用 Rails 4 运行。 即使puts 告诉我该类已加载,我也会得到Unable to autoload constant Base。 我究竟做错了什么?

app/api/api.rb

class API < Grape::API
  prefix 'api'
  format :json
  default_format :json
  mount V1::Base   # Everything loads perfectly until I add this line.
end

app/api/v1/base.rb

module V1
  class Base < API
    puts "=== DEBUG - in Base"
    version 'v1', using: :path, vendor: 'orwapp', cascade: false

    mount Users

  end
end

$ rspec 规范/api

12:58:29 - INFO - Run all
12:58:29 - INFO - Running all specs
=== DEBUG - in Base
/dependencies.rb:481:in `load_missing_constant': 
Unable to autoload constant Base,
 expected /Users/martins/Work/myapp/app/api/v1/base.rb to define it (LoadError)
        from /Users/martins/Work/myapp/app/api/api.rb:9:in `<class:API>'
        from /Users/martins/Work/myapp/app/api/api.rb:3:in `<top (required)>'

spec/api/users_spec.rb

describe 'GET /api/v1/users/:id', focus: true do
  let(:user) { Fabricate :user }

  it 'returns that specific user' do
    get "/api/v1/users/#{ user.id }", {}, https_and_authorization
    response.status.should eq 200
    parse_response_for(:user)['email'].should eq user.email
  end
end

我正在使用的版本

$ ack grape Gemfile.lock
      remote: git://github.com/intridea/grape.git
        grape (0.9.1)
        grape-entity (0.4.4)
        grape-swagger (0.8.0)
          grape
          grape-entity

【问题讨论】:

    标签: ruby-on-rails grape-api


    【解决方案1】:

    尝试让Base 继承自Grape::API 而不是API

    module V1
      class Base < Grape::API
      ...
    

    通过让它从API 继承,你正在创建一个循环依赖:解释器在知道API 的定义之前无法知道V1::Base 的定义,但为此它首先需要知道V1::Base的定义等等。

    【讨论】:

    • 感谢您的建议。不过,这并没有什么区别。我对循环依赖没有任何问题。我得到的错误是 无法自动加载常量 Base
    【解决方案2】:

    更改为 mount ::V1::Base 已修复。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-05
      • 2019-01-28
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多