Dynamically generating a sitemap for Google
Written by Robin Fisher in 344 words
25
Feb
One of the issues I encountered with my previous Rails application was adding a sitemap to the root directory so that I could use Google’s Webmaster Tools. As I was not under a deadline for sparky, I was able to dedicate some time to the issue.
I figured the easiest way to create the sitemap was to use Rails’ built-in XML builder to dynamically generate the sitemap when requested by Google. This has the advantage of picking up every new blog entry.
First was the controller. In order to keep everything segregated and RESTful, I created a sitemaps controller with one action:
class SitemapController < ApplicationController
def sitemap
@entries = Entry.find(:all)
@jobs = Job.find(:all)
respond_to do |format|
format.xml { render :layout => false }
end
end
end
I retrieve all the dynamic information in the controller, which is then passed to the view file. Creating the view was a lot of trial and error, particularly in terms of getting it to match the sitemap specification. Here though is the final view file split into chunks for commentary purposes.
base_url = "http://www.capturedsparks.com" xml.instruct!ml, :version=>"1.0" xml.tag! 'urlset', "xmlns" => "http://www.sitemaps.org/schemas/sitemap/0.9" do
This sets the header information in the resulting xml file as required by the sitemap specification.
for entry in @entries do
xml.tag! 'url' do
xml.tag! 'loc', "#{base_url}#{generate_url(entry)}"
xml.tag! 'lastmod', entry.updated_at.strftime("%Y-%m-%d")
xml.tag! 'changefreq', 'monthly'
xml.tag! 'priority', '0.8'
end
end
This iterates through the blog entries, which are contained in the @entries variable set in the controller. This is then followed with identical code for the @jobs variable.
For each of the static pages (including the blog and job indexes), I use the following code assigning them higher priorities than the individual blog and job entries.
xml.tag! 'url' do
xml.tag! 'loc', "http://www.capturedsparks.com/about/"
xml.tag! 'changefreq', 'monthly'
xml.tag! 'priority', '1'
end
The resulting xml file can be seen here.