Module: XML::Mapping

Defined in:
lib/xml/mapping_extensions.rb

Defined Under Namespace

Modules: ClassMethods Classes: Node

Instance Method Summary collapse

Instance Method Details

#write_to_file(path, indent: -1,, pretty: false, options: { mapping: :_default })

Writes this mapped object to the specified file, as an XML document (including declaration).

Parameters:

  • path (String)

    The path of the file to write to

  • indent (Integer) (defaults to: -1,)

    The indentation level. Defaults to -1 (no indenting). Note that this parameter will be ignored if pretty is present.

  • pretty (Boolean) (defaults to: false)

    Whether to pretty-print the output. Defaults to false. Note that this option overrides indent.

  • options (Hash) (defaults to: { mapping: :_default })

    the options to be passed to XML::Mapping#save_to_xml



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/xml/mapping_extensions.rb', line 60

def write_to_file(path, indent: -1, pretty: false, options: { mapping: :_default })
  doc = REXML::Document.new
  doc << REXML::XMLDecl.new
  doc.elements[1] = save_to_xml(options)
  File.open(path, 'w') do |f|
    return doc.write(f, indent) unless pretty
    formatter = REXML::Formatters::Pretty.new
    formatter.compact = true
    formatter.write(doc, f)
  end
end

#write_xml(options = { mapping: :_default }) ⇒ String

Writes this mapped object as a pretty-printed XML string.

Parameters:

Returns:

  • (String)

    the XML form of the object, as a compact, pretty-printed string.



42
43
44
45
46
47
48
49
# File 'lib/xml/mapping_extensions.rb', line 42

def write_xml(options = { mapping: :_default })
  xml = save_to_xml(options)
  formatter = REXML::Formatters::Pretty.new
  formatter.compact = true
  io = ::StringIO.new
  formatter.write(xml, io)
  io.string
end