Class: DynamicSitemaps::IndexGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/dynamic_sitemaps/index_generator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sitemaps) ⇒ IndexGenerator

Initialize the class with an array of SitemapResult



6
7
8
# File 'lib/dynamic_sitemaps/index_generator.rb', line 6

def initialize(sitemaps)
  @sitemaps = sitemaps
end

Instance Attribute Details

#sitemapsObject (readonly)

Array of sitemap results



3
4
5
# File 'lib/dynamic_sitemaps/index_generator.rb', line 3

def sitemaps
  @sitemaps
end

Instance Method Details

#generateObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/dynamic_sitemaps/index_generator.rb', line 10

def generate
  sitemaps.group_by(&:folder).each do |folder, sitemaps|
    index_path = "#{DynamicSitemaps.temp_path}/#{folder}/#{DynamicSitemaps.index_file_name}"

    if !DynamicSitemaps.always_generate_index && sitemaps.count == 1 && sitemaps.first.files.count == 1
      file_path = "#{DynamicSitemaps.temp_path}/#{folder}/#{sitemaps.first.files.first}"
      FileUtils.copy file_path, index_path
      File.delete file_path
    else
      File.open(index_path, "w") do |file|
        write_beginning(file)
        write_sitemaps(file, sitemaps)
        write_end(file)
      end
    end
  end
end

#write_beginning(file) ⇒ Object



28
29
30
31
# File 'lib/dynamic_sitemaps/index_generator.rb', line 28

def write_beginning(file)
  file.puts '<?xml version="1.0" encoding="UTF-8"?>',
            '<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'
end

#write_end(file) ⇒ Object



43
44
45
# File 'lib/dynamic_sitemaps/index_generator.rb', line 43

def write_end(file)
  file.puts '</sitemapindex>'
end

#write_sitemaps(file, sitemaps) ⇒ Object



33
34
35
36
37
38
39
40
41
# File 'lib/dynamic_sitemaps/index_generator.rb', line 33

def write_sitemaps(file, sitemaps)
  sitemaps.each do |sitemap|
    sitemap.files.each do |file_name|
      file.puts '<sitemap>',
                "<loc>http://#{sitemap.host}/#{sitemap.folder}/#{file_name}</loc>",
                '</sitemap>'
    end
  end
end