Sha256: d74ee880669e7aac2c4516ff4d336fe663fac7f664a76a0c50edb20f65f5c653
Contents?: true
Size: 1.38 KB
Versions: 8
Compression:
Stored size: 1.38 KB
Contents
require "nokogiri" class SmartXmlLogger def initialize(forward_to, method = nil) @logger = forward_to @method = method end def configure(key, options) @configuration ||= {} @configuration[key] = options end def log(text) return unless @logger @logger.send(@method, text) end def log_xml(key, xml) return unless @logger options = @configuration[key] dom = Nokogiri::XML::Document.parse(xml) node_set = options[:xpath] ? dom.xpath(options[:xpath]) : dom log(if node_set.respond_to?(:each) node_set.map { |node| print_node(node, options[:start_indent] || 0) }.join else print_node(node_set, options[:start_indent] || 0) end) end # private def print_node(node, indent = 0) return "" if node.text? empty = node.children.empty? has_text = node.children.detect { |child| child.text? } out = " " * indent attrs = node.attributes.values.map { |attr| %(#{attr.name}="#{attr.value}") }.join(" ") attrs = " #{attrs}" if attrs.present? out << "<#{node.name}#{attrs}#{"/" if empty}>" out << if has_text node.text.to_s else "\n" end node.children.each do |child| out << print_node(child, indent + 2) end out << " " * indent unless has_text || empty out << "</#{node.name}>\n" unless empty out end end
Version data entries
8 entries across 8 versions & 1 rubygems