Rails Integration

The Railtie loads automatically when Rails is present. It wires two things:

  1. URL helperss.route.<helper> inside process blocks.
  2. No other magic — no initializer, no autoloaded directories, no patched generators.

URL helpers in processes

config/sitemap.rb
SiteMaps.use(:file_system) do
configure do |config|
config.url = 'https://example.com/sitemap.xml'
config.directory = Rails.public_path.to_s
end
process do |s|
s.add(s.route.root_path, priority: 1.0)
s.add(s.route.about_path)
Post.find_each { |p| s.add(s.route.post_path(p), lastmod: p.updated_at) }
end
end

s.route is a singleton wrapping Rails.application.routes.url_helpers.

Generating from Rails

One-off

Terminal window
bundle exec site_maps generate --config-file config/sitemap.rb

The CLI auto-requires config/environment.rb if it finds a config/application.rb, so ActiveRecord, URL helpers, and everything else loads as normal.

From a Rake task

lib/tasks/sitemap.rake
namespace :sitemap do
desc 'Generate sitemaps'
task generate: :environment do
runner = SiteMaps.generate(config_file: Rails.root.join('config/sitemap.rb').to_s)
runner.enqueue_all.run
end
end

Run on deploy or via cron:

Terminal window
bundle exec rake sitemap:generate

From a scheduled job

class SitemapJob < ApplicationJob
def perform
runner = SiteMaps.generate(config_file: Rails.root.join('config/sitemap.rb').to_s)
runner.enqueue_all.run
end
end
SitemapJob.set(cron: '0 3 * * *').perform_later

Serving generated sitemaps

Add the Rack middleware to serve files generated by the :file_system adapter:

config/application.rb
config.middleware.use SiteMaps::Middleware, adapter: -> { SiteMaps.current_adapter }

See middleware.md for options.

Asset precompile integration

If you want sitemaps regenerated on every deploy, hook into assets:precompile:

lib/tasks/sitemap.rake
Rake::Task['assets:precompile'].enhance(['sitemap:generate'])

robots.txt

<%# public/robots.txt.erb or app/views/robots.text.erb %>
User-agent: *
Disallow: /admin
<%= SiteMaps::RobotsTxt.sitemap_directive('https://example.com/sitemap.xml') %>

Multi-tenant

SiteMaps.define gives you a generation function parameterized by runtime context:

config/sitemap.rb
SiteMaps.define do |tenant:|
use(:file_system) do
configure do |config|
config.url = "https://#{tenant.domain}/sitemap.xml"
config.directory = tenant.public_path
end
process { |s| tenant.pages.each { |page| s.add(page.path, lastmod: page.updated_at) } }
end
end
Tenant.find_each do |tenant|
SiteMaps.generate(config_file: 'config/sitemap.rb', context: { tenant: tenant }).enqueue_all.run
end

The context hash is splatted into the define block as keyword args.

Dependencies

  • Rails is not listed in the gemspec. The Railtie is loaded only if Rails is already present. If you’re using site_maps in a non-Rails Ruby project, the Rails-specific pieces are inert.