LoginSignup
8
6

More than 5 years have passed since last update.

Grape で共通のネームスペースを切る

Last updated at Posted at 2013-11-18

namespace のブロックの中で mount すればよい。

versiontwitter/v1 のようなパスを書いても同じ URL が得られるが、 routes を表示したときに :version にまとめられてしまってわかりづらいので明示的に namespace を切ったほうがよい。

app.rb
require 'grape'

module Twitter
  module API
    class V1 < Grape::API
      version 'v1'
      format :json
    end
  end
end

module Twitter
  module API
    class V1 < Grape::API
      class Users < Grape::API
        get '/users' do
          { users: 1 }
        end
      end
    end
  end
end

module Twitter
  module API
    class V1 < Grape::API
      class PublicApi < Grape::API
        get '/pub' do
          { pub: 1 }
        end
      end
    end
  end
end

module Twitter
  module API
    class V1 < Grape::API
      class PrivateApi < Grape::API
        get '/priv' do
          { priv: 1 }
        end
      end
    end
  end
end

module Twitter
  module API
    class V1 < Grape::API
      namespace :v1 do
        mount Twitter::API::V1::Users

        namespace :public do
          mount Twitter::API::V1::PublicApi
        end

        namespace :private do
          mount Twitter::API::V1::PrivateApi
        end
      end
    end
  end
end
Rakefile.rb
require './app'

task :routes do
  Twitter::API::V1.routes.each do |r|
    method = r.route_method.ljust(10)
    path   = r.route_path
    puts "     #{method} #{path}"
  end
end
$ rake routes
     GET        /:version/v1/users(.:format)
     GET        /:version/v1/public/pub(.:format)
     GET        /:version/v1/private/priv(.:format)
8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6