Module: Nanoc::Helpers::XMLSitemap

Defined in:
lib/nanoc/helpers/xml_sitemap.rb

Overview

Instance Method Summary collapse

Instance Method Details

#xml_sitemap(params = {}) ⇒ String

Parameters:

  • params (Hash) (defaults to: {})

    a customizable set of options

Options Hash (params):

  • :items (Array)
  • :rep_select (Proc)

Returns:

  • (String)


10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/nanoc/helpers/xml_sitemap.rb', line 10

def xml_sitemap(params = {})
  require 'builder'

  # Extract parameters
  items       = params.fetch(:items) { @items.reject { |i| i[:is_hidden] } }
  select_proc = params.fetch(:rep_select, nil)

  # Create builder
  buffer = +''
  xml = Builder::XmlMarkup.new(target: buffer, indent: 2)

  # Check for required attributes
  if @config[:base_url].nil?
    raise 'The Nanoc::Helpers::XMLSitemap helper requires the site configuration to specify the base URL for the site.'
  end

  # Build sitemap
  xml.instruct!
  xml.urlset(xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9') do
    # Add item
    items.sort_by(&:identifier).each do |item|
      reps = item.reps.select(&:path)
      reps.select! { |r| select_proc[r] } if select_proc
      reps.sort_by { |r| r.name.to_s }.each do |rep|
        xml.url do
          xml.loc Addressable::URI.escape(@config[:base_url] + rep.path)
          xml.lastmod item[:mtime].__nanoc_to_iso8601_date unless item[:mtime].nil?
          xml.changefreq item[:changefreq] unless item[:changefreq].nil?
          xml.priority item[:priority] unless item[:priority].nil?
        end
      end
    end
  end

  # Return sitemap
  buffer
end