@r7kamuraさん作のJsonWorldでJSON Schemaを生成できるモデルを作成します。
準備
JsonWorldについては@r7kamuraさん本人による下記のエントリをチェック
JsonWorldでモデルからJSON Schemaを生成する
サンプル
仕様
Railsのscaffoldで以下のモデルを作成しました。
attr | type |
---|---|
People#name | String |
People#age | Integer |
Web キャプチャ
Resourceクラス作成
class PersonResource
include JsonWorld::DSL
property(
:id,
description: 'person id',
example: 1,
type: Integer,
)
property(
:name,
example: "tanaka",
type: String,
)
property(
:age,
example: 34,
type: Integer,
)
attr_reader :id, :name, :age
# @param [Person] person
def initialize(person)
@id = person.id
@name = person.name
@age = person.age
end
end
Controllerの修正
show を変更してみます
- Before
scaffold直後の状態は下記です。
# GET /people/1
# GET /people/1.json
def show
end
- After
Resourceクラスを呼び出すように変更します。
# GET /people/1
# GET /people/1.json
def show
respond_to do |format|
format.html
format.json { render json: PersonResource.new(Person.find(params[:id])) }
end
end
動作確認
- curl で呼び出し
% curl http://172.16.33.100:3000/people/1.json
{"id":1,"name":"tanaka","age":23}
% curl GET http://172.16.33.100:3000/people/2.json
{"id":2,"name":"suzuki","age":42}
- rails console でJSON-Schemaを確認
> puts PersonResource.to_json_schema
{
"properties": {
"id": {
"description": "person id",
"example": 1,
"type": "integer"
},
"name": {
"example": "tanaka",
"type": "string"
},
"age": {
"example": 34,
"type": "integer"
}
},
"required": [
"id",
"name",
"age"
]
}