Class: BetterSeo::Sitemap::SitemapIndex

Inherits:
Object
  • Object
show all
Defined in:
lib/better_seo/sitemap/sitemap_index.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSitemapIndex

Returns a new instance of SitemapIndex.



11
12
13
# File 'lib/better_seo/sitemap/sitemap_index.rb', line 11

def initialize
  @sitemaps = []
end

Instance Attribute Details

#sitemapsObject (readonly)

Returns the value of attribute sitemaps.



9
10
11
# File 'lib/better_seo/sitemap/sitemap_index.rb', line 9

def sitemaps
  @sitemaps
end

Instance Method Details

#add_sitemap(loc, lastmod: nil) ⇒ Object

Add a sitemap to the index



16
17
18
19
20
21
# File 'lib/better_seo/sitemap/sitemap_index.rb', line 16

def add_sitemap(loc, lastmod: nil)
  sitemap = { loc: loc }
  sitemap[:lastmod] = format_date(lastmod) if lastmod
  @sitemaps << sitemap
  self
end

#to_xmlObject

Generate XML for sitemap index



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/better_seo/sitemap/sitemap_index.rb', line 24

def to_xml
  xml = []
  xml << '<?xml version="1.0" encoding="UTF-8"?>'
  xml << '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'

  @sitemaps.each do |sitemap|
    xml << "  <sitemap>"
    xml << "    <loc>#{escape_xml(sitemap[:loc])}</loc>"
    xml << "    <lastmod>#{sitemap[:lastmod]}</lastmod>" if sitemap[:lastmod]
    xml << "  </sitemap>"
  end

  xml << "</sitemapindex>"
  xml.join("\n")
end

#write_to_file(path) ⇒ Object

Write sitemap index to file



41
42
43
44
45
46
# File 'lib/better_seo/sitemap/sitemap_index.rb', line 41

def write_to_file(path)
  directory = File.dirname(path)
  FileUtils.mkdir_p(directory) unless File.directory?(directory)

  File.write(path, to_xml)
end