Class: Peanuts::XML::LibXML::Writer

Inherits:
Writer
  • Object
show all
Defined in:
lib/peanuts/xml/libxml.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{}

Instance Method Summary collapse

Methods inherited from Writer

new

Constructor Details

#initialize(dest, options = {}) ⇒ Writer

Returns a new instance of Writer.



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/peanuts/xml/libxml.rb', line 20

def initialize(dest, options = {})
  @dest = case dest
  when :string
    ''
  when :document
    ::LibXML::XML::Document.new
  when ::LibXML::XML::Document
    dest
  else
    raise ArgumentError, "unsupported destination #{dest.inspect}" unless dest.respond_to?(:<<)
    dest
  end
  @options = LibXML.libxml_opt(options, DEFAULT_OPTIONS)
end

Instance Method Details

#resultObject



35
36
37
# File 'lib/peanuts/xml/libxml.rb', line 35

def result
  @dest
end

#write(node_type, local_name = nil, namespace_uri = nil, prefix = nil) {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/peanuts/xml/libxml.rb', line 54

def write(node_type, local_name = nil, namespace_uri = nil, prefix = nil)
  case node_type
  when :element
    @node = ::LibXML::XML::Node.new(local_name)
    @parent << @node if @parent
    if namespace_uri || prefix
      unless namespace_uri
        defns = @node.namespaces.default
        namespace_uri = defns ? defns.href : ''
      end
      @node.namespaces.namespace = mkns(@node, namespace_uri, prefix)
    end
  when :attribute
    @node = ::LibXML::XML::Attr.new(@parent, local_name, '', namespace_uri && mkns(@parent, namespace_uri, prefix))
  else
    raise "unsupported node type #{node_type.inspect}"
  end

  exparent, @parent = @parent, @node

  yield self

  if exparent.nil?
    case @dest
    when ::LibXML::XML::Document
      @dest.root = @parent
    else
      @dest << @parent.to_s(@options)
    end
  end

  @parent = exparent
end

#write_namespaces(namespaces) ⇒ Object



48
49
50
51
52
# File 'lib/peanuts/xml/libxml.rb', line 48

def write_namespaces(namespaces)
  for prefix, uri in namespaces
    mkns(@node, uri, prefix)
  end
end

#write_value(value) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/peanuts/xml/libxml.rb', line 39

def write_value(value)
  case @node
  when ::LibXML::XML::Attr
    @node.value = value || ''
  else
    @node.content = value || ''
  end
end