Question

I'm trying to call version specific classes for versioned api(rails-grape) and get error

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

my directory structure

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

api.rb require 'v1/base.rb' require 'v2/base.rb'

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

in v1/base.rb i access classes for this version of api

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

Please, could you tell me why do i get this error?

Thanks for your answer, I've created simple app that demonstrates how it's done https://github.com/Asmmund/grape_versioning

Was it helpful?

Solution

It could be simply something wrong in your module structure. Maybe a missing require.

I would write something like this:

/foo
  v1/
  |_ responses/
  |  |_ time.rb
  |
  |_ base.rb

  v2/
  |  
  |_ base.rb

  api.rb
  config.ru

The files:

# 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

Then in config.ru

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

Run with:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top