As a beginner to rails, I\'m finding the generation of sitemaps on Heroku to be extremely daunting due to its read-only limitations. However, a sitemap is fundamental to my webs
I figured out a small trick that makes it possible to dynamically generate the sitemap file but persist it for later calls on Heroku.
It works great for small\medium size projects, if you have a big\huge project and thousand of pages that changes endlessly , please consider using S3 to store the sitemap file.
Those are the steps:
use the sitemap_generator
gem as instructed here https://github.com/kjvarga/sitemap_generator
after bundle
, run rake sitemap:install
, it will create a config/sitemap.rb file for you
edit the config/sitemap.rb file to look like this
SitemapGenerator::Sitemap.default_host = [your host name goes here]
SitemapGenerator::Sitemap.public_path = File.join(Rails.root, 'tmp').to_s
SitemapGenerator::Sitemap.compress = false
SitemapGenerator::Sitemap.create do
[all your site pages add commands goes here]
end
"#{ENV['HOST_PROTOCOL']}://#{ENV['HOST_NAME']}"
(and of course add the appropriate environment variables) so you could change it on different environments.create your sitemap controller file - app/controllers/sitemap_controller.rb
Edit the sitemap controller file to look like this
require 'rake'
class SitemapController < ApplicationController
def index
file_name = File.join(Rails.root, 'tmp', 'sitemap.xml').to_s
unless File.exist?(file_name)
Rails.application.load_tasks
Rake::Task['sitemap:refresh:no_ping'].invoke
end
# it's better to be safe than sorry
if File.exist?(file_name)
respond_to do |format|
format.xml { render file: file_name }
end
else
render file: 'public/404.html', status: :not_found, layout: false
end
end
end
resources :sitemap, only: %i[index], constraints: ->(req) { req.format == :xml }
Enjoy