Created
August 23, 2010 21:56
-
-
Save peleteiro/546422 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "nokogiri" | |
class SitemapBuilder | |
attr_reader :root | |
def initialize | |
@urls = Array.new | |
@root = File.expand_path("public", Rails.root) | |
Dir[File.join(root, "sitemap*")].each{|f| FileUtils.rm f} | |
end | |
def add(url) | |
@urls << url | |
end | |
def save(domain, name, defaults = {}) | |
defaults.reverse_merge!(:changefreq => 'monthly', :priority => 0.5, :lastmod => DateTime.now.utc.xmlschema) | |
urls_groups = @urls.in_groups_of(50000) | |
urls_groups.each_with_index do |urls, i| | |
urls.compact! | |
sitemap = Nokogiri::XML::Builder.new do |xml| | |
xml.urlset(:xmlns => "http://www.sitemaps.org/schemas/sitemap/0.9") do | |
urls.each do |url| | |
url = url.reverse_merge(defaults) | |
xml.url do | |
xml.loc "http://#{domain}#{url[:loc]}" | |
xml.lastmod url[:lastmod] | |
xml.changefreq url[:changefreq] | |
xml.priority url[:priority] | |
end | |
end | |
end | |
end | |
Zlib::GzipWriter.open(File.expand_path("public/sitemap-#{name}-#{i}.xml.gz", Rails.root)) do |file| | |
file << sitemap.to_xml | |
end | |
end | |
sitemap_index = Nokogiri::XML::Builder.new do |xml| | |
xml.sitemapindex(:xmlns => "http://www.sitemaps.org/schemas/sitemap/0.9") do | |
urls_groups.length.times do |i| | |
xml.sitemap do | |
xml.loc "http://#{domain}/sitemap-#{name}-#{i}.xml.gz" | |
xml.lastmod DateTime.now.utc.xmlschema | |
end | |
end | |
end | |
end | |
File.open(File.expand_path("public/sitemap-#{name}.xml", Rails.root), "w") do |file| | |
file << sitemap_index.to_xml | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment