AetherEchoesEngineering
Vol.042025年9月2日
Engineering#00122 min143145 view

JSON-LD を Rails で型安全に組み立てる

schema.org の JSON-LD を埋めるとき、Hash を直書きすると型がない。dry-struct で構造を持たせる小さな工夫。

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 での失敗を、出力前に潰せます。

Tags

Reaction

Share

X (Twitter)