LoginSignup
3
3

More than 5 years have passed since last update.

AutodocのGrape用拡張機能追加するgemをつくった

Last updated at Posted at 2016-02-13

APIのドキュメント作りの便利なライブラリとして、r7kamuraさんが公開されているAutodocというgemがあります。
こちらは、テストケースからrequest, response, specの情報を使ってドキュメントを生成するというもので、実際の動作とドキュメントに差異がなくなるため、かなり重宝しております。

しかし、そのAPIのパラメータの定義部分をWeaksParameterによって定義された情報を介して取得していたので、
現在APIの作成に使っているGrapeのライブラリには対応しておりません。

そこでこちらをGrapeのparamsに対応できないものかなと思い、AutodocのGrape用のgemを作成しました。

作成したライブラリはこちらです。
kei-p/autodoc-grape

Grapeのparame から AutodocのParameter sectionを生成

Grapeでのパラメータは以下のように定義するようになっています。

params do
  requires :id, type: Integer, desc: 'Status id.'
end
get do
  Item.find(params[:id])
end

こちらから、ライブラリを使うと下記のようなmarkdownが得られます。

### Parameters
* id Integer (required)

仕組み

GrapeのAPIを介して通信すると、request.env["rack.routing_args"][:route_info]Grape::Routeが格納されており、こちらからparamsの定義情報を取得できます。

request.env["rack.routing_args"][:route_info]
=> #<Grape::Route:0x007fd309795ed0
 @options=
  {:params=>
    {"id"=>{:required=>true, :type=>"Integer"},
     "hash"=>{:required=>false, :type=>"Hash"},
     "hash[attr]"=>{:required=>true, :type=>"String"}},
   :prefix=>"api",
   :version=>nil,
   :namespace=>"/items",
   :method=>"GET",
   :path=>"/api/items/:id(.json)",
   :compiled=>/\A\/api\/items\/(?<id>[^\/.?]+)(?:\.json)?\Z/,
   :settings=>
    {:description=>
      {:params=>
        {"id"=>{:required=>true, :type=>"Integer"},
         "hash"=>{:required=>false, :type=>"Hash"},
         "hash[attr]"=>{:required=>true, :type=>"String"}}},
     :declared_params=>[:id, {:hash=>[:attr]}]}}>

この情報を使って、ドキュメントのパラメータ情報を作成しています。

最後に

Grapeのparamsの定義方法はいろいろあるのですが、このGrape::Route:paramsから取得できる情報に制限があるため現状は対応しているものは、

  • required
  • values
  • default
  • description

となっています。

今のところ自分のAPIでは事足りているのですが、regexpallow_blankといった他の定義にも対応できそうであれば、対応していきたいところです。

もし方法ご存知の方いましたら、PRよろしくお願いします!

3
3
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
3
3