Class: Factbase::ToXML

Inherits:
Object
  • Object
show all
Defined in:
lib/factbase/to_xml.rb

Overview

Factbase to XML converter.

This class helps converting an entire Factbase to YAML format, for example:

require 'factbase/to_xml'
fb = Factbase.new
puts Factbase::ToXML.new(fb).xml
Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2024 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Constructor Details

#initialize(fb, sorter = '_id') ⇒ ToXML

Constructor.



40
41
42
43
# File 'lib/factbase/to_xml.rb', line 40

def initialize(fb, sorter = '_id')
  @fb = fb
  @sorter = sorter
end

Instance Method Details

#xmlString

Convert the entire factbase into XML.

Returns:

  • (String)

    The factbase in XML format



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/factbase/to_xml.rb', line 47

def xml
  bytes = @fb.export
  maps = Marshal.load(bytes)
  meta = {
    version: Factbase::VERSION,
    size: bytes.size
  }
  Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
    xml.fb(meta) do
      maps.sort_by { |m| m[@sorter] }.each do |m|
        xml.f_ do
          m.sort.to_h.each do |k, vv|
            if vv.is_a?(Array)
              xml.send(:"#{k}_") do
                vv.each do |v|
                  xml.send(:v, to_str(v))
                end
              end
            else
              xml.send(:"#{k}_", to_str(vv))
            end
          end
        end
      end
    end
  end.to_xml
end