[RUBY] [Rails] Set Twitter OGP

There is no Gem.

I referred to the following article for the meta tag required to display Twitter's OGP. [2020 Edition] What is a Twitter card? Summary of usage and setting method

Implementation

app/helper/application_helper.rb


def full_title(page_title = '')
  base_title = 'MC BATTLE CHANNEL'
  if page_title.empty?
    base_title
  else
    "#{page_title} | #{base_title}"
  end
end

def full_url(path)
  domain = if Rails.env.development?
             'http://0.0.0.0:3000'
           else
             'https://mcbattle-ch.jp'
           end
  "#{domain}#{path}"
end

erb:app/views/layouts/application.html.erb


<head>
  <!-- ogp -->
  <meta name="twitter:card" content="summary_large_image" />
  <meta name="twitter:site" content="@McBattleChannel" />
  <meta property="og:title" content="<%= full_title(yield(:title)) %>" />
  <meta property="og:url" content="<%= request.url %>" />
  <meta property="og:description"
    content="<%= content_for?(:description) ? yield(:description) : 'This is a comprehensive site for MC battles.' %>" />
  <meta property="og:image"
    content="<%= content_for?(:image_url) ? yield(:image_url) : full_url('/assets/other/ogp_default.png') %>" />

erb:app/views/hoge/fuga.html.erb


<%= content_for(:title, "Title of this individual page!") %>
<%= content_for(:description, "Description of this individual page!") %>
<%= content_for(:image_url, full_url("assets/mc/hoge.img")) %>

If it is not displayed in the production environment

If you see it in a staging environment but not in a production environment, it's probably due to the OGP cache. If you use the following "Tool to check the display of OGP", the cache will be cleared at the same time as checking the display. https://cards-dev.twitter.com/validator

Recommended Posts

[Rails] Set Twitter OGP
[rails] Set validation
Steps to set a favicon in Rails
[Rails 6] Implementation of SNS (Twitter) sharing function
Rails6 OmniAuth twitter Authentication Email conditional branch