Skip to content

Instantly share code, notes, and snippets.

@Achillefs
Created October 26, 2011 17:21
Show Gist options
  • Save Achillefs/1317062 to your computer and use it in GitHub Desktop.
Save Achillefs/1317062 to your computer and use it in GitHub Desktop.
Sitemap Generator
class SitemapGenerator
# For Rails 3.*, replace with include Rails.application.routes.url_helper
include ActionController::UrlWriter
def initialize model_name, options = {}
@host = options.delete(:host) || default_url_options[:host]
@model_name = model_name
@file = options.delete(:file) || model_name.to_s.pluralize
@changefreq = options.delete(:changefreq) || 'daily'
@lastmod = options.delete(:lastmod_method) || :updated_at
@priority = options.delete(:priority) || '0.5'
@sitemap_path = File.join(RAILS_ROOT,"public","#{@file}.xml")
@compress = options.delete(:compress) || false
end
def generate
File.open(@sitemap_path,"w") do |f|
f.write(%[<?xml version="1.0" encoding="UTF-8"?>\n])
f.write(%[<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n])
@model_name.camelize.constantize.all.each do |item|
f.write %[<url><loc><![CDATA[#{send(:"#{@model_name}_url",item, :host => @host)}]]></loc><lastmod>#{item.send(@lastmod).utc.strftime("%Y-%m-%dT%H:%M:%S+00:00")}</lastmod><changefreq>#{@changefreq}</changefreq><priority>#{@priority}</priority></url>\n]
end
f.write(%[</urlset>])
end
`gzip -f #{@sitemap_path}` if @compress
end
class << self
def generate model_name, options = {}
generator = new(model_name, options)
generator.generate
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment