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
Have taken a look to Dynamic Site Maps Gem this is really simple to set up just read the read me in the Github for more features you can also look at Site Map Generator gem
Wish you the best of luck
try like this
Controller
class SitemapController < ApplicationController
layout nil
def index
@static_pages = [jobs_url, advertising_url, join_url]
@offers = Offer.all
respond_to do |format|
format.xml
end
end
end
View
xml.instruct!
xml.urlset(
) do
@static_pages.each do |page|
xml.url do
xml.loc "#{page}"
xml.changefreq("monthly")
end
end
@offers.each do |offer|
xml.url do
xml.loc
xml.changefreq("daily")
end
end
end
Route
get 'sitemap.xml', :to => 'sitemap#index', :defaults => { :format => 'xml' }
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