Web Development

In the world of SEO, sitemaps are a big thing. Sitemaps help search engines when crawling your site. It gives some helpful information about web pages on your site like, frequency of changes, priorities, last modified time and the actual URL. Here I am gonna post how you could generate a sitemap for your Ruby on Rails website.

Assumptions

  • The post assumes that you already have data on your Ruby on Rails application and just want to have a sitemap.
  • The post assumes that you have a Post model. You can change this on your code

Make a Route

Unless you are using a SitemapController for anything, you would want to use something already available. In my case, the HomeController.

get 'sitemap', to: 'home#sitemap'

Retrieve the data

We will be using the xml format

  def sitemap
    @posts = Post.all
    respond_to do |format|
      format.xml
    end
  end

Create a View file

Create a file in the home folder named, sitemap.xml.builder and paste the following.

xml.instruct!
xml.urlset xmlns: "http://www.sitemaps.org/schemas/sitemap/0.9" do
  @posts.each do |post|
    xml.url do
      xml.loc post_url(post)
      xml.lastmod post.updated_at.strftime('%Y-%m-%d')
      xml.changefreq 'daily'
      xml.priority '0.5'
    end
  end
end

Voila! A Sitemap generated by Ruby on Rails

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>
http://gistpages.com/posts/how_to_turn_off_autocomplete_on_forms
</loc>
<lastmod>2015-11-02</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>
http://gistpages.com/posts/how-to-zip-an-entire-folder-in-ubuntu
</loc>
<lastmod>2015-11-03</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>
http://gistpages.com/posts/expiring-rails-sessions-with-devise
</loc>
<lastmod>2015-11-03</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>
http://gistpages.com/posts/permanent-redirect-urls-with-nginx
</loc>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>http://gistpages.com/posts/hashing-data-with-ruby</loc>
<lastmod>2015-11-04</lastmod>
<changefreq>daily</changefreq>
<priority>0.5</priority>
</url>
</urlset>