Class: SmartXmlLogger

Inherits:
Object
  • Object
show all
Defined in:
lib/reactor/tools/smart_xml_logger.rb

Instance Method Summary collapse

Constructor Details

#initialize(forward_to, method = nil) ⇒ SmartXmlLogger

Returns a new instance of SmartXmlLogger.



4
5
6
7
# File 'lib/reactor/tools/smart_xml_logger.rb', line 4

def initialize(forward_to, method = nil)
  @logger = forward_to
  @method = method
end

Instance Method Details

#configure(key, options) ⇒ Object



9
10
11
12
# File 'lib/reactor/tools/smart_xml_logger.rb', line 9

def configure(key, options)
  @configuration ||= {}
  @configuration[key] = options
end

#log(text) ⇒ Object



14
15
16
17
18
# File 'lib/reactor/tools/smart_xml_logger.rb', line 14

def log(text)
  return unless @logger

  @logger.send(@method, text)
end

#log_xml(key, xml) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/reactor/tools/smart_xml_logger.rb', line 20

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



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/reactor/tools/smart_xml_logger.rb', line 38

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