SoSoraEndo2025年9月2日2 min143 字
問題
Rails 側で JSON-LD を組み立てるとき、生 Hash で書くとタイポが命取り。@type を @Type と書いても誰も検出してくれない。
dry-struct で構造を作る
class ArticleLd < Dry::Struct
attribute :@type, Types::String.constrained(eql: 'Article')
attribute :headline, Types::String
attribute :author, Types::Hash
attribute :datePublished, Types::String
attribute :image, Types::String
end
使う側は構造を受け取るだけ。
ArticleLd.new(
@type: 'Article',
headline: post.title,
author: { @type: 'Person', name: post.author.name },
datePublished: post.published_at.iso8601,
image: ogp_image_url(post)
).to_h
メリット
- スキーマ違反は
Dry::Struct::Errorで即落ちる - 必須項目の欠落も同様
- フロントの
<script type="application/ld+json">出力までを 1 関数で
まとめ
JSON-LD は「外部から検証されない」ぶん、内部で型を持たせる価値が高い領域。Rich Result Test での失敗を、出力前に潰せます。