Class: XmlSitemap::Index

Inherits:
Object
  • Object
show all
Defined in:
lib/xml-sitemap/index.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) {|_self| ... } ⇒ Index

Initialize a new Index instance

opts - Index options

opts - Force HTTPS for all items. (default: false)

Yields:

  • (_self)

Yield Parameters:


11
12
13
14
15
16
17
# File 'lib/xml-sitemap/index.rb', line 11

def initialize(opts={})
  @maps     = []
  @offsets  = Hash.new(0)
  @secure   = opts[:secure] || false
  
  yield self if block_given?
end

Instance Attribute Details

#mapsObject (readonly)

Returns the value of attribute maps


3
4
5
# File 'lib/xml-sitemap/index.rb', line 3

def maps
  @maps
end

Instance Method Details

#add(map, use_offsets = true) ⇒ Object

Add map object to index

map - XmlSitemap::Map instance

Raises:

  • (ArgumentError)

23
24
25
26
27
28
29
30
31
32
# File 'lib/xml-sitemap/index.rb', line 23

def add(map, use_offsets=true)
  raise ArgumentError, 'XmlSitemap::Map object required!' unless map.kind_of?(XmlSitemap::Map)
  raise ArgumentError, 'Map is empty!' if map.empty?
  
  @maps << {
    :loc     => use_offsets ? map.index_url(@offsets[map.group], @secure) : map.plain_index_url(@secure),
    :lastmod => map.created_at.utc.iso8601
  }
  @offsets[map.group] += 1
end

#renderObject

Generate sitemap XML index


36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/xml-sitemap/index.rb', line 36

def render
  xml = Builder::XmlMarkup.new(:indent => 2)
  xml.instruct!(:xml, :version => '1.0', :encoding => 'UTF-8')
  xml.sitemapindex(XmlSitemap::INDEX_SCHEMA_OPTIONS) { |s|
    @maps.each do |item|
      s.sitemap do |m|
        m.loc        item[:loc]
        m.lastmod    item[:lastmod]
      end
    end
  }.to_s
end

#render_to(path, options = {}) ⇒ Object

Render XML sitemap index into the file

path - Output filename options - Options hash

options - Overwrite file contents (default: true)


56
57
58
59
60
61
62
63
64
65
# File 'lib/xml-sitemap/index.rb', line 56

def render_to(path, options={})
  overwrite = options[:overwrite] || true
  path = File.expand_path(path)
  
  if File.exists?(path) && !overwrite
    raise RuntimeError, "File already exists and not overwritable!"
  end
  
  File.open(path, 'w') { |f| f.write(self.render) }
end