TypeStructが良い感じ
Gemfile
以下のように定義
lib/structure.rbというファイル名で作成
require 'type_struct/ext'
module Structure
using TypeStruct::Union::Ext
# 埋め込みHTML
Embed = TypeStruct.new(
html: String,
)
# 動画オブジェクトの構造体
Movie = TypeStruct.new(
id: Integer,
name: String,
description: description: TypeStruct::Union.new(String, nil), // NULLを許容する
embed: Embed // 別の構造体を指定できる
)
end
以下のようにAPIの結果を構造体に保存したりできる
def self.channel_videos(channel_id)
response = sendRequest("https://hogehoge.jp/api/v1/movie", 'GET')
response["data"].map{ |d| Structure::Movie.from_hash(d) }
end
NULLを許容するときの書き方
description: TypeStruct::Union.new(String, nil)