トピック

Ruby on Rails でのOG画像

FastOGのサブスクリプションベースのDynamic APIを使用して、Ruby on RailsでOG画像を生成します。Dynamic APIのサブスクリプション(ダッシュボードでAPIキーを作成)が必要です。無料のOG画像テスター(Free OG Image Tester)でプレビューし、HMAC署名付きURLを使用してRailsアプリから動的なOpen Graph画像をレンダリングします。

クイックスタート

1. サイナーサービス(signer service)の作成

ruby
# app/services/fastog_signer.rb
class QuickogSigner
  def self.generate_signed_og_url(params, options = {})
    base_url = options[:base_url] || ENV.fetch("FASTOG_BASE_URL", "https://fastog.com/api/v1/og")
    api_key = options[:api_key] || ENV.fetch("FASTOG_API_KEY")
    hmac_secret = options[:hmac_secret] || ENV.fetch("FASTOG_HMAC_SECRET")

    raise "Missing FASTOG_API_KEY or FASTOG_HMAC_SECRET" unless api_key && hmac_secret

    all = params.merge(key: api_key)
    pairs = all.flat_map do |k, v|
      Array(v).sort.map { |vv| "#{enc(k)}=#{enc(vv)}" }
    end
    canonical = pairs.sort.join("&")
    signature = OpenSSL::HMAC.hexdigest("SHA256", hmac_secret, "GET/api/v1/og\n#{canonical}")
    "#{base_url}?#{URI.encode_www_form(all.merge(s: signature))}"
  end

  def self.enc(s)
    s.to_s.gsub(/[^A-Za-z0-9\-._~]/) { |c| c.bytes.map { |b| "%%%02X" % b }.join }
  end
  private_class_method :enc
end

カスタムencを使う理由は? これはパーセントエンコーディングを大文字の16進数で行い、-._~の予約外文字だけを残します。そのため、スペースは%20になり、+にはなりません。これはサーバーのrawurlencodeと一致します。CGI.escapeやURI.encode_www_form_componentに置き換えると、どちらもスペースに対して+を出力します。その場合は、最初に.gsub('+', '%20')で正規化してください。

2. 設定

ruby
# config/application.rb
config.fastog = ActiveSupport::OrderedOptions.new
config.fastog.api_key = ENV.fetch("FASTOG_API_KEY", nil)
config.fastog.hmac_secret = ENV.fetch("FASTOG_HMAC_SECRET", nil)
config.fastog.base_url = ENV.fetch("FASTOG_BASE_URL", "https://fastog.com/api/v1/og")
bash
# .env
FASTOG_API_KEY=sk_your_full_api_key_here
FASTOG_HMAC_SECRET=your_64_char_hex_secret_here

コントローラー

ruby
# app/controllers/blog_controller.rb
class BlogController < ApplicationController
  def show
    @post = Post.find_by!(slug: params[:slug])

    @og_image_url = QuickogSigner.generate_signed_og_url(
      template: "blog",
      title: @post.title,
      subtitle: @post.excerpt,
      author: @post.author.name
    )
  end
end

ビュー

erb
<!-- app/views/blog/show.html.erb -->
<% content_for :head do %>
  <meta property="og:image" content="<%= @og_image_url %>" />
  <meta property="og:title" content="<%= @post.title %>" />
  <meta property="og:description" content="<%= @post.excerpt %>" />
<% end %>

<article>
  <h1><%= @post.title %></h1>
  <p><%= @post.excerpt %></p>
</article>

レイアウト

erb
<!-- app/views/layouts/application.html.erb -->
<head>
  <%= yield :head %>
</head>

ヘルパー

ruby
# app/helpers/fastog_helper.rb
module QuickogHelper
  def og_image_url(template:, **params)
    QuickogSigner.generate_signed_og_url({ template: template }.merge(params))
  end
end
erb
<!-- In view -->
<meta property="og:image" content="<%= og_image_url(template: 'blog', title: @post.title) %>" />

Eコマースの例

ruby
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
  def show
    @product = Product.find(params[:id])

    @og_image_url = QuickogSigner.generate_signed_og_url(
      template: "ecommerce",
      title: @product.name,
      price: @product.formatted_price,
      image: @product.image_url
    )
  end
end

ブログ記事の例

ruby
# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def show
    @user = User.find_by!(username: params[:username])

    @og_image_url = QuickogSigner.generate_signed_og_url(
      template: "blog",
      title: @user.name,
      subtitle: @user.bio,
      author: @user.name
    )
  end
end

API エンドポイント

ruby
# config/routes.rb
get "api/og", to: "api/og#generate"
ruby
# app/controllers/api/og_controller.rb
module Api
  class OgController < ApplicationController
    skip_before_action :verify_authenticity_token

    def generate
      title = params[:title]
      template = params[:template] || "default"

      unless title
        return render json: { error: "Missing title" }, status: :bad_request
      end

      og_image_url = QuickogSigner.generate_signed_og_url(
        template: template,
        title: title
      )

      render json: { ogImageUrl: og_image_url }
    end
  end
end

Turbo/Hotwire

erb
<!-- app/views/blog/_post.html.erb -->
<%= turbo_frame_tag "post_#{@post.id}" do %>
  <meta property="og:image" content="<%= og_image_url(template: 'blog', title: @post.title) %>" />
  <h2><%= link_to @post.title, blog_path(@post) %></h2>
<% end %>

よくある落とし穴

誤ったメッセージへの署名

❌ 誤り: "GET/api/v1/og#{canonical}" — 改行セパレーターが欠落しています。 ✅ 正しい: "GET/api/v1/og\n#{canonical}" — メソッド+パス、改行、その後に正規クエリ。

署名からkeyを除外する

❌ 誤り: コンテンツパラメータのみに署名し、後からURLにkeyを追加する。 ✅ 正しい: keyは正規クエリを構築する前にパラメータにマージされ、最終的なURLにも含まれます。

401 missing_signature / invalid_signature

missing_signature(401)は、URLにkeyまたはsが欠落していることを意味します。invalid_signature(401)は正規化が一致しなかったことを意味します — 署名メッセージ内の改行、両側で同じhmac_secret、そしてencがスペースを%20としてパーセントエンコードしていること(+ではないこと)を確認してください。

HMACシークレットの露出

フロントエンドのJavaScriptやクライアントサイドコードでFASTOG_HMAC_SECRETを公開しないでください。

完全なAPIリファレンス

無料で試す — サインアップ不要

動的OG画像を数秒でプレビューおよびテスト。

無料のOG画像テスターを開く

A BeCaSimulations site