This post shows how to make sitemap.xml for your web site. The sitemap will be accessible by URL http://mysite.com/sitemap.xml
Myrails::Application.routes.draw do
get "/sitemap.xml" => "sitemap#index", :format => "xml", :as => :sitemap
end
# app/controllers/sitemap_controller.rb
class SitemapController < ApplicationController
def index
respond_to do |format|
format.xml
end
end
end
XML will be generated using XML builder. Create a view file 'sitemap/index.xml.builder' where you can use xml builder methods.
# app/views/sitemap/index.xml.builder
base_url = "http://#{request.host_with_port}/"
xml.instruct! :xml, :version=>"1.0"
xml.tag! 'urlset', 'xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9', 'xmlns:image' => 'http://www.google.com/schemas/sitemap-image/1.1', 'xmlns:video' => 'http://www.google.com/schemas/sitemap-video/1.1' do
xml.url do
xml.loc base_url
end
xml.url do
xml.loc base_url+'about.html'
end
xml.url do
xml.loc base_url+'contacts.html'
end
end
To do some refactoring let's prepare some data in controller for static pages and dynamic pages (like products).
controller:
class SitemapController < ApplicationController
def index
@pages = ['', 'about.html', 'contacts.html']
@products = Product.all
respond_to do |format|
format.xml
end
end
end
change view:
# app/views/index.xml.builder
base_url = "http://#{request.host_with_port}/"
xml.instruct! :xml, :version=>"1.0"
xml.tag! 'urlset', 'xmlns' => 'http://www.sitemaps.org/schemas/sitemap/0.9', 'xmlns:image' => 'http://www.google.com/schemas/sitemap-image/1.1', 'xmlns:video' => 'http://www.google.com/schemas/sitemap-video/1.1' do
xml << (render :partial => 'sitemap/common', pages: @pages)
xml << (render :partial => 'sitemap/products', items: @products)
end
and our partials:
# app/views/sitemap/_common.xml.builder
base_url = "http://#{request.host_with_port}/"
# pages = ['about.html', 'contacts.html' ]
pages.each do |page|
xml.url do
xml.loc base_url+page
end
end
# app/views/sitemap/_products.xml.builder
items.each do |item|
xml.url do
xml.loc product_path(item)
end
end