Skip to content

Instantly share code, notes, and snippets.

@zealot128
Created December 16, 2011 21:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zealot128/1488180 to your computer and use it in GitHub Desktop.
Save zealot128/1488180 to your computer and use it in GitHub Desktop.
Easy XML Sitemap with rails (little work involved anyway)

Sitemap XML with Rails

Rails is too custom, to provide a generic sitemap as a gem for any situation. But it ist not too hard anyway! Here is a frame how to make one:

rails g controller sitemap

add the index action to sitemap-controller:

class SitemapController < ApplicationController
  def index
    respond_to do |f|
      f.xml
    end
  end
end

add the route (bonus points for restricting the format to xml)

# config/routes
  ....
  get "sitemap", :controller => :sitemap, :action => :index

Generate the sitemap with builder:

# app/views/sitemap/index.xml.builder 
xml.instruct!
xml.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") do
  # whatever logic your app has, e.g. static pages:
  @pages.each do |page|
    xml.url do
      xml.loc page_url(page)
      xml.lastmod page.updated_at.to_date.to_s(:db)
      xml.changefreq "monthly"
      xml.priority 0.3
    end
  end
end

Do not forget to add the sitemap to your robots.txt

Sitemap: http://www.mydomain.de/sitemap.xml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment