class SimpleSitemapGenerator::Generator

Attributes

additional_paths[RW]
default_changefreq[RW]
default_lastmod[RW]
default_priority[RW]
host[RW]
inappropriate_paths[RW]
options[RW]

Public Class Methods

new() click to toggle source
# File lib/simple_sitemap_generator.rb, line 19
def initialize
  @default_changefreq = 'daily'
  @default_priority = 0.5
  @inappropriate_paths = [
    /:/,  # ignore paths like 'users/:id', 'pages/:page'
    /sitemap\.xml/,
  ]
  @host = ''
  @options = {}
  @additional_paths = []
end

Public Instance Methods

generate_xml() click to toggle source
# File lib/simple_sitemap_generator.rb, line 7
def generate_xml
  paths.map { |path| {
      loc: @host + path,
      lastmod: @options[path.to_sym]&.[](:lastmod) || @default_lastmod,
      changefreq: @options[path.to_sym]&.[](:changefreq) || @default_changefreq,
      priority: @options[path.to_sym]&.[](:priority) || @default_priority,
    }.compact }
    .to_xml(root: 'url', skip_types: true)
    .gsub(default_root_start_tag, root_start_tag)
    .gsub(default_root_end_tag, root_end_tag)
end

Private Instance Methods

default_root_end_tag() click to toggle source
# File lib/simple_sitemap_generator.rb, line 37
def default_root_end_tag
  "\n</url>\n"
end
default_root_start_tag() click to toggle source
# File lib/simple_sitemap_generator.rb, line 33
def default_root_start_tag
  "\n<url>\n"
end
inappropriate_path?(path) click to toggle source
# File lib/simple_sitemap_generator.rb, line 41
def inappropriate_path?(path)
  inappropriate_paths.map { |x| path.match(x).present? }.any?
end
paths() click to toggle source
# File lib/simple_sitemap_generator.rb, line 45
def paths
  paths = routes.select{ |route| route.verb == 'GET' }
    .reject{ |route| redirect_path?(route) }
    .map { |route| route.path.spec.to_s.gsub('(.:format)', '') }
    .reject{ |path| inappropriate_path?(path) }
    .uniq
  paths + additional_paths
end
redirect_path?(route) click to toggle source
# File lib/simple_sitemap_generator.rb, line 54
def redirect_path?(route)
  route.app.app.class.to_s == 'ActionDispatch::Routing::PathRedirect'
end
root_end_tag() click to toggle source
# File lib/simple_sitemap_generator.rb, line 66
def root_end_tag
  "\n</urlset>\n"
end
root_start_tag() click to toggle source
# File lib/simple_sitemap_generator.rb, line 62
def root_start_tag
  "\n<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n"
end
routes() click to toggle source
# File lib/simple_sitemap_generator.rb, line 58
def routes
  Rails.application.routes.routes
end