Create a simple Sitemap with Rails and Ping it to Google with Rake

You just finished that new blog post or optimized your copy. And Google should know about it. Now you can wait for Google to fetch the changes – or just ping them.

We decide to ping Google. Our ingredients are a Rake task and a simple model class – this gets us rake sitemap:ping .

The Rake task and model

We use httparty for the HTTP request, so add it to the Gemfile

# Gemfile gem 'httparty'

# app/models/sitemap.rb require 'httparty' class Sitemap include HTTParty def initialize(sitemap_url = "https://exceptiontrap.com/sitemap.xml") @sitemap_url = sitemap_url @google_ping_url = "http://www.google.com/webmasters/sitemaps/ping" end def ping puts "Ping Google with: #{@sitemap_url}" self.class.get @google_ping_url, query: { sitemap: @sitemap_url } end end

# lib/tasks/sitemap.rake namespace :sitemap do desc 'Ping Google to let them know something has changed.' task ping: :environment do puts Sitemap . new . ping end end

Just change the sitemap_url 's default value and you're fine. In case that you have multiple sitemaps, you can call Sitemap.new with your URL. But you should use index sitemaps for that.

Implement a simple Sitemap

Do you also need a simple sitemap for your Rails app? There are several gems available, but I'll show you a simple and flexible solution.

# config/routes.rb get "sitemap" => "sitemap#show" , format: :xml , as: :sitemap

# app/controllers/sitemap_controller.rb class SitemapController < ApplicationController def show # e.g. @articles = Blog::Article.all end end

# app/views/sitemap/show.xml.erb <?xml version="1.0" encoding="UTF-8"?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd"> <url> <loc><%= root_url %></loc> <changefreq>daily</changefreq> </url> <url> <loc>https://exceptiontrap.com/de</loc> <changefreq>daily</changefreq> </url> </urlset>

It's just an ERb template. So feel free to use any URL helpers to create the URLs.

Certainly, you can do more dynamic stuff, like:

# app/views/sitemap/show.xml.erb <% @articles.each do |article| %> <url> <loc><%= blog_article_url(article) %></loc> <changefreq>daily</changefreq> </url> <% end %>

Let me know

Did this work for you or do you use another approach? Just ping me at @tbuehl

This is a Nuts & Bolts Series post – join the mailing list below to get more tips & tricks.

← Back to Overview