lib/massive_sitemap/builder/base.rb in massive_sitemap-2.0.0.rc4 vs lib/massive_sitemap/builder/base.rb in massive_sitemap-2.0.0.rc5
- old
+ new
@@ -1,5 +1,8 @@
+# MassiveSitemap Builder
+# The purpose of a builder is create the XML files: continaing header and all other tag (with attributes).
+#
module MassiveSitemap
module Builder
class Base
OPTS = {
@@ -17,33 +20,33 @@
def initialize(writer, options = {}, &block)
@writer = writer
@options = self.class::OPTS.merge(options)
@opened_tags = []
- if block
- instance_eval(&block)
- close!
- end
+ process(&block)
end
+ # alias for .new
def self.generate(writer, options = {}, &block)
self.new(writer, options, &block)
end
+ # add url, prefix with given base_url
def add(path, attrs = {})
add_url! ::File.join(url, path), attrs
- rescue MassiveSitemap::Writer::File::FileExistsException => e
- # don't fail here
end
- def init!(&block)
+ # implicitly called by add_url!, call explicitly to check if writer can be used
+ def init_writer!(writer_options = {}, &block)
unless @writer.inited?
- @writer.init!
- header!(&block)
+ @writer.init!(writer_options)
+ header!
end
+ process(&block)
end
+ # close a tag, if last one, close writer too
def close!(indent = true)
if name = @opened_tags.pop
@writer.print "\n" + ' ' * @options[:indent_by] * @opened_tags.size if indent
@writer.print "</#{name}>"
if @opened_tags.size == 0
@@ -58,11 +61,11 @@
@writer.print '<?xml version="1.0" encoding="UTF-8"?>'
tag! self.class::HEADER_NAME, self.class::HEADER_ATTRIBUTES, &block
end
def add_url!(location, attrs = {})
- init!
+ init_writer!
tag! 'url' do
tag! 'loc', location
tag! 'lastmod', attrs[:last_modified].utc.strftime('%Y-%m-%dT%H:%M:%S+00:00') if attrs[:last_modified]
tag! 'changefreq', attrs[:change_frequency] if attrs[:change_frequency]
@@ -75,14 +78,11 @@
open!(name, attrs)
if content.is_a? String
@writer.print content.gsub('&', '&')
close!(false)
else
- if block
- instance_eval(&block)
- close!
- end
+ process(&block)
end
end
def open!(name, attrs = {})
attrs = attrs.map { |attr, value| %Q( #{attr}="#{value}") }.join('')
@@ -90,9 +90,16 @@
@opened_tags << name
@writer.print "<#{name}#{attrs}>"
end
private
+ def process(&block)
+ if block
+ instance_eval(&block)
+ close!
+ end
+ end
+
def url
schema, host = @options[:url].scan(/^(https?:\/\/)?(.+?)\/?$/).flatten
"#{schema || 'http://'}#{host}/"
rescue
""