【问题标题】:rails - grape api error calling classes for version-ed apirails - 版本化 api 的葡萄 api 错误调用类
【发布时间】:2013-11-30 11:08:42
【问题描述】:

我正在尝试为版本化 api(rails-grape) 调用特定于版本的类并得到错误

 NameError (uninitialized constant API::V1::XMLResponses):
09:23:36 web.1     |   app/api/v1/base.rb 

我的目录结构

app/
  api/
    v1/
      xmlresponses/
         phonebook.rb   
      api.rb
    v2/
      xmlresponses/ 
      api.rb
    api.rb

api.rb 需要'v1/base.rb' 需要'v2/base.rb'

module  API
  class Base < Grape::API
    mount API::V1 => '/'
    mount API::V2 => '/v2/'
  end
end

在 v1/base.rb 中,我可以访问此版本 api 的类

V1::XMLResponses::Phonebook::getall()

请告诉我为什么会出现这个错误?

感谢您的回答,我创建了一个简单的应用程序来演示它是如何完成的https://github.com/Asmmund/grape_versioning

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 versioning grape-api


    【解决方案1】:

    这可能只是您的模块结构有问题。 也许缺少require

    我会这样写:

    /foo
      v1/
      |_ responses/
      |  |_ time.rb
      |
      |_ base.rb
    
      v2/
      |  
      |_ base.rb
    
      api.rb
      config.ru
    

    文件:

    # api.rb`
    
    require 'grape'
    require './v1/base.rb'
    require './v2/base.rb'
    
    module FooBar
      module API
        class Base < Grape::API
          mount API::V1 => '/'
          mount API::V2 => '/v2/'
        end
      end
    end
    
    
    # v1/base.rb
    require_relative './responses/time.rb'
    
    module FooBar
      module API
        class V1 < Grape::API
          get 'foo' do
            "foo"
          end
          get 'time' do
            API::Responses::Time.api_time
          end
        end
      end
    end
    
    # v1/responses/time.rb
    module FooBar
      module API
        module Responses
          class Time
            def self.api_time
              "API time"
            end
          end
        end
      end
    end
    
    # v2/base.rb
    module FooBar
      module API
        class V2 < Grape::API
          get 'bar' do
            "bar"
          end
        end
      end
    end
    

    然后在config.ru

    # config.ru
    require './api.rb'
    run FooBar::API::Base
    

    运行:

    thin start
    ...
    curl 0.0.0.0:3000/foo
    => foo
    curl 0.0.0.0:3000/v2/bar
    => bar
    curl 0.0.0.0:3000/time
    => API time
    

    【讨论】:

    • 感谢您的回答!很有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多