Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google sitemap files for Rails projects

Is there an easy way to create a sitemaps file for Rails projects? Especially for dynamic sites (such as Stack Overflow for example) there should be a way to dynamically create a sitemaps file. What is the way to go in Ruby and/or Rails?

What would you suggest? Is there any good gem out there?

like image 750
z3cko Avatar asked Jan 16 '10 12:01

z3cko


People also ask

How do I add a sitemap in rails?

Run the script in Ruby prompt: ruby mysitemap. rb URL, substituting the URL for the sitemap. The sitemap code snippet may require changes depending on the node tag names. Validate the sitemap & submit it to Google: Register your site on Google Webmaster Tools.

Does Google use sitemap XML?

An XML sitemap is a file that lists a website's essential pages, making sure Google can find and crawl them all. It also helps search engines understand your website structure. You want Google to crawl every important page of your website.


2 Answers

Add this route towards the bottom of your config/routes.rb file (more specific routes should be listed above it):

map.sitemap '/sitemap.xml', :controller => 'sitemap' 

Create the SitemapController (app/controllers/sitemap_controller):

class SitemapController < ApplicationController   layout nil    def index     headers['Content-Type'] = 'application/xml'     last_post = Post.last     if stale?(:etag => last_post, :last_modified => last_post.updated_at.utc)       respond_to do |format|         format.xml { @posts = Post.sitemap } # sitemap is a named scope       end     end   end end 

—As you can see, this is for a blog, so is using a Post model. This is the HAML view template (app/views/sitemap/index.xml.haml):

- base_url = "http://#{request.host_with_port}" !!! XML %urlset{:xmlns => "http://www.sitemaps.org/schemas/sitemap/0.9"}   - for post in @posts     %url       %loc #{base_url}#{post.permalink}       %lastmod=post.last_modified       %changefreq monthly       %priority 0.5 

That's it! You can test it by bringing up http://localhost:3000/sitemap.xml (if using Mongrel) in a browser, or perhaps by using cURL.

Note that the controller uses the stale? method to issue a HTTP 304 Not Modified response if there are no new posts sinces the sitemap was last requested.

like image 143
John Topley Avatar answered Oct 02 '22 17:10

John Topley


Now for rails3, it is better off using full-featured sitemap_generator gem.

like image 41
Ninad Avatar answered Oct 02 '22 16:10

Ninad