Easy Google Sitemap with REST in Rails
February 21st, 2007
Google Sitemaps are an effective way to let Google know which pages of your website are available for indexing. Though they go to great lengths to point out that submitting a sitemap is only a suggestion, and not a command, Google does use your sitemap to provide insights into how your website is being indexed and found by web searchers.
Here’s how I added a Google Sitemap for Moral Metric in two shakes of a lamb’s tail.
First, I made sure that my HomeController was defined as a resource in my routes.rb file:
map.resource :home |
My HomeController is very sparse – it only has one public method: index. I wanted to have my application return XML when Google asked for XML, so rather than adding a new method, I used Rails’ respond_to blocks:
1 2 3 4 5 6 7 |
def index respond_to do |format| @things = Thing.find(:all) format.html {} format.xml {render :partial => "sitemap", :layout => false} end end |
Easy enough. Then I created an RXML file in app/views/home/sitemap.rxml. Here I constructed my sitemap code according to Google’s Sitemap Protocol, which is very simple. The file looks something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
xml.instruct! xml.urlset "xmlns" => "http://www.google.com/schemas/sitemap/0.84" do # Provide your site's homepage xml.url do xml.loc "http://www.moralmetric.com/" xml.lastmod w3c_date @articles.last.updated_at xml.changefreq "hourly" xml.priority "1.0" end # You can hand-specify important sub-sections of your site xml.url do xml.loc "http://www.moralmetric.com/things" xml.lastmod w3c_date @things.last.updated_at xml.changefreq "daily" xml.priority "0.9" end # You can iterate over items in your site, providing a link to each page @things.each do |thing| xml.url do xml.loc thing_url(thing) xml.lastmod w3c_date thing.updated_at xml.changefreq "daily" end end |
The w3c_date helper method is a convenience method from Codeism, to whom I also owe thanks for the inspiration for this technique.
That’s it! Now, going to /home.xml will pull up your newly minted XML format Google sitemap.
You could also ping Google each time something new is posted. See here.
Resources: