module Resync::XML

Helper methods and modules related to reading and writing XML.

Public Class Methods

element(xml) click to toggle source

Extracts a REXML::Element from the specified object.

@param xml [String, IO, REXML::Document, REXML::Element] A string or IO-like

object containing an XML document (with or without XML declaration), or an
XML document, or an XML element.

@return [REXML::Element] the root element of the document, or the element

itself if +xml+ is already an element.
# File lib/resync/xml.rb, line 33
def self.element(xml)
  case xml
  when REXML::Document
    xml.root
  when REXML::Element
    xml
  else
    raise ArgumentError, "Unexpected argument type; expected XML document, String, or IO source, was #{xml.class}" unless can_parse(xml)
    REXML::Document.new(xml).root
  end
end
to_uri(url) click to toggle source

Ensures that the provided value is a URI, parsing it if necessary.

@param url [URI, String] the URI. @raise [URI::InvalidURIError] if url cannot be converted to a URI.

# File lib/resync/xml.rb, line 19
def self.to_uri(url)
  return nil unless url
  return url if url.is_a? URI
  stripped = url.respond_to?(:strip) ? url.strip : url.to_s.strip
  URI.parse(stripped)
end

Private Class Methods

can_parse(arg) click to toggle source

Whether the argument can be parsed as an REXML::Document

@return [Boolean] true if +REXML::Document.new()+ should be able to parse

the argument, false otherwise
# File lib/resync/xml.rb, line 52
def self.can_parse(arg)
  arg.is_a?(String) ||
    (arg.respond_to?(:read) &&
        arg.respond_to?(:readline) &&
        arg.respond_to?(:nil?) &&
        arg.respond_to?(:eof?))
end