Torsten Bühl
Software Engineer & Founder

Hi, I'm Torsten. I am the founder of Foodlane, Company Signal, and Exceptiontrap (acquired by Scout APM). I strive to build simple and beautiful software products that people love to use. Learn more about them here

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

Torsten Bühl

You just finished that new blog post or optimized your website 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 will get get us rake sitemap:ping.

Rake task and model

We use httparty for the HTTP request, so let’s 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 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
  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 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| %>
  <url>
    <loc><%= blog_article_url(article) %></loc>
    <changefreq>daily</changefreq>
  </url>
<% end %>

Let me know

Any feedback? Just ping me at @tbuehl.