AB Lab

abgata20000 blog.

Grape を Rails4で利用する場合の注意点

参考サイト

なんかいろいろとはまってしまったので備忘録

file pathを追加する

config/application.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
module TestApp
  class Application < Rails::Application
    ...
    config.paths.add "app/api", glob: "**/*.rb"
    config.autoload_paths += Dir["#{Rails.root}/app/api/*"]
    ...
  end
end
routes.rbにmountするコードを一行追加

TestApp::Application.routes.draw do
  mount TestAPI => 'api'
  ...
end

流れ

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$ rails new test-app
$ cd test-app
$ vi Gemfile
# + gem 'grape', :git => "https://github.com/intridea/grape.git"
$ bundle install
$ mkdir app/api
$ vi app/api/test_api.rb
$ vi app/api/api_v1.rb
$ mkdir app/api/v1
$ vi app/api/ping.rb
$ vi config/application.rb
$ vi config/routes.rb
$ bundle exec rails s
$ open http://localhost:3000/api/v1/hello
files
app/api/test_api.rb
1
2
3
class TestAPI < Grape::API
  mount API_V1
end
app/api/api_v1.rb

v1/以下のclassをmountする

1
2
3
4
class API_V1 < Grape::API
  prefix 'v1' # とりあえずprefixだけつけている
  mount V1::Ping
end
app/api/v1/ping.rb
1
2
3
4
5
6
7
8
9
module V1
  class Ping < Grape::API
    format :json

    get :hello do
      {hello: "world"}
    end
  end
end

ベースのクラスをモジュールで囲うと何故かサブクラス呼び出せない

不思議だ。

要調査