Skip to content

Instantly share code, notes, and snippets.

@heratyian
Last active December 11, 2023 17:35
Show Gist options
  • Save heratyian/149c1b68a63741a44b7b7610816b89f8 to your computer and use it in GitHub Desktop.
Save heratyian/149c1b68a63741a44b7b7610816b89f8 to your computer and use it in GitHub Desktop.
Setup meta tags in your rails app
  1. Add gem "meta-tags" to your gemfile meta-tags

  2. Setup some default meta tags

app/helpers/application_helper.rb

module ApplicationHelper
  def default_meta_tags
    {
      site: "My Awesome App",
      image: image_url('your_image_name.jpg'),
      description: "This is the best app ever",
      og: {
        title: "My Awesome App",
        image: image_url('your_image_name.jpg'),
        description: "This is the best app ever",
        site_name: "My Awesome App"
      }
      # TODO: add twitter tags
    }
  end
end

app/views/layouts/application.html.erb

<!DOCTYPE html>
<html>
  <head>
    ...
    <%= display_meta_tags(default_meta_tags) %>
    ...
  </head>

  <body>
    <%= yield %>
  </body>
</html>

For any page that you want to set custom meta tags, you'll need to set meta tags in the action.

class MyController < ApplicationController
  def show
    ...
    set_meta_tags @record
    ...
  end
end

You just need to implement a to_meta_tags method in your model. I like to keep this logic in a concern so it's all together.

module MyModel::Metataggable
  extend ActiveSupport::Concern
  
  include ApplicationHelper # we need this so we can extend default meta tags

  def to_meta_tags
    my_model_tags = {
      title: 'my title',
      description: 'description',
      keywords: 'add keywords',
      image: image_url,
      og: {
        title: 'my title',
        image: image_url,
        description: 'description',
        site_name: "My Awesome App"
      },
    }

    default_meta_tags.merge(my_model_tags)
  end
end

Then just include this concern in your model.

We can use a meta tags preview service to test out our URLs metatags.io

We can use [ngrok] to easily create a public url for our localhost. d Install ngrok on macOS using Homebrew brew install --cask ngrok

Run ngrok http [port number] in your terminal (most localhost defaults to port 3000)

This will generate a forwarding URL you can use in metatags.io for testing. Forwarding https://d46c-38-32-143-226.ngrok-free.app -> http://localhost:3000

(you can also share this url with friends while developing the app on your machine)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment