Skip to content

Instantly share code, notes, and snippets.

@rummelonp
Created March 20, 2014 08:03
Show Gist options
  • Save rummelonp/9659267 to your computer and use it in GitHub Desktop.
Save rummelonp/9659267 to your computer and use it in GitHub Desktop.
Grape でファイル分ける
# app/api/users.rb
class Users < Grape::API
format :json
get do
# returns users
end
get ':id' do
# returns user
end
# nested resources
route_param :user_id do
mount Users::Books
end
end
# app/api/users/books.rb
class Users::Books < Grape::API
resource :books do
get do
# return user books
end
get ':id' do
# return user book
end
end
end
# config/routes.rb
SomeApp::Application.routes.draw do
mount Users => '/api/users'
end
# config/application.rb
module SomeApp
class Application < Rails::Application
config.autoload_paths += %W(#{config.root}/app/api)
end
end
@rummelonp
Copy link
Author

$ curl some_app/api/users
[{"id":1,"name":"user1"},{"id":2,"name":"user2"}]

$ curl some_app/api/users/1
{"id":"1","name":"user1"}

$ curl some_app/api/users/1/books
[{"id":1,"name":"user1_book1"},{"id":2,"name":"user1_book2"}]

$ curl some_app/api/users/1/books/1
{"id":"1","name":"user1_book1"}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment