LoginSignup
1
3

More than 5 years have passed since last update.

JsonWorldでrootがarrayなjson schemaを作る

Last updated at Posted at 2015-10-08

as_json_schemaをoverrideして無理矢理作れる。

module Api
  module Resources
    class User
      include JsonWorld::DSL

      property(
        :id,
        type: Integer,
      )
      property(
        :screen_name,
        type: String,
      )
    end
    class Users
      include JsonWorld::DSL

      property(
        :users,
        type: Array,
        items: {
          type: Api::Resources::User
        }
      )

      attr_reader :users

      # @param [Api::Resources::User] users
      def initialize(users)
        @users = users
      end

      def self.as_json_schema
        super[:properties][:users]
      end

      def as_json(options = {})
        super(options)["users"]
      end
    end
  end
end

puts Api::Resources::User.to_json_schema
# =>
#{
#  "properties": {
#    "id": {
#      "type": "integer"
#    },
#    "screen_name": {
#      "type": "string"
#    }
#  },
#  "required": [
#    "id",
#    "screen_name"
#  ]
#}

puts Api::Resources::Users.to_json_schema
# =>
#{
#  "items": {
#    "properties": {
#      "id": {
#        "type": "integer"
#      },
#      "screen_name": {
#        "type": "string"
#      }
#    },
#    "required": [
#      "id",
#      "screen_name"
#    ]
#  },
#  "type": "array"
#}

:tada:

参考

JsonWorldでモデルからJSON Schemaを生成する - Qiita

json_worldの全体的な使い方はこれを見る

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