This is a Nuts & Bolts Article – Tips & Tricks for Developers

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

by Torsten Bühl

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 = "")
    @sitemap_url = sitemap_url
    @google_ping_url = ""

  def ping
    puts "Ping Google with: #{@sitemap_url}"
    self.class.get @google_ping_url, query: { sitemap: @sitemap_url }
# lib/tasks/sitemap.rake
namespace :sitemap do
  desc 'Ping Google to let them know something has changed.'
  task ping: :environment do

Just change the sitemap_url's default value and you're fine. In case that you have multiple sitemaps, you can call 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
# app/views/sitemap/show.xml.erb
<?xml version="1.0" encoding="UTF-8"?>
    <loc><%= root_url %></loc>

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| %>
    <loc><%= blog_article_url(article) %></loc>
<% 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

Try our simple and powerful
application error tracking