To simply add XML sitemap generation to a Ruby program or script the sitemap-generator gem is all one needs. However the documentation for the library is quite heavy and filtering out what's needed to incorporate its functionality into a simple script can take a while. But really all it takes is this:
gem install sitemap-generator
vim sm-gen.rb
001 # sm-gen.rb
002 require 'sitemap-generator'
003
004 # optional for verbose output
005 SitemapGenerator.verbose = true
006 SitemapGenerator::Sitemap.verbose = true
007
008 # required
009 SitemapGenerator::Sitemap.default_host = 'http://www.example.com'
010 SitemapGenerator::Sitemap.public_path = '.'
011
012 SitemapGenerator::Sitemap.create do
013 # for each url, adjust as needed
014 # creates an entry for http://www.example.com/example/url/index.html
015 add 'example/url/index.html', :changefreq => 'monthly',
016 :lastmod => File.mtime(path).strftime("%FT%T%:z"),
017 :priority => 1.0
018 end
Where public_path
defines the directory, relative to the script's working directory, where the generated sitemap should be placed. The script might produce an index for a bunch of sitemaps. Regardless of the behavior, by default the file to add to robots.txt
and search engines is always sitemap.xml.gz
.
To build the sitemap run
ruby sm-gen.rb
The sitemap-generator
gem can do a lot more though. See the documentation linked above.