Module: FormattedString::Formats::Xml

Defined in:
lib/formatted_string/formats/xml.rb

Constant Summary collapse

XML_OPTIONS =
{
  :include_key => :attribute, # Can be false, :element, or :attribute
  :report_nil => true, # Sets an attribute nil="true" on elements that are nil, so that the reader doesn't read as an empty string
  :key_name => 'id', # Default key name
}

Instance Method Summary collapse

Instance Method Details

#===(other) ⇒ Object



127
128
129
# File 'lib/formatted_string/formats/xml.rb', line 127

def ===(other)
  to_hash == other.to_hash
end

#to_hash(options = {}) ⇒ Object



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# File 'lib/formatted_string/formats/xml.rb', line 131

def to_hash(options={})
  options = XML_OPTIONS.merge(options)

  stack = []
  parser = REXML::Parsers::BaseParser.new(self)

  while true
    event = parser.pull
    case event[0]
    when :end_document
      break
    when :end_doctype, :start_doctype
      # do nothing
    when :start_element
      stack.push REXMLUtilityNode.new(event[1], event[2])
    when :end_element
      if stack.size > 1
        temp = stack.pop
        stack.last.add_node(temp)
      end
    when :text, :cdata
      stack.last.add_node(event[1]) unless event[1].strip.length == 0
    end
  end
  data = stack.pop
  data = data.to_hash if data.respond_to?(:to_hash)

  # Turn any {} || {"nil" => "true"} into just nil
  if data.respond_to?(:crawl) # basically, is it a hash or nil?
    if options[:report_nil]
      data.crawl {|h,k,v| h[k] = nil if v == {} || v == {'nil' => 'true'}; v}
    else
      data.crawl {|h,k,v| h[k] = nil if v == {}; v}
    end
  end
  data
end