Software Developer & Founder Torsten Bühl

Hi, I'm Torsten Bühl. I'm the founder of Foodlane, Company Signal, and Exceptiontrap (acquired by Scout APM). I build simple and straightforward products to help businesses do a better job. Learn more about them here

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

12 Jan 2015 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 it.

Let’s 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 here is 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 you can use any view 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

Any feedback? Just ping me at @tbuehl.