주제

Ruby on Rails에서의 OG 이미지

FastOG의 구독 기반 Dynamic API를 사용하여 Ruby on Rails에서 OG 이미지를 생성할 수 있습니다. Dynamic API 구독을 통해 대시보드에서 API 키를 생성하세요. 무료 OG 이미지 테스터에서 미리보기를 확인한 후, HMAC 서명 URL을 사용하여 Rails 앱에서 동적 Open Graph 이미지를 렌더링할 수 있습니다.

빠른 시작

1. 서명자(signer) 서비스 생성

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) %>" />

전자상거래 예시

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